FindGo.cmake 2.3 KB

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