FindGo.cmake 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # SPDX-License-Identifier: GPL-3.0-or-later
  2. #
  3. # Custom CMake module to find the Go toolchain
  4. #
  5. # This is a relatively orthodox CMake Find Module. It can be used by
  6. # simply including it and then invoking `find_package(Go)`.
  7. #
  8. # Version handling is done by CMake itself via the
  9. # find_package_handle_standard_args() function, so `find_package(Go 1.21)`
  10. # will also work correctly.
  11. if(GO_FOUND)
  12. return()
  13. endif()
  14. # The complexity below is needed to account for the complex rules we use for finding the Go install.
  15. #
  16. # If GOROOT is set, we honor that. Otherwise, we check known third-party install paths for the platform in question
  17. # and fall back to looking in PATH. For the specific case of MSYS2, we prefer a Windows install over an MSYS2 install.
  18. if(DEFINED $ENV{GOROOT})
  19. find_program(GO_EXECUTABLE go PATHS "$ENV{GOROOT}/bin" DOC "Go toolchain" NO_DEFAULT_PATH)
  20. set(GO_ROOT $ENV{GOROOT})
  21. elseif(OS_WINDOWS)
  22. if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
  23. find_program(GO_EXECUTABLE go PATHS C:/go/bin "C:/Program Files/go/bin" DOC "Go toolchain" NO_DEFAULT_PATH)
  24. else()
  25. find_program(GO_EXECUTABLE go PATHS /c/go/bin "/c/Program Files/go/bin" /mingw64/lib/go/bin /ucrt64/lib/go/bin /clang64/lib/go/bin DOC "Go toolchain" NO_DEFAULT_PATH)
  26. endif()
  27. else()
  28. find_program(GO_EXECUTABLE go PATHS /usr/local/go/bin DOC "Go toolchain" NO_DEFAULT_PATH)
  29. endif()
  30. find_program(GO_EXECUTABLE go DOC "Go toolchain")
  31. if (GO_EXECUTABLE)
  32. execute_process(
  33. COMMAND ${GO_EXECUTABLE} version
  34. OUTPUT_VARIABLE GO_VERSION_STRING
  35. RESULT_VARIABLE RESULT
  36. )
  37. if (RESULT EQUAL 0)
  38. string(REGEX MATCH "go([0-9]+\\.[0-9]+(\\.[0-9]+)?)" GO_VERSION_STRING "${GO_VERSION_STRING}")
  39. string(REGEX MATCH "([0-9]+\\.[0-9]+(\\.[0-9]+)?)" GO_VERSION_STRING "${GO_VERSION_STRING}")
  40. else()
  41. unset(GO_VERSION_STRING)
  42. endif()
  43. if(NOT DEFINED GO_ROOT)
  44. execute_process(
  45. COMMAND ${GO_EXECUTABLE} env GOROOT
  46. OUTPUT_VARIABLE GO_ROOT
  47. RESULT_VARIABLE RESULT
  48. )
  49. if(RESULT EQUAL 0)
  50. string(REGEX REPLACE "\n$" "" GO_ROOT "${GO_ROOT}")
  51. else()
  52. unset(GO_ROOT)
  53. endif()
  54. endif()
  55. endif()
  56. include(FindPackageHandleStandardArgs)
  57. find_package_handle_standard_args(
  58. Go
  59. REQUIRED_VARS GO_EXECUTABLE GO_ROOT
  60. VERSION_VAR GO_VERSION_STRING
  61. )