master
cmake 66 lines 2.24 KB
Raw
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
12 if(GO_FOUND)
13 return()
14 endif()
15
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
34 if (GO_EXECUTABLE)
35 execute_process(
36 COMMAND ${GO_EXECUTABLE} version
37 OUTPUT_VARIABLE GO_VERSION_STRING
38 RESULT_VARIABLE RESULT
39 )
40 if (RESULT EQUAL 0)
41 string(REGEX MATCH "go([0-9]+\\.[0-9]+(\\.[0-9]+)?)" GO_VERSION_STRING "${GO_VERSION_STRING}")
42 string(REGEX MATCH "([0-9]+\\.[0-9]+(\\.[0-9]+)?)" GO_VERSION_STRING "${GO_VERSION_STRING}")
43 else()
44 unset(GO_VERSION_STRING)
45 endif()
46
47 if(NOT DEFINED GO_ROOT)
48 execute_process(
49 COMMAND ${GO_EXECUTABLE} env GOROOT
50 OUTPUT_VARIABLE GO_ROOT
51 RESULT_VARIABLE RESULT
52 )
53 if(RESULT EQUAL 0)
54 string(REGEX REPLACE "\n$" "" GO_ROOT "${GO_ROOT}")
55 else()
56 unset(GO_ROOT)
57 endif()
58 endif()
59 endif()
60
61 include(FindPackageHandleStandardArgs)
62 find_package_handle_standard_args(
63 Go
64 REQUIRED_VARS GO_EXECUTABLE GO_ROOT
65 VERSION_VAR GO_VERSION_STRING
66 )