ExternalData.cmake 28 KB

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