ExternalData.cmake 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. # - Manage data files stored outside source tree
  2. # Use this module to unambiguously reference data files stored outside the
  3. # source tree and fetch them at build time from arbitrary local and remote
  4. # content-addressed locations. Functions provided by this module recognize
  5. # arguments with the syntax "DATA{<name>}" as references to external data,
  6. # replace them with full paths to local copies of those data, and create build
  7. # rules to fetch and update the local copies.
  8. #
  9. # The DATA{} syntax is literal and the <name> is a full or relative path
  10. # within the source tree. The source tree must contain either a real data
  11. # file at <name> or a "content link" at <name><ext> containing a hash of the
  12. # real file using a hash algorithm corresponding to <ext>. For example, the
  13. # argument "DATA{img.png}" may be satisfied by either a real "img.png" file in
  14. # the current source directory or a "img.png.md5" file containing its MD5 sum.
  15. #
  16. # The 'ExternalData_Expand_Arguments' function evaluates DATA{} references
  17. # in its arguments and constructs a new list of arguments:
  18. # ExternalData_Expand_Arguments(
  19. # <target> # Name of data management target
  20. # <outVar> # Output variable
  21. # [args...] # Input arguments, DATA{} allowed
  22. # )
  23. # It replaces each DATA{} reference in an argument with the full path of a
  24. # real data file on disk that will exist after the <target> builds.
  25. #
  26. # The 'ExternalData_Add_Test' function wraps around the CMake add_test()
  27. # command but supports DATA{} references in its arguments:
  28. # ExternalData_Add_Test(
  29. # <target> # Name of data management target
  30. # ... # Arguments of add_test(), DATA{} allowed
  31. # )
  32. # It passes its arguments through ExternalData_Expand_Arguments and then
  33. # invokes add_test() using the results.
  34. #
  35. # The 'ExternalData_Add_Target' function creates a custom target to manage
  36. # local instances of data files stored externally:
  37. # ExternalData_Add_Target(
  38. # <target> # Name of data management target
  39. # )
  40. # It creates custom commands in the target as necessary to make data files
  41. # available for each DATA{} reference previously evaluated by other functions
  42. # provided by this module. A list of URL templates must be provided in the
  43. # variable ExternalData_URL_TEMPLATES using the placeholders "%(algo)" and
  44. # "%(hash)" in each template. Data fetch rules try each URL template in order
  45. # by substituting the hash algorithm name for "%(algo)" and the hash value for
  46. # "%(hash)".
  47. #
  48. # The following hash algorithms are supported:
  49. # %(algo) <ext> Description
  50. # ------- ----- -----------
  51. # MD5 .md5 Message-Digest Algorithm 5, RFC 1321
  52. # SHA1 .sha1 US Secure Hash Algorithm 1, RFC 3174
  53. # SHA224 .sha224 US Secure Hash Algorithms, RFC 4634
  54. # SHA256 .sha256 US Secure Hash Algorithms, RFC 4634
  55. # SHA384 .sha384 US Secure Hash Algorithms, RFC 4634
  56. # SHA512 .sha512 US Secure Hash Algorithms, RFC 4634
  57. # Note that the hashes are used only for unique data identification and
  58. # download verification. This is not security software.
  59. #
  60. # Example usage:
  61. # include(ExternalData)
  62. # set(ExternalData_URL_TEMPLATES "file:///local/%(algo)/%(hash)"
  63. # "http://data.org/%(algo)/%(hash)")
  64. # ExternalData_Add_Test(MyData
  65. # NAME MyTest
  66. # COMMAND MyExe DATA{MyInput.png}
  67. # )
  68. # ExternalData_Add_Target(MyData)
  69. # When test "MyTest" runs the "DATA{MyInput.png}" argument will be replaced by
  70. # the full path to a real instance of the data file "MyInput.png" on disk. If
  71. # the source tree contains a content link such as "MyInput.png.md5" then the
  72. # "MyData" target creates a real "MyInput.png" in the build tree.
  73. #
  74. # The DATA{} syntax can be told to fetch a file series using the form
  75. # "DATA{<name>,:}", where the ":" is literal. If the source tree contains a
  76. # group of files or content links named like a series then a reference to one
  77. # member adds rules to fetch all of them. Although all members of a series
  78. # are fetched, only the file originally named by the DATA{} argument is
  79. # substituted for it. The default configuration recognizes file series names
  80. # ending with "#.ext", "_#.ext", ".#.ext", or "-#.ext" where "#" is a sequence
  81. # of decimal digits and ".ext" is any single extension. Configure it with a
  82. # regex that parses <number> and <suffix> parts from the end of <name>:
  83. # ExternalData_SERIES_PARSE = regex of the form (<number>)(<suffix>)$
  84. # For more complicated cases set:
  85. # ExternalData_SERIES_PARSE = regex with at least two () groups
  86. # ExternalData_SERIES_PARSE_PREFIX = <prefix> regex group number, if any
  87. # ExternalData_SERIES_PARSE_NUMBER = <number> regex group number
  88. # ExternalData_SERIES_PARSE_SUFFIX = <suffix> regex group number
  89. # Configure series number matching with a regex that matches the
  90. # <number> part of series members named <prefix><number><suffix>:
  91. # ExternalData_SERIES_MATCH = regex matching <number> in all series members
  92. # Note that the <suffix> of a series does not include a hash-algorithm
  93. # extension.
  94. #
  95. # The DATA{} syntax can alternatively match files associated with the named
  96. # file and contained in the same directory. Associated files may be specified
  97. # by options using the syntax DATA{<name>,<opt1>,<opt2>,...}. Each option may
  98. # specify one file by name or specify a regular expression to match file names
  99. # using the syntax REGEX:<regex>. For example, the arguments
  100. # DATA{MyData/MyInput.mhd,MyInput.img} # File pair
  101. # DATA{MyData/MyFrames00.png,REGEX:MyFrames[0-9]+\\.png} # Series
  102. # will pass MyInput.mha and MyFrames00.png on the command line but ensure
  103. # that the associated files are present next to them.
  104. #
  105. # The DATA{} syntax may reference a directory using a trailing slash and a
  106. # list of associated files. The form DATA{<name>/,<opt1>,<opt2>,...} adds
  107. # rules to fetch any files in the directory that match one of the associated
  108. # file options. For example, the argument DATA{MyDataDir/,REGEX:.*} will pass
  109. # the full path to a MyDataDir directory on the command line and ensure that
  110. # the directory contains files corresponding to every file or content link in
  111. # the MyDataDir source directory.
  112. #
  113. # The variable ExternalData_LINK_CONTENT may be set to the name of a supported
  114. # hash algorithm to enable automatic conversion of real data files referenced
  115. # by the DATA{} syntax into content links. For each such <file> a content
  116. # link named "<file><ext>" is created. The original file is renamed to the
  117. # form ".ExternalData_<algo>_<hash>" to stage it for future transmission to
  118. # one of the locations in the list of URL templates (by means outside the
  119. # scope of this module). The data fetch rule created for the content link
  120. # will use the staged object if it cannot be found using any URL template.
  121. #
  122. # The variable ExternalData_OBJECT_STORES may be set to a list of local
  123. # directories that store objects using the layout <dir>/%(algo)/%(hash).
  124. # These directories will be searched first for a needed object. If the object
  125. # is not available in any store then it will be fetched remotely using the URL
  126. # templates and added to the first local store listed. If no stores are
  127. # specified the default is a location inside the build tree.
  128. #
  129. # The variable ExternalData_SOURCE_ROOT may be set to the highest source
  130. # directory containing any path named by a DATA{} reference. The default is
  131. # CMAKE_SOURCE_DIR. ExternalData_SOURCE_ROOT and CMAKE_SOURCE_DIR must refer
  132. # to directories within a single source distribution (e.g. they come together
  133. # in one tarball).
  134. #
  135. # The variable ExternalData_BINARY_ROOT may be set to the directory to hold
  136. # the real data files named by expanded DATA{} references. The default is
  137. # CMAKE_BINARY_DIR. The directory layout will mirror that of content links
  138. # under ExternalData_SOURCE_ROOT.
  139. #
  140. # Variables ExternalData_TIMEOUT_INACTIVITY and ExternalData_TIMEOUT_ABSOLUTE
  141. # set the download inactivity and absolute timeouts, in seconds. The defaults
  142. # are 60 seconds and 300 seconds, respectively. Set either timeout to 0
  143. # seconds to disable enforcement.
  144. #=============================================================================
  145. # Copyright 2010-2013 Kitware, Inc.
  146. #
  147. # Distributed under the OSI-approved BSD License (the "License");
  148. # see accompanying file Copyright.txt for details.
  149. #
  150. # This software is distributed WITHOUT ANY WARRANTY; without even the
  151. # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  152. # See the License for more information.
  153. #=============================================================================
  154. # (To distribute this file outside of CMake, substitute the full
  155. # License text for the above reference.)
  156. function(ExternalData_add_test target)
  157. ExternalData_expand_arguments("${target}" testArgs ${ARGN})
  158. add_test(${testArgs})
  159. endfunction()
  160. function(ExternalData_add_target target)
  161. if(NOT ExternalData_URL_TEMPLATES)
  162. message(FATAL_ERROR "ExternalData_URL_TEMPLATES is not set!")
  163. endif()
  164. if(NOT ExternalData_OBJECT_STORES)
  165. set(ExternalData_OBJECT_STORES ${CMAKE_BINARY_DIR}/ExternalData/Objects)
  166. endif()
  167. set(config ${CMAKE_CURRENT_BINARY_DIR}/${target}_config.cmake)
  168. configure_file(${_ExternalData_SELF_DIR}/ExternalData_config.cmake.in ${config} @ONLY)
  169. set(files "")
  170. # Set "_ExternalData_FILE_${file}" for each output file to avoid duplicate
  171. # rules. Use local data first to prefer real files over content links.
  172. # Custom commands to copy or link local data.
  173. get_property(data_local GLOBAL PROPERTY _ExternalData_${target}_LOCAL)
  174. foreach(entry IN LISTS data_local)
  175. string(REPLACE "|" ";" tuple "${entry}")
  176. list(GET tuple 0 file)
  177. list(GET tuple 1 name)
  178. if(NOT DEFINED "_ExternalData_FILE_${file}")
  179. set("_ExternalData_FILE_${file}" 1)
  180. add_custom_command(
  181. COMMENT "Generating ${file}"
  182. OUTPUT "${file}"
  183. COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
  184. -Dfile=${file} -Dname=${name}
  185. -DExternalData_ACTION=local
  186. -DExternalData_CONFIG=${config}
  187. -P ${_ExternalData_SELF}
  188. MAIN_DEPENDENCY "${name}"
  189. )
  190. list(APPEND files "${file}")
  191. endif()
  192. endforeach()
  193. # Custom commands to fetch remote data.
  194. get_property(data_fetch GLOBAL PROPERTY _ExternalData_${target}_FETCH)
  195. foreach(entry IN LISTS data_fetch)
  196. string(REPLACE "|" ";" tuple "${entry}")
  197. list(GET tuple 0 file)
  198. list(GET tuple 1 name)
  199. list(GET tuple 2 ext)
  200. set(stamp "${ext}-stamp")
  201. if(NOT DEFINED "_ExternalData_FILE_${file}")
  202. set("_ExternalData_FILE_${file}" 1)
  203. add_custom_command(
  204. # Users care about the data file, so hide the hash/timestamp file.
  205. COMMENT "Generating ${file}"
  206. # The hash/timestamp file is the output from the build perspective.
  207. # List the real file as a second output in case it is a broken link.
  208. # The files must be listed in this order so CMake can hide from the
  209. # make tool that a symlink target may not be newer than the input.
  210. OUTPUT "${file}${stamp}" "${file}"
  211. # Run the data fetch/update script.
  212. COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
  213. -Dfile=${file} -Dname=${name} -Dext=${ext}
  214. -DExternalData_ACTION=fetch
  215. -DExternalData_CONFIG=${config}
  216. -P ${_ExternalData_SELF}
  217. # Update whenever the object hash changes.
  218. MAIN_DEPENDENCY "${name}${ext}"
  219. )
  220. list(APPEND files "${file}${stamp}")
  221. endif()
  222. endforeach()
  223. # Custom target to drive all update commands.
  224. add_custom_target(${target} ALL DEPENDS ${files})
  225. endfunction()
  226. function(ExternalData_expand_arguments target outArgsVar)
  227. # Replace DATA{} references with real arguments.
  228. set(data_regex "DATA{([^{}\r\n]*)}")
  229. set(other_regex "([^D]|D[^A]|DA[^T]|DAT[^A]|DATA[^{])+|.")
  230. set(outArgs "")
  231. foreach(arg IN LISTS ARGN)
  232. if("x${arg}" MATCHES "${data_regex}")
  233. # Split argument into DATA{}-pieces and other pieces.
  234. string(REGEX MATCHALL "${data_regex}|${other_regex}" pieces "${arg}")
  235. # Compose output argument with DATA{}-pieces replaced.
  236. set(outArg "")
  237. foreach(piece IN LISTS pieces)
  238. if("x${piece}" MATCHES "^x${data_regex}$")
  239. # Replace this DATA{}-piece with a file path.
  240. string(REGEX REPLACE "${data_regex}" "\\1" data "${piece}")
  241. _ExternalData_arg("${target}" "${piece}" "${data}" file)
  242. set(outArg "${outArg}${file}")
  243. else()
  244. # No replacement needed for this piece.
  245. set(outArg "${outArg}${piece}")
  246. endif()
  247. endforeach()
  248. list(APPEND outArgs "${outArg}")
  249. else()
  250. # No replacements needed in this argument.
  251. list(APPEND outArgs "${arg}")
  252. endif()
  253. endforeach()
  254. set("${outArgsVar}" "${outArgs}" PARENT_SCOPE)
  255. endfunction()
  256. #-----------------------------------------------------------------------------
  257. # Private helper interface
  258. set(_ExternalData_REGEX_ALGO "MD5|SHA1|SHA224|SHA256|SHA384|SHA512")
  259. set(_ExternalData_REGEX_EXT "md5|sha1|sha224|sha256|sha384|sha512")
  260. set(_ExternalData_SELF "${CMAKE_CURRENT_LIST_FILE}")
  261. get_filename_component(_ExternalData_SELF_DIR "${_ExternalData_SELF}" PATH)
  262. function(_ExternalData_compute_hash var_hash algo file)
  263. if("${algo}" MATCHES "^${_ExternalData_REGEX_ALGO}$")
  264. file("${algo}" "${file}" hash)
  265. set("${var_hash}" "${hash}" PARENT_SCOPE)
  266. else()
  267. message(FATAL_ERROR "Hash algorithm ${algo} unimplemented.")
  268. endif()
  269. endfunction()
  270. function(_ExternalData_random var)
  271. string(RANDOM LENGTH 6 random)
  272. set("${var}" "${random}" PARENT_SCOPE)
  273. endfunction()
  274. function(_ExternalData_exact_regex regex_var string)
  275. string(REGEX REPLACE "([][+.*()^])" "\\\\\\1" regex "${string}")
  276. set("${regex_var}" "${regex}" PARENT_SCOPE)
  277. endfunction()
  278. function(_ExternalData_atomic_write file content)
  279. _ExternalData_random(random)
  280. set(tmp "${file}.tmp${random}")
  281. file(WRITE "${tmp}" "${content}")
  282. file(RENAME "${tmp}" "${file}")
  283. endfunction()
  284. function(_ExternalData_link_content name var_ext)
  285. if("${ExternalData_LINK_CONTENT}" MATCHES "^(${_ExternalData_REGEX_ALGO})$")
  286. set(algo "${ExternalData_LINK_CONTENT}")
  287. else()
  288. message(FATAL_ERROR
  289. "Unknown hash algorithm specified by ExternalData_LINK_CONTENT:\n"
  290. " ${ExternalData_LINK_CONTENT}")
  291. endif()
  292. _ExternalData_compute_hash(hash "${algo}" "${name}")
  293. get_filename_component(dir "${name}" PATH)
  294. set(staged "${dir}/.ExternalData_${algo}_${hash}")
  295. string(TOLOWER ".${algo}" ext)
  296. _ExternalData_atomic_write("${name}${ext}" "${hash}\n")
  297. file(RENAME "${name}" "${staged}")
  298. set("${var_ext}" "${ext}" PARENT_SCOPE)
  299. file(RELATIVE_PATH relname "${ExternalData_SOURCE_ROOT}" "${name}${ext}")
  300. message(STATUS "Linked ${relname} to ExternalData ${algo}/${hash}")
  301. endfunction()
  302. function(_ExternalData_arg target arg options var_file)
  303. # Separate data path from the options.
  304. string(REPLACE "," ";" options "${options}")
  305. list(GET options 0 data)
  306. list(REMOVE_AT options 0)
  307. # Interpret trailing slashes as directories.
  308. set(data_is_directory 0)
  309. if("x${data}" MATCHES "^x(.*)([/\\])$")
  310. set(data_is_directory 1)
  311. set(data "${CMAKE_MATCH_1}")
  312. endif()
  313. # Convert to full path.
  314. if(IS_ABSOLUTE "${data}")
  315. set(absdata "${data}")
  316. else()
  317. set(absdata "${CMAKE_CURRENT_SOURCE_DIR}/${data}")
  318. endif()
  319. get_filename_component(absdata "${absdata}" ABSOLUTE)
  320. # Convert to relative path under the source tree.
  321. if(NOT ExternalData_SOURCE_ROOT)
  322. set(ExternalData_SOURCE_ROOT "${CMAKE_SOURCE_DIR}")
  323. endif()
  324. set(top_src "${ExternalData_SOURCE_ROOT}")
  325. file(RELATIVE_PATH reldata "${top_src}" "${absdata}")
  326. if(IS_ABSOLUTE "${reldata}" OR "${reldata}" MATCHES "^\\.\\./")
  327. message(FATAL_ERROR "Data file referenced by argument\n"
  328. " ${arg}\n"
  329. "does not lie under the top-level source directory\n"
  330. " ${top_src}\n")
  331. endif()
  332. if(data_is_directory AND NOT IS_DIRECTORY "${top_src}/${reldata}")
  333. message(FATAL_ERROR "Data directory referenced by argument\n"
  334. " ${arg}\n"
  335. "corresponds to source tree path\n"
  336. " ${reldata}\n"
  337. "that does not exist as a directory!")
  338. endif()
  339. if(NOT ExternalData_BINARY_ROOT)
  340. set(ExternalData_BINARY_ROOT "${CMAKE_BINARY_DIR}")
  341. endif()
  342. set(top_bin "${ExternalData_BINARY_ROOT}")
  343. # Handle in-source builds gracefully.
  344. if("${top_src}" STREQUAL "${top_bin}")
  345. if(ExternalData_LINK_CONTENT)
  346. message(WARNING "ExternalData_LINK_CONTENT cannot be used in-source")
  347. set(ExternalData_LINK_CONTENT 0)
  348. endif()
  349. set(top_same 1)
  350. endif()
  351. set(external "") # Entries external to the source tree.
  352. set(internal "") # Entries internal to the source tree.
  353. set(have_original ${data_is_directory})
  354. # Process options.
  355. set(series_option "")
  356. set(associated_files "")
  357. set(associated_regex "")
  358. foreach(opt ${options})
  359. if("x${opt}" MATCHES "^xREGEX:[^:/]+$")
  360. # Regular expression to match associated files.
  361. string(REGEX REPLACE "^REGEX:" "" regex "${opt}")
  362. list(APPEND associated_regex "${regex}")
  363. elseif("x${opt}" MATCHES "^x:$")
  364. # Activate series matching.
  365. set(series_option "${opt}")
  366. elseif("x${opt}" MATCHES "^[^][:/*?]+$")
  367. # Specific associated file.
  368. list(APPEND associated_files "${opt}")
  369. else()
  370. message(FATAL_ERROR "Unknown option \"${opt}\" in argument\n"
  371. " ${arg}\n")
  372. endif()
  373. endforeach()
  374. if(series_option)
  375. if(data_is_directory)
  376. message(FATAL_ERROR "Series option \"${series_option}\" not allowed with directories.")
  377. endif()
  378. if(associated_files OR associated_regex)
  379. message(FATAL_ERROR "Series option \"${series_option}\" not allowed with associated files.")
  380. endif()
  381. # Load a whole file series.
  382. _ExternalData_arg_series()
  383. elseif(data_is_directory)
  384. if(associated_files OR associated_regex)
  385. # Load listed/matching associated files in the directory.
  386. _ExternalData_arg_associated()
  387. else()
  388. message(FATAL_ERROR "Data directory referenced by argument\n"
  389. " ${arg}\n"
  390. "must list associated files.")
  391. endif()
  392. else()
  393. # Load the named data file.
  394. _ExternalData_arg_single()
  395. if(associated_files OR associated_regex)
  396. # Load listed/matching associated files.
  397. _ExternalData_arg_associated()
  398. endif()
  399. endif()
  400. if(NOT have_original)
  401. message(FATAL_ERROR "Data file referenced by argument\n"
  402. " ${arg}\n"
  403. "corresponds to source tree path\n"
  404. " ${reldata}\n"
  405. "that does not exist as a file (with or without an extension)!")
  406. endif()
  407. if(external)
  408. # Make the series available in the build tree.
  409. set_property(GLOBAL APPEND PROPERTY
  410. _ExternalData_${target}_FETCH "${external}")
  411. set_property(GLOBAL APPEND PROPERTY
  412. _ExternalData_${target}_LOCAL "${internal}")
  413. set("${var_file}" "${top_bin}/${reldata}" PARENT_SCOPE)
  414. else()
  415. # The whole series is in the source tree.
  416. set("${var_file}" "${top_src}/${reldata}" PARENT_SCOPE)
  417. endif()
  418. endfunction()
  419. macro(_ExternalData_arg_associated)
  420. # Associated files lie in the same directory.
  421. if(data_is_directory)
  422. set(reldir "${reldata}")
  423. else()
  424. get_filename_component(reldir "${reldata}" PATH)
  425. endif()
  426. if(reldir)
  427. set(reldir "${reldir}/")
  428. endif()
  429. _ExternalData_exact_regex(reldir_regex "${reldir}")
  430. # Find files named explicitly.
  431. foreach(file ${associated_files})
  432. _ExternalData_exact_regex(file_regex "${file}")
  433. _ExternalData_arg_find_files("${reldir}${file}" "${reldir_regex}${file_regex}")
  434. endforeach()
  435. # Find files matching the given regular expressions.
  436. set(all "")
  437. set(sep "")
  438. foreach(regex ${associated_regex})
  439. set(all "${all}${sep}${reldir_regex}${regex}")
  440. set(sep "|")
  441. endforeach()
  442. _ExternalData_arg_find_files("${reldir}" "${all}")
  443. endmacro()
  444. macro(_ExternalData_arg_single)
  445. # Match only the named data by itself.
  446. _ExternalData_exact_regex(data_regex "${reldata}")
  447. _ExternalData_arg_find_files("${reldata}" "${data_regex}")
  448. endmacro()
  449. macro(_ExternalData_arg_series)
  450. # Configure series parsing and matching.
  451. set(series_parse_prefix "")
  452. set(series_parse_number "\\1")
  453. set(series_parse_suffix "\\2")
  454. if(ExternalData_SERIES_PARSE)
  455. if(ExternalData_SERIES_PARSE_NUMBER AND ExternalData_SERIES_PARSE_SUFFIX)
  456. if(ExternalData_SERIES_PARSE_PREFIX)
  457. set(series_parse_prefix "\\${ExternalData_SERIES_PARSE_PREFIX}")
  458. endif()
  459. set(series_parse_number "\\${ExternalData_SERIES_PARSE_NUMBER}")
  460. set(series_parse_suffix "\\${ExternalData_SERIES_PARSE_SUFFIX}")
  461. elseif(NOT "x${ExternalData_SERIES_PARSE}" MATCHES "^x\\([^()]*\\)\\([^()]*\\)\\$$")
  462. message(FATAL_ERROR
  463. "ExternalData_SERIES_PARSE is set to\n"
  464. " ${ExternalData_SERIES_PARSE}\n"
  465. "which is not of the form\n"
  466. " (<number>)(<suffix>)$\n"
  467. "Fix the regular expression or set variables\n"
  468. " ExternalData_SERIES_PARSE_PREFIX = <prefix> regex group number, if any\n"
  469. " ExternalData_SERIES_PARSE_NUMBER = <number> regex group number\n"
  470. " ExternalData_SERIES_PARSE_SUFFIX = <suffix> regex group number\n"
  471. )
  472. endif()
  473. set(series_parse "${ExternalData_SERIES_PARSE}")
  474. else()
  475. set(series_parse "([0-9]*)(\\.[^./]*)$")
  476. endif()
  477. if(ExternalData_SERIES_MATCH)
  478. set(series_match "${ExternalData_SERIES_MATCH}")
  479. else()
  480. set(series_match "[_.-]?[0-9]*")
  481. endif()
  482. # Parse the base, number, and extension components of the series.
  483. string(REGEX REPLACE "${series_parse}" "${series_parse_prefix};${series_parse_number};${series_parse_suffix}" tuple "${reldata}")
  484. list(LENGTH tuple len)
  485. if(NOT "${len}" EQUAL 3)
  486. message(FATAL_ERROR "Data file referenced by argument\n"
  487. " ${arg}\n"
  488. "corresponds to path\n"
  489. " ${reldata}\n"
  490. "that does not match regular expression\n"
  491. " ${series_parse}")
  492. endif()
  493. list(GET tuple 0 relbase)
  494. list(GET tuple 2 ext)
  495. # Glob files that might match the series.
  496. # Then match base, number, and extension.
  497. _ExternalData_exact_regex(series_base "${relbase}")
  498. _ExternalData_exact_regex(series_ext "${ext}")
  499. _ExternalData_arg_find_files("${relbase}*${ext}"
  500. "${series_base}${series_match}${series_ext}")
  501. endmacro()
  502. function(_ExternalData_arg_find_files pattern regex)
  503. file(GLOB globbed RELATIVE "${top_src}" "${top_src}/${pattern}*")
  504. foreach(entry IN LISTS globbed)
  505. if("x${entry}" MATCHES "^x(.*)(\\.(${_ExternalData_REGEX_EXT}))$")
  506. set(relname "${CMAKE_MATCH_1}")
  507. set(alg "${CMAKE_MATCH_2}")
  508. else()
  509. set(relname "${entry}")
  510. set(alg "")
  511. endif()
  512. if("x${relname}" MATCHES "^x${regex}$" AND NOT IS_DIRECTORY "${top_src}/${entry}")
  513. set(name "${top_src}/${relname}")
  514. set(file "${top_bin}/${relname}")
  515. if(alg)
  516. list(APPEND external "${file}|${name}|${alg}")
  517. elseif(ExternalData_LINK_CONTENT)
  518. _ExternalData_link_content("${name}" alg)
  519. list(APPEND external "${file}|${name}|${alg}")
  520. elseif(NOT top_same)
  521. list(APPEND internal "${file}|${name}")
  522. endif()
  523. if("${relname}" STREQUAL "${reldata}")
  524. set(have_original 1)
  525. endif()
  526. endif()
  527. endforeach()
  528. set(external "${external}" PARENT_SCOPE)
  529. set(internal "${internal}" PARENT_SCOPE)
  530. set(have_original "${have_original}" PARENT_SCOPE)
  531. endfunction()
  532. #-----------------------------------------------------------------------------
  533. # Private script mode interface
  534. if(CMAKE_GENERATOR OR NOT ExternalData_ACTION)
  535. return()
  536. endif()
  537. if(ExternalData_CONFIG)
  538. include(${ExternalData_CONFIG})
  539. endif()
  540. if(NOT ExternalData_URL_TEMPLATES)
  541. message(FATAL_ERROR "No ExternalData_URL_TEMPLATES set!")
  542. endif()
  543. function(_ExternalData_link_or_copy src dst)
  544. # Create a temporary file first.
  545. get_filename_component(dst_dir "${dst}" PATH)
  546. file(MAKE_DIRECTORY "${dst_dir}")
  547. _ExternalData_random(random)
  548. set(tmp "${dst}.tmp${random}")
  549. if(UNIX)
  550. # Create a symbolic link.
  551. set(tgt "${src}")
  552. if(relative_top)
  553. # Use relative path if files are close enough.
  554. file(RELATIVE_PATH relsrc "${relative_top}" "${src}")
  555. file(RELATIVE_PATH relfile "${relative_top}" "${dst}")
  556. if(NOT IS_ABSOLUTE "${relsrc}" AND NOT "${relsrc}" MATCHES "^\\.\\./" AND
  557. NOT IS_ABSOLUTE "${reldst}" AND NOT "${reldst}" MATCHES "^\\.\\./")
  558. file(RELATIVE_PATH tgt "${dst_dir}" "${src}")
  559. endif()
  560. endif()
  561. execute_process(COMMAND "${CMAKE_COMMAND}" -E create_symlink "${tgt}" "${tmp}" RESULT_VARIABLE result)
  562. else()
  563. # Create a copy.
  564. execute_process(COMMAND "${CMAKE_COMMAND}" -E copy "${src}" "${tmp}" RESULT_VARIABLE result)
  565. endif()
  566. if(result)
  567. file(REMOVE "${tmp}")
  568. message(FATAL_ERROR "Failed to create\n ${tmp}\nfrom\n ${obj}")
  569. endif()
  570. # Atomically create/replace the real destination.
  571. file(RENAME "${tmp}" "${dst}")
  572. endfunction()
  573. function(_ExternalData_download_file url file err_var msg_var)
  574. set(retry 3)
  575. while(retry)
  576. math(EXPR retry "${retry} - 1")
  577. if(ExternalData_TIMEOUT_INACTIVITY)
  578. set(inactivity_timeout INACTIVITY_TIMEOUT ${ExternalData_TIMEOUT_INACTIVITY})
  579. elseif(NOT "${ExternalData_TIMEOUT_INACTIVITY}" EQUAL 0)
  580. set(inactivity_timeout INACTIVITY_TIMEOUT 60)
  581. else()
  582. set(inactivity_timeout "")
  583. endif()
  584. if(ExternalData_TIMEOUT_ABSOLUTE)
  585. set(absolute_timeout TIMEOUT ${ExternalData_TIMEOUT_ABSOLUTE})
  586. elseif(NOT "${ExternalData_TIMEOUT_ABSOLUTE}" EQUAL 0)
  587. set(absolute_timeout TIMEOUT 300)
  588. else()
  589. set(absolute_timeout "")
  590. endif()
  591. file(DOWNLOAD "${url}" "${file}" STATUS status LOG log ${inactivity_timeout} ${absolute_timeout} SHOW_PROGRESS)
  592. list(GET status 0 err)
  593. list(GET status 1 msg)
  594. if(err)
  595. if("${msg}" MATCHES "HTTP response code said error" AND
  596. "${log}" MATCHES "error: 503")
  597. set(msg "temporarily unavailable")
  598. endif()
  599. elseif("${log}" MATCHES "\nHTTP[^\n]* 503")
  600. set(err TRUE)
  601. set(msg "temporarily unavailable")
  602. endif()
  603. if(NOT err OR NOT "${msg}" MATCHES "partial|timeout|temporarily")
  604. break()
  605. elseif(retry)
  606. message(STATUS "[download terminated: ${msg}, retries left: ${retry}]")
  607. endif()
  608. endwhile()
  609. set("${err_var}" "${err}" PARENT_SCOPE)
  610. set("${msg_var}" "${msg}" PARENT_SCOPE)
  611. endfunction()
  612. function(_ExternalData_download_object name hash algo var_obj)
  613. # Search all object stores for an existing object.
  614. foreach(dir ${ExternalData_OBJECT_STORES})
  615. set(obj "${dir}/${algo}/${hash}")
  616. if(EXISTS "${obj}")
  617. message(STATUS "Found object: \"${obj}\"")
  618. set("${var_obj}" "${obj}" PARENT_SCOPE)
  619. return()
  620. endif()
  621. endforeach()
  622. # Download object to the first store.
  623. list(GET ExternalData_OBJECT_STORES 0 store)
  624. set(obj "${store}/${algo}/${hash}")
  625. _ExternalData_random(random)
  626. set(tmp "${obj}.tmp${random}")
  627. set(found 0)
  628. set(tried "")
  629. foreach(url_template IN LISTS ExternalData_URL_TEMPLATES)
  630. string(REPLACE "%(hash)" "${hash}" url_tmp "${url_template}")
  631. string(REPLACE "%(algo)" "${algo}" url "${url_tmp}")
  632. message(STATUS "Fetching \"${url}\"")
  633. _ExternalData_download_file("${url}" "${tmp}" err errMsg)
  634. set(tried "${tried}\n ${url}")
  635. if(err)
  636. set(tried "${tried} (${errMsg})")
  637. else()
  638. # Verify downloaded object.
  639. _ExternalData_compute_hash(dl_hash "${algo}" "${tmp}")
  640. if("${dl_hash}" STREQUAL "${hash}")
  641. set(found 1)
  642. break()
  643. else()
  644. set(tried "${tried} (wrong hash ${algo}=${dl_hash})")
  645. if("$ENV{ExternalData_DEBUG_DOWNLOAD}" MATCHES ".")
  646. file(RENAME "${tmp}" "${store}/${algo}/${dl_hash}")
  647. endif()
  648. endif()
  649. endif()
  650. file(REMOVE "${tmp}")
  651. endforeach()
  652. get_filename_component(dir "${name}" PATH)
  653. set(staged "${dir}/.ExternalData_${algo}_${hash}")
  654. if(found)
  655. file(RENAME "${tmp}" "${obj}")
  656. message(STATUS "Downloaded object: \"${obj}\"")
  657. elseif(EXISTS "${staged}")
  658. set(obj "${staged}")
  659. message(STATUS "Staged object: \"${obj}\"")
  660. else()
  661. message(FATAL_ERROR "Object ${algo}=${hash} not found at:${tried}")
  662. endif()
  663. set("${var_obj}" "${obj}" PARENT_SCOPE)
  664. endfunction()
  665. if("${ExternalData_ACTION}" STREQUAL "fetch")
  666. foreach(v ExternalData_OBJECT_STORES file name ext)
  667. if(NOT DEFINED "${v}")
  668. message(FATAL_ERROR "No \"-D${v}=\" value provided!")
  669. endif()
  670. endforeach()
  671. file(READ "${name}${ext}" hash)
  672. string(STRIP "${hash}" hash)
  673. if("${ext}" MATCHES "^\\.(${_ExternalData_REGEX_EXT})$")
  674. string(TOUPPER "${CMAKE_MATCH_1}" algo)
  675. else()
  676. message(FATAL_ERROR "Unknown hash algorithm extension \"${ext}\"")
  677. endif()
  678. _ExternalData_download_object("${name}" "${hash}" "${algo}" obj)
  679. # Check if file already corresponds to the object.
  680. set(stamp "${ext}-stamp")
  681. set(file_up_to_date 0)
  682. if(EXISTS "${file}" AND EXISTS "${file}${stamp}")
  683. file(READ "${file}${stamp}" f_hash)
  684. string(STRIP "${f_hash}" f_hash)
  685. if("${f_hash}" STREQUAL "${hash}")
  686. #message(STATUS "File already corresponds to object")
  687. set(file_up_to_date 1)
  688. endif()
  689. endif()
  690. if(file_up_to_date)
  691. # Touch the file to convince the build system it is up to date.
  692. execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${file}")
  693. else()
  694. _ExternalData_link_or_copy("${obj}" "${file}")
  695. endif()
  696. # Atomically update the hash/timestamp file to record the object referenced.
  697. _ExternalData_atomic_write("${file}${stamp}" "${hash}\n")
  698. elseif("${ExternalData_ACTION}" STREQUAL "local")
  699. foreach(v file name)
  700. if(NOT DEFINED "${v}")
  701. message(FATAL_ERROR "No \"-D${v}=\" value provided!")
  702. endif()
  703. endforeach()
  704. _ExternalData_link_or_copy("${name}" "${file}")
  705. else()
  706. message(FATAL_ERROR "Unknown ExternalData_ACTION=[${ExternalData_ACTION}]")
  707. endif()