David Benjamin | 8378dad | 2024-01-23 15:22:45 -0500 | [diff] [blame] | 1 | find_program(GO_EXECUTABLE go) |
David Benjamin | 261ec61 | 2023-01-29 16:34:48 -0500 | [diff] [blame] | 2 | if(NOT GO_EXECUTABLE) |
| 3 | message(FATAL_ERROR "Could not find Go") |
| 4 | endif() |
| 5 | |
| 6 | function(go_executable dest package) |
David Benjamin | 8c4ec3b | 2023-02-27 12:46:12 -0500 | [diff] [blame] | 7 | set(godeps "${PROJECT_SOURCE_DIR}/util/godeps.go") |
David Benjamin | 261ec61 | 2023-01-29 16:34:48 -0500 | [diff] [blame] | 8 | if(NOT CMAKE_GENERATOR STREQUAL "Ninja") |
| 9 | # The DEPFILE parameter to add_custom_command only works with Ninja. Query |
| 10 | # the sources at configure time. Additionally, everything depends on go.mod. |
| 11 | # That affects what external packages to use. |
| 12 | # |
| 13 | # TODO(davidben): Starting CMake 3.20, it also works with Make. Starting |
| 14 | # 3.21, it works with Visual Studio and Xcode too. |
| 15 | execute_process(COMMAND ${GO_EXECUTABLE} run ${godeps} -format cmake |
| 16 | -pkg ${package} |
| 17 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} |
| 18 | OUTPUT_VARIABLE sources |
| 19 | RESULT_VARIABLE godeps_result) |
| 20 | add_custom_command(OUTPUT ${dest} |
| 21 | COMMAND ${GO_EXECUTABLE} build |
| 22 | -o ${CMAKE_CURRENT_BINARY_DIR}/${dest} ${package} |
| 23 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} |
David Benjamin | 8c4ec3b | 2023-02-27 12:46:12 -0500 | [diff] [blame] | 24 | DEPENDS ${sources} ${PROJECT_SOURCE_DIR}/go.mod) |
David Benjamin | 261ec61 | 2023-01-29 16:34:48 -0500 | [diff] [blame] | 25 | else() |
| 26 | # Ninja expects the target in the depfile to match the output. This is a |
| 27 | # relative path from the build directory. |
David Benjamin | b0b1f9d | 2023-04-19 17:18:27 -0400 | [diff] [blame] | 28 | binary_dir_relative_path(${dest} target) |
David Benjamin | 261ec61 | 2023-01-29 16:34:48 -0500 | [diff] [blame] | 29 | |
| 30 | set(depfile "${CMAKE_CURRENT_BINARY_DIR}/${dest}.d") |
| 31 | add_custom_command(OUTPUT ${dest} |
| 32 | COMMAND ${GO_EXECUTABLE} build |
| 33 | -o ${CMAKE_CURRENT_BINARY_DIR}/${dest} ${package} |
| 34 | COMMAND ${GO_EXECUTABLE} run ${godeps} -format depfile |
| 35 | -target ${target} -pkg ${package} -out ${depfile} |
| 36 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} |
David Benjamin | 8c4ec3b | 2023-02-27 12:46:12 -0500 | [diff] [blame] | 37 | DEPENDS ${godeps} ${PROJECT_SOURCE_DIR}/go.mod |
David Benjamin | 261ec61 | 2023-01-29 16:34:48 -0500 | [diff] [blame] | 38 | DEPFILE ${depfile}) |
| 39 | endif() |
| 40 | endfunction() |
| 41 | |