ExternalData.cmake 29 KB

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