• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1if(ANDROID)
2  # Android-NDK CMake files reconfigure the path and so Go won't be found.
3  # However, ninja will still find them in $PATH if we just name them.
4  if(NOT GO_EXECUTABLE)
5    set(GO_EXECUTABLE "go")
6  endif()
7else()
8  find_program(GO_EXECUTABLE go)
9endif()
10
11if(NOT GO_EXECUTABLE)
12  message(FATAL_ERROR "Could not find Go")
13endif()
14
15function(go_executable dest package)
16  set(godeps "${PROJECT_SOURCE_DIR}/util/godeps.go")
17  if(NOT CMAKE_GENERATOR STREQUAL "Ninja")
18    # The DEPFILE parameter to add_custom_command only works with Ninja. Query
19    # the sources at configure time. Additionally, everything depends on go.mod.
20    # That affects what external packages to use.
21    #
22    # TODO(davidben): Starting CMake 3.20, it also works with Make. Starting
23    # 3.21, it works with Visual Studio and Xcode too.
24    execute_process(COMMAND ${GO_EXECUTABLE} run ${godeps} -format cmake
25                            -pkg ${package}
26                    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
27                    OUTPUT_VARIABLE sources
28                    RESULT_VARIABLE godeps_result)
29    add_custom_command(OUTPUT ${dest}
30                       COMMAND ${GO_EXECUTABLE} build
31                               -o ${CMAKE_CURRENT_BINARY_DIR}/${dest} ${package}
32                       WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
33                       DEPENDS ${sources} ${PROJECT_SOURCE_DIR}/go.mod)
34  else()
35    # Ninja expects the target in the depfile to match the output. This is a
36    # relative path from the build directory.
37    binary_dir_relative_path(${dest} target)
38
39    set(depfile "${CMAKE_CURRENT_BINARY_DIR}/${dest}.d")
40    add_custom_command(OUTPUT ${dest}
41                       COMMAND ${GO_EXECUTABLE} build
42                               -o ${CMAKE_CURRENT_BINARY_DIR}/${dest} ${package}
43                       COMMAND ${GO_EXECUTABLE} run ${godeps} -format depfile
44                               -target ${target} -pkg ${package} -out ${depfile}
45                       WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
46                       DEPENDS ${godeps} ${PROJECT_SOURCE_DIR}/go.mod
47                       DEPFILE ${depfile})
48  endif()
49endfunction()
50
51