FindEnvModules.cmake 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. FindEnvModules
  5. --------------
  6. Locate an environment module implementation and make commands available to
  7. CMake scripts to use them. This is compatible with both Lua-based Lmod
  8. and TCL-based EnvironmentModules.
  9. This module is intended for the use case of setting up the compiler and library
  10. environment within a :ref:`CTest Script <CTest Script>` (``ctest -S``). It can
  11. also be used in a :ref:`CMake Script <Script Processing Mode>` (``cmake -P``).
  12. .. note::
  13. The loaded environment will not survive past the end of the calling process.
  14. Do not use this module in project code (``CMakeLists.txt`` files) to load
  15. a compiler environment; it will not be available during the build. Instead
  16. load the environment manually before running CMake or using the generated
  17. build system.
  18. Example Usage
  19. ^^^^^^^^^^^^^
  20. .. code-block:: cmake
  21. set(CTEST_BUILD_NAME "CrayLinux-CrayPE-Cray-dynamic")
  22. set(CTEST_BUILD_CONFIGURATION Release)
  23. set(CTEST_BUILD_FLAGS "-k -j8")
  24. set(CTEST_CMAKE_GENERATOR "Unix Makefiles")
  25. ...
  26. find_package(EnvModules REQUIRED)
  27. env_module(purge)
  28. env_module(load modules)
  29. env_module(load craype)
  30. env_module(load PrgEnv-cray)
  31. env_module(load craype-knl)
  32. env_module(load cray-mpich)
  33. env_module(load cray-libsci)
  34. set(ENV{CRAYPE_LINK_TYPE} dynamic)
  35. ...
  36. Result Variables
  37. ^^^^^^^^^^^^^^^^
  38. This module will set the following variables in your project:
  39. ``EnvModules_FOUND``
  40. True if a compatible environment modules framework was found.
  41. Cache Variables
  42. ^^^^^^^^^^^^^^^
  43. The following cache variable will be set:
  44. ``EnvModules_COMMAND``
  45. The low level module command to use. Currently supported
  46. implementations are the Lua based Lmod and TCL based EnvironmentModules.
  47. Environment Variables
  48. ^^^^^^^^^^^^^^^^^^^^^
  49. ``ENV{MODULESHOME}``
  50. Usually set by the module environment implementation, used as a hint to
  51. locate the module command to execute.
  52. Provided Functions
  53. ^^^^^^^^^^^^^^^^^^
  54. This defines the following CMake functions for interacting with environment
  55. modules:
  56. .. command:: env_module
  57. Execute an aribitrary module command:
  58. .. code-block:: cmake
  59. env_module(cmd arg1 ... argN)
  60. env_module(
  61. COMMAND cmd arg1 ... argN
  62. [OUTPUT_VARIABLE <out-var>]
  63. [RESULT_VARIABLE <ret-var>]
  64. )
  65. The options are:
  66. ``cmd arg1 ... argN``
  67. The module sub-command and arguments to execute as if they were
  68. passed directly to the module command in your shell environment.
  69. ``OUTPUT_VARIABLE <out-var>``
  70. The standard output from executing the module command.
  71. ``RESULT_VARIABLE <ret-var>``
  72. The return code from executing the module command.
  73. .. command:: env_module_swap
  74. Swap one module for another:
  75. .. code-block:: cmake
  76. env_module_swap(out_mod in_mod
  77. [OUTPUT_VARIABLE <out-var>]
  78. [RESULT_VARIABLE <ret-var>]
  79. )
  80. This is functionally equivalent to the ``module swap out_mod in_mod`` shell
  81. command. The options are:
  82. ``OUTPUT_VARIABLE <out-var>``
  83. The standard output from executing the module command.
  84. ``RESULT_VARIABLE <ret-var>``
  85. The return code from executing the module command.
  86. .. command:: env_module_list
  87. Retrieve the list of currently loaded modules:
  88. .. code-block:: cmake
  89. env_module_list(<out-var>)
  90. This is functionally equivalent to the ``module list`` shell command.
  91. The result is stored in ``<out-var>`` as a properly formatted CMake
  92. :ref:`semicolon-separated list <CMake Language Lists>` variable.
  93. .. command:: env_module_avail
  94. Retrieve the list of available modules:
  95. .. code-block:: cmake
  96. env_module_avail([<mod-prefix>] <out-var>)
  97. This is functionally equivalent to the ``module avail <mod-prefix>`` shell
  98. command. The result is stored in ``<out-var>`` as a properly formatted
  99. CMake :ref:`semicolon-separated list <CMake Language Lists>` variable.
  100. #]=======================================================================]
  101. function(env_module)
  102. if(NOT EnvModules_COMMAND)
  103. message(FATAL_ERROR "Failed to process module command. EnvModules_COMMAND not found")
  104. return()
  105. endif()
  106. set(options)
  107. set(oneValueArgs OUTPUT_VARIABLE RESULT_VARIABLE)
  108. set(multiValueArgs COMMAND)
  109. cmake_parse_arguments(MOD_ARGS
  110. "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGV}
  111. )
  112. if(NOT MOD_ARGS_COMMAND)
  113. # If no explicit command argument was given, then treat the calling syntax
  114. # as: module(cmd args...)
  115. set(exec_cmd ${ARGV})
  116. else()
  117. set(exec_cmd ${MOD_ARGS_COMMAND})
  118. endif()
  119. if(MOD_ARGS_OUTPUT_VARIABLE)
  120. set(err_var_args ERROR_VARIABLE err_var)
  121. endif()
  122. execute_process(
  123. COMMAND mktemp -t module.cmake.XXXXXXXXXXXX
  124. OUTPUT_VARIABLE tempfile_name
  125. )
  126. string(STRIP "${tempfile_name}" tempfile_name)
  127. # If the $MODULESHOME/init/cmake file exists then assume that the CMake
  128. # "shell" functionality exits
  129. if(EXISTS "$ENV{MODULESHOME}/init/cmake")
  130. execute_process(
  131. COMMAND ${EnvModules_COMMAND} cmake ${exec_cmd}
  132. OUTPUT_FILE ${tempfile_name}
  133. ${err_var_args}
  134. RESULT_VARIABLE ret_var
  135. )
  136. else() # fallback to the sh shell and manually convert to CMake
  137. execute_process(
  138. COMMAND ${EnvModules_COMMAND} sh ${exec_cmd}
  139. OUTPUT_VARIABLE out_var
  140. ${err_var_args}
  141. RESULT_VARIABLE ret_var
  142. )
  143. endif()
  144. # If we executed successfully then process and cleanup the temp file
  145. if(ret_var EQUAL 0)
  146. # No CMake shell so we need to process the sh output into CMake code
  147. if(NOT EXISTS "$ENV{MODULESHOME}/init/cmake")
  148. file(WRITE ${tempfile_name} "")
  149. string(REPLACE "\n" ";" out_var "${out_var}")
  150. foreach(sh_cmd IN LISTS out_var)
  151. if(sh_cmd MATCHES "^ *unset *([^ ]*)")
  152. set(cmake_cmd "unset(ENV{${CMAKE_MATCH_1}})")
  153. elseif(sh_cmd MATCHES "^ *export *([^ ]*)")
  154. set(cmake_cmd "set(ENV{${CMAKE_MATCH_1}} \"\${${CMAKE_MATCH_1}}\")")
  155. elseif(sh_cmd MATCHES " *([^ =]*) *= *(.*)")
  156. set(var_name "${CMAKE_MATCH_1}")
  157. set(var_value "${CMAKE_MATCH_2}")
  158. if(var_value MATCHES "^\"(.*[^\\])\"")
  159. # If it's in quotes, take the value as is
  160. set(var_value "${CMAKE_MATCH_1}")
  161. else()
  162. # Otherwise, strip trailing spaces
  163. string(REGEX REPLACE "([^\\])? +$" "\\1" var_value "${var_value}")
  164. endif()
  165. string(REPLACE "\\ " " " var_value "${var_value}")
  166. set(cmake_cmd "set(${var_name} \"${var_value}\")")
  167. else()
  168. continue()
  169. endif()
  170. file(APPEND ${tempfile_name} "${cmake_cmd}\n")
  171. endforeach()
  172. endif()
  173. # Process the change in environment variables
  174. include(${tempfile_name})
  175. file(REMOVE ${tempfile_name})
  176. endif()
  177. # Push the output back out to the calling scope
  178. if(MOD_ARGS_OUTPUT_VARIABLE)
  179. set(${MOD_ARGS_OUTPUT_VARIABLE} "${err_var}" PARENT_SCOPE)
  180. endif()
  181. if(MOD_ARGS_RESULT_VARIABLE)
  182. set(${MOD_ARGS_RESULT_VARIABLE} ${ret_var} PARENT_SCOPE)
  183. endif()
  184. endfunction(env_module)
  185. #------------------------------------------------------------------------------
  186. function(env_module_swap out_mod in_mod)
  187. set(options)
  188. set(oneValueArgs OUTPUT_VARIABLE RESULT_VARIABLE)
  189. set(multiValueArgs)
  190. cmake_parse_arguments(MOD_ARGS
  191. "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGV}
  192. )
  193. env_module(COMMAND -t swap ${out_mod} ${in_mod}
  194. OUTPUT_VARIABLE tmp_out
  195. RETURN_VARIABLE tmp_ret
  196. )
  197. if(MOD_ARGS_OUTPUT_VARIABLE)
  198. set(${MOD_ARGS_OUTPUT_VARIABLE} "${err_var}" PARENT_SCOPE)
  199. endif()
  200. if(MOD_ARGS_RESULT_VARIABLE)
  201. set(${MOD_ARGS_RESULT_VARIABLE} ${tmp_ret} PARENT_SCOPE)
  202. endif()
  203. endfunction()
  204. #------------------------------------------------------------------------------
  205. function(env_module_list out_var)
  206. cmake_policy(SET CMP0007 NEW)
  207. env_module(COMMAND -t list OUTPUT_VARIABLE tmp_out)
  208. # Convert output into a CMake list
  209. string(REPLACE "\n" ";" ${out_var} "${tmp_out}")
  210. # Remove title headers and empty entries
  211. list(REMOVE_ITEM ${out_var} "No modules loaded")
  212. if(${out_var})
  213. list(FILTER ${out_var} EXCLUDE REGEX "^(.*:)?$")
  214. endif()
  215. list(FILTER ${out_var} EXCLUDE REGEX "^(.*:)?$")
  216. set(${out_var} ${${out_var}} PARENT_SCOPE)
  217. endfunction()
  218. #------------------------------------------------------------------------------
  219. function(env_module_avail)
  220. cmake_policy(SET CMP0007 NEW)
  221. if(ARGC EQUAL 1)
  222. set(mod_prefix)
  223. set(out_var ${ARGV0})
  224. elseif(ARGC EQUAL 2)
  225. set(mod_prefix ${ARGV0})
  226. set(out_var ${ARGV1})
  227. else()
  228. message(FATAL_ERROR "Usage: env_module_avail([mod_prefix] out_var)")
  229. endif()
  230. env_module(COMMAND -t avail ${mod_prefix} OUTPUT_VARIABLE tmp_out)
  231. # Convert output into a CMake list
  232. string(REPLACE "\n" ";" tmp_out "${tmp_out}")
  233. set(${out_var})
  234. foreach(MOD IN LISTS tmp_out)
  235. # Remove directory entries and empty values
  236. if(MOD MATCHES "^(.*:)?$")
  237. continue()
  238. endif()
  239. # Convert default modules
  240. if(MOD MATCHES "^(.*)/$" ) # "foo/"
  241. list(APPEND ${out_var} ${CMAKE_MATCH_1})
  242. elseif(MOD MATCHES "^((.*)/.*)\\(default\\)$") # "foo/1.2.3(default)"
  243. list(APPEND ${out_var} ${CMAKE_MATCH_2})
  244. list(APPEND ${out_var} ${CMAKE_MATCH_1})
  245. else()
  246. list(APPEND ${out_var} ${MOD})
  247. endif()
  248. endforeach()
  249. set(${out_var} ${${out_var}} PARENT_SCOPE)
  250. endfunction()
  251. #------------------------------------------------------------------------------
  252. # Make sure we know where the underlying module command is
  253. find_program(EnvModules_COMMAND
  254. NAMES lmod modulecmd
  255. HINTS ENV MODULESHOME
  256. PATH_SUFFIXES libexec
  257. )
  258. include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
  259. find_package_handle_standard_args(EnvModules DEFAULT_MSG EnvModules_COMMAND)