ExternalData.cmake 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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_REGEX_ALGO "MD5")
  254. set(_ExternalData_REGEX_EXT "md5")
  255. set(_ExternalData_SELF "${CMAKE_CURRENT_LIST_FILE}")
  256. get_filename_component(_ExternalData_SELF_DIR "${_ExternalData_SELF}" PATH)
  257. function(_ExternalData_compute_hash var_hash algo file)
  258. if("${algo}" MATCHES "^${_ExternalData_REGEX_ALGO}$")
  259. file("${algo}" "${file}" hash)
  260. set("${var_hash}" "${hash}" PARENT_SCOPE)
  261. else()
  262. message(FATAL_ERROR "Hash algorithm ${algo} unimplemented.")
  263. endif()
  264. endfunction()
  265. function(_ExternalData_random var)
  266. string(RANDOM LENGTH 6 random)
  267. set("${var}" "${random}" PARENT_SCOPE)
  268. endfunction()
  269. function(_ExternalData_exact_regex regex_var string)
  270. string(REGEX REPLACE "([][+.*()^])" "\\\\\\1" regex "${string}")
  271. set("${regex_var}" "${regex}" PARENT_SCOPE)
  272. endfunction()
  273. function(_ExternalData_atomic_write file content)
  274. _ExternalData_random(random)
  275. set(tmp "${file}.tmp${random}")
  276. file(WRITE "${tmp}" "${content}")
  277. file(RENAME "${tmp}" "${file}")
  278. endfunction()
  279. function(_ExternalData_link_content name var_ext)
  280. if("${ExternalData_LINK_CONTENT}" MATCHES "^(${_ExternalData_REGEX_ALGO})$")
  281. set(algo "${ExternalData_LINK_CONTENT}")
  282. else()
  283. message(FATAL_ERROR
  284. "Unknown hash algorithm specified by ExternalData_LINK_CONTENT:\n"
  285. " ${ExternalData_LINK_CONTENT}")
  286. endif()
  287. _ExternalData_compute_hash(hash "${algo}" "${name}")
  288. get_filename_component(dir "${name}" PATH)
  289. set(staged "${dir}/.ExternalData_${algo}_${hash}")
  290. string(TOLOWER ".${algo}" ext)
  291. _ExternalData_atomic_write("${name}${ext}" "${hash}\n")
  292. file(RENAME "${name}" "${staged}")
  293. set("${var_ext}" "${ext}" PARENT_SCOPE)
  294. file(RELATIVE_PATH relname "${ExternalData_SOURCE_ROOT}" "${name}${ext}")
  295. message(STATUS "Linked ${relname} to ExternalData ${algo}/${hash}")
  296. endfunction()
  297. function(_ExternalData_arg target arg options var_file)
  298. # Separate data path from the options.
  299. string(REPLACE "," ";" options "${options}")
  300. list(GET options 0 data)
  301. list(REMOVE_AT options 0)
  302. # Interpret trailing slashes as directories.
  303. set(data_is_directory 0)
  304. if("x${data}" MATCHES "^x(.*)([/\\])$")
  305. set(data_is_directory 1)
  306. set(data "${CMAKE_MATCH_1}")
  307. endif()
  308. # Convert to full path.
  309. if(IS_ABSOLUTE "${data}")
  310. set(absdata "${data}")
  311. else()
  312. get_filename_component(absdata "${CMAKE_CURRENT_SOURCE_DIR}/${data}" ABSOLUTE)
  313. endif()
  314. # Convert to relative path under the source tree.
  315. if(NOT ExternalData_SOURCE_ROOT)
  316. set(ExternalData_SOURCE_ROOT "${CMAKE_SOURCE_DIR}")
  317. endif()
  318. set(top_src "${ExternalData_SOURCE_ROOT}")
  319. file(RELATIVE_PATH reldata "${top_src}" "${absdata}")
  320. if(IS_ABSOLUTE "${reldata}" OR "${reldata}" MATCHES "^\\.\\./")
  321. message(FATAL_ERROR "Data file referenced by argument\n"
  322. " ${arg}\n"
  323. "does not lie under the top-level source directory\n"
  324. " ${top_src}\n")
  325. endif()
  326. if(data_is_directory AND NOT IS_DIRECTORY "${top_src}/${reldata}")
  327. message(FATAL_ERROR "Data directory referenced by argument\n"
  328. " ${arg}\n"
  329. "corresponds to source tree path\n"
  330. " ${reldata}\n"
  331. "that does not exist as a directory!")
  332. endif()
  333. if(NOT ExternalData_BINARY_ROOT)
  334. set(ExternalData_BINARY_ROOT "${CMAKE_BINARY_DIR}")
  335. endif()
  336. set(top_bin "${ExternalData_BINARY_ROOT}")
  337. # Handle in-source builds gracefully.
  338. if("${top_src}" STREQUAL "${top_bin}")
  339. if(ExternalData_LINK_CONTENT)
  340. message(WARNING "ExternalData_LINK_CONTENT cannot be used in-source")
  341. set(ExternalData_LINK_CONTENT 0)
  342. endif()
  343. set(top_same 1)
  344. endif()
  345. set(external "") # Entries external to the source tree.
  346. set(internal "") # Entries internal to the source tree.
  347. set(have_original ${data_is_directory})
  348. # Process options.
  349. set(series_option "")
  350. set(associated_files "")
  351. set(associated_regex "")
  352. foreach(opt ${options})
  353. if("x${opt}" MATCHES "^xREGEX:[^:/]+$")
  354. # Regular expression to match associated files.
  355. string(REGEX REPLACE "^REGEX:" "" regex "${opt}")
  356. list(APPEND associated_regex "${regex}")
  357. elseif("x${opt}" MATCHES "^x:$")
  358. # Activate series matching.
  359. set(series_option "${opt}")
  360. elseif("x${opt}" MATCHES "^[^][:/*?]+$")
  361. # Specific associated file.
  362. list(APPEND associated_files "${opt}")
  363. else()
  364. message(FATAL_ERROR "Unknown option \"${opt}\" in argument\n"
  365. " ${arg}\n")
  366. endif()
  367. endforeach()
  368. if(series_option)
  369. if(data_is_directory)
  370. message(FATAL_ERROR "Series option \"${series_option}\" not allowed with directories.")
  371. endif()
  372. if(associated_files OR associated_regex)
  373. message(FATAL_ERROR "Series option \"${series_option}\" not allowed with associated files.")
  374. endif()
  375. # Load a whole file series.
  376. _ExternalData_arg_series()
  377. elseif(data_is_directory)
  378. if(associated_files OR associated_regex)
  379. # Load listed/matching associated files in the directory.
  380. _ExternalData_arg_associated()
  381. else()
  382. message(FATAL_ERROR "Data directory referenced by argument\n"
  383. " ${arg}\n"
  384. "must list associated files.")
  385. endif()
  386. else()
  387. # Load the named data file.
  388. _ExternalData_arg_single()
  389. if(associated_files OR associated_regex)
  390. # Load listed/matching associated files.
  391. _ExternalData_arg_associated()
  392. endif()
  393. endif()
  394. if(NOT have_original)
  395. message(FATAL_ERROR "Data file referenced by argument\n"
  396. " ${arg}\n"
  397. "corresponds to source tree path\n"
  398. " ${reldata}\n"
  399. "that does not exist as a file (with or without an extension)!")
  400. endif()
  401. if(external)
  402. # Make the series available in the build tree.
  403. set_property(GLOBAL APPEND PROPERTY
  404. _ExternalData_${target}_FETCH "${external}")
  405. set_property(GLOBAL APPEND PROPERTY
  406. _ExternalData_${target}_LOCAL "${internal}")
  407. set("${var_file}" "${top_bin}/${reldata}" PARENT_SCOPE)
  408. else()
  409. # The whole series is in the source tree.
  410. set("${var_file}" "${top_src}/${reldata}" PARENT_SCOPE)
  411. endif()
  412. endfunction()
  413. macro(_ExternalData_arg_associated)
  414. # Associated files lie in the same directory.
  415. if(data_is_directory)
  416. set(reldir "${reldata}")
  417. else()
  418. get_filename_component(reldir "${reldata}" PATH)
  419. endif()
  420. if(reldir)
  421. set(reldir "${reldir}/")
  422. endif()
  423. _ExternalData_exact_regex(reldir_regex "${reldir}")
  424. # Find files named explicitly.
  425. foreach(file ${associated_files})
  426. _ExternalData_exact_regex(file_regex "${file}")
  427. _ExternalData_arg_find_files("${reldir}${file}" "${reldir_regex}${file_regex}")
  428. endforeach()
  429. # Find files matching the given regular expressions.
  430. set(all "")
  431. set(sep "")
  432. foreach(regex ${associated_regex})
  433. set(all "${all}${sep}${reldir_regex}${regex}")
  434. set(sep "|")
  435. endforeach()
  436. _ExternalData_arg_find_files("${reldir}" "${all}")
  437. endmacro()
  438. macro(_ExternalData_arg_single)
  439. # Match only the named data by itself.
  440. _ExternalData_exact_regex(data_regex "${reldata}")
  441. _ExternalData_arg_find_files("${reldata}" "${data_regex}")
  442. endmacro()
  443. macro(_ExternalData_arg_series)
  444. # Configure series parsing and matching.
  445. set(series_parse_prefix "")
  446. set(series_parse_number "\\1")
  447. set(series_parse_suffix "\\2")
  448. if(ExternalData_SERIES_PARSE)
  449. if(ExternalData_SERIES_PARSE_NUMBER AND ExternalData_SERIES_PARSE_SUFFIX)
  450. if(ExternalData_SERIES_PARSE_PREFIX)
  451. set(series_parse_prefix "\\${ExternalData_SERIES_PARSE_PREFIX}")
  452. endif()
  453. set(series_parse_number "\\${ExternalData_SERIES_PARSE_NUMBER}")
  454. set(series_parse_suffix "\\${ExternalData_SERIES_PARSE_SUFFIX}")
  455. elseif(NOT "x${ExternalData_SERIES_PARSE}" MATCHES "^x\\([^()]*\\)\\([^()]*\\)\\$$")
  456. message(FATAL_ERROR
  457. "ExternalData_SERIES_PARSE is set to\n"
  458. " ${ExternalData_SERIES_PARSE}\n"
  459. "which is not of the form\n"
  460. " (<number>)(<suffix>)$\n"
  461. "Fix the regular expression or set variables\n"
  462. " ExternalData_SERIES_PARSE_PREFIX = <prefix> regex group number, if any\n"
  463. " ExternalData_SERIES_PARSE_NUMBER = <number> regex group number\n"
  464. " ExternalData_SERIES_PARSE_SUFFIX = <suffix> regex group number\n"
  465. )
  466. endif()
  467. set(series_parse "${ExternalData_SERIES_PARSE}")
  468. else()
  469. set(series_parse "([0-9]*)(\\.[^./]*)$")
  470. endif()
  471. if(ExternalData_SERIES_MATCH)
  472. set(series_match "${ExternalData_SERIES_MATCH}")
  473. else()
  474. set(series_match "[_.-]?[0-9]*")
  475. endif()
  476. # Parse the base, number, and extension components of the series.
  477. string(REGEX REPLACE "${series_parse}" "${series_parse_prefix};${series_parse_number};${series_parse_suffix}" tuple "${reldata}")
  478. list(LENGTH tuple len)
  479. if(NOT "${len}" EQUAL 3)
  480. message(FATAL_ERROR "Data file referenced by argument\n"
  481. " ${arg}\n"
  482. "corresponds to path\n"
  483. " ${reldata}\n"
  484. "that does not match regular expression\n"
  485. " ${series_parse}")
  486. endif()
  487. list(GET tuple 0 relbase)
  488. list(GET tuple 2 ext)
  489. # Glob files that might match the series.
  490. # Then match base, number, and extension.
  491. _ExternalData_exact_regex(series_base "${relbase}")
  492. _ExternalData_exact_regex(series_ext "${ext}")
  493. _ExternalData_arg_find_files("${relbase}*${ext}"
  494. "${series_base}${series_match}${series_ext}")
  495. endmacro()
  496. function(_ExternalData_arg_find_files pattern regex)
  497. file(GLOB globbed RELATIVE "${top_src}" "${top_src}/${pattern}*")
  498. foreach(entry IN LISTS globbed)
  499. if("x${entry}" MATCHES "^x(.*)(\\.(${_ExternalData_REGEX_EXT}))$")
  500. set(relname "${CMAKE_MATCH_1}")
  501. set(alg "${CMAKE_MATCH_2}")
  502. else()
  503. set(relname "${entry}")
  504. set(alg "")
  505. endif()
  506. if("x${relname}" MATCHES "^x${regex}$" AND NOT IS_DIRECTORY "${top_src}/${entry}")
  507. set(name "${top_src}/${relname}")
  508. set(file "${top_bin}/${relname}")
  509. if(alg)
  510. list(APPEND external "${file}|${name}|${alg}")
  511. elseif(ExternalData_LINK_CONTENT)
  512. _ExternalData_link_content("${name}" alg)
  513. list(APPEND external "${file}|${name}|${alg}")
  514. elseif(NOT top_same)
  515. list(APPEND internal "${file}|${name}")
  516. endif()
  517. if("${relname}" STREQUAL "${reldata}")
  518. set(have_original 1)
  519. endif()
  520. endif()
  521. endforeach()
  522. set(external "${external}" PARENT_SCOPE)
  523. set(internal "${internal}" PARENT_SCOPE)
  524. set(have_original "${have_original}" PARENT_SCOPE)
  525. endfunction()
  526. #-----------------------------------------------------------------------------
  527. # Private script mode interface
  528. if(CMAKE_GENERATOR OR NOT ExternalData_ACTION)
  529. return()
  530. endif()
  531. if(ExternalData_CONFIG)
  532. include(${ExternalData_CONFIG})
  533. endif()
  534. if(NOT ExternalData_URL_TEMPLATES)
  535. message(FATAL_ERROR "No ExternalData_URL_TEMPLATES set!")
  536. endif()
  537. function(_ExternalData_link_or_copy src dst)
  538. # Create a temporary file first.
  539. get_filename_component(dst_dir "${dst}" PATH)
  540. file(MAKE_DIRECTORY "${dst_dir}")
  541. _ExternalData_random(random)
  542. set(tmp "${dst}.tmp${random}")
  543. if(UNIX)
  544. # Create a symbolic link.
  545. set(tgt "${src}")
  546. if(relative_top)
  547. # Use relative path if files are close enough.
  548. file(RELATIVE_PATH relsrc "${relative_top}" "${src}")
  549. file(RELATIVE_PATH relfile "${relative_top}" "${dst}")
  550. if(NOT IS_ABSOLUTE "${relsrc}" AND NOT "${relsrc}" MATCHES "^\\.\\./" AND
  551. NOT IS_ABSOLUTE "${reldst}" AND NOT "${reldst}" MATCHES "^\\.\\./")
  552. file(RELATIVE_PATH tgt "${dst_dir}" "${src}")
  553. endif()
  554. endif()
  555. execute_process(COMMAND "${CMAKE_COMMAND}" -E create_symlink "${tgt}" "${tmp}" RESULT_VARIABLE result)
  556. else()
  557. # Create a copy.
  558. execute_process(COMMAND "${CMAKE_COMMAND}" -E copy "${src}" "${tmp}" RESULT_VARIABLE result)
  559. endif()
  560. if(result)
  561. file(REMOVE "${tmp}")
  562. message(FATAL_ERROR "Failed to create\n ${tmp}\nfrom\n ${obj}")
  563. endif()
  564. # Atomically create/replace the real destination.
  565. file(RENAME "${tmp}" "${dst}")
  566. endfunction()
  567. function(_ExternalData_download_file url file err_var msg_var)
  568. set(retry 3)
  569. while(retry)
  570. math(EXPR retry "${retry} - 1")
  571. if(ExternalData_TIMEOUT_INACTIVITY)
  572. set(inactivity_timeout INACTIVITY_TIMEOUT ${ExternalData_TIMEOUT_INACTIVITY})
  573. elseif(NOT "${ExternalData_TIMEOUT_INACTIVITY}" EQUAL 0)
  574. set(inactivity_timeout INACTIVITY_TIMEOUT 60)
  575. else()
  576. set(inactivity_timeout "")
  577. endif()
  578. if(ExternalData_TIMEOUT_ABSOLUTE)
  579. set(absolute_timeout TIMEOUT ${ExternalData_TIMEOUT_ABSOLUTE})
  580. elseif(NOT "${ExternalData_TIMEOUT_ABSOLUTE}" EQUAL 0)
  581. set(absolute_timeout TIMEOUT 300)
  582. else()
  583. set(absolute_timeout "")
  584. endif()
  585. file(DOWNLOAD "${url}" "${file}" STATUS status LOG log ${inactivity_timeout} ${absolute_timeout} SHOW_PROGRESS)
  586. list(GET status 0 err)
  587. list(GET status 1 msg)
  588. if(err)
  589. if("${msg}" MATCHES "HTTP response code said error" AND
  590. "${log}" MATCHES "error: 503")
  591. set(msg "temporarily unavailable")
  592. endif()
  593. elseif("${log}" MATCHES "\nHTTP[^\n]* 503")
  594. set(err TRUE)
  595. set(msg "temporarily unavailable")
  596. endif()
  597. if(NOT err OR NOT "${msg}" MATCHES "partial|timeout|temporarily")
  598. break()
  599. elseif(retry)
  600. message(STATUS "[download terminated: ${msg}, retries left: ${retry}]")
  601. endif()
  602. endwhile()
  603. set("${err_var}" "${err}" PARENT_SCOPE)
  604. set("${msg_var}" "${msg}" PARENT_SCOPE)
  605. endfunction()
  606. function(_ExternalData_download_object name hash algo var_obj)
  607. # Search all object stores for an existing object.
  608. foreach(dir ${ExternalData_OBJECT_STORES})
  609. set(obj "${dir}/${algo}/${hash}")
  610. if(EXISTS "${obj}")
  611. message(STATUS "Found object: \"${obj}\"")
  612. set("${var_obj}" "${obj}" PARENT_SCOPE)
  613. return()
  614. endif()
  615. endforeach()
  616. # Download object to the first store.
  617. list(GET ExternalData_OBJECT_STORES 0 store)
  618. set(obj "${store}/${algo}/${hash}")
  619. _ExternalData_random(random)
  620. set(tmp "${obj}.tmp${random}")
  621. set(found 0)
  622. set(tried "")
  623. foreach(url_template IN LISTS ExternalData_URL_TEMPLATES)
  624. string(REPLACE "%(hash)" "${hash}" url_tmp "${url_template}")
  625. string(REPLACE "%(algo)" "${algo}" url "${url_tmp}")
  626. message(STATUS "Fetching \"${url}\"")
  627. _ExternalData_download_file("${url}" "${tmp}" err errMsg)
  628. set(tried "${tried}\n ${url}")
  629. if(err)
  630. set(tried "${tried} (${errMsg})")
  631. else()
  632. # Verify downloaded object.
  633. _ExternalData_compute_hash(dl_hash "${algo}" "${tmp}")
  634. if("${dl_hash}" STREQUAL "${hash}")
  635. set(found 1)
  636. break()
  637. else()
  638. set(tried "${tried} (wrong hash ${algo}=${dl_hash})")
  639. if("$ENV{ExternalData_DEBUG_DOWNLOAD}" MATCHES ".")
  640. file(RENAME "${tmp}" "${store}/${algo}/${dl_hash}")
  641. endif()
  642. endif()
  643. endif()
  644. file(REMOVE "${tmp}")
  645. endforeach()
  646. get_filename_component(dir "${name}" PATH)
  647. set(staged "${dir}/.ExternalData_${algo}_${hash}")
  648. if(found)
  649. file(RENAME "${tmp}" "${obj}")
  650. message(STATUS "Downloaded object: \"${obj}\"")
  651. elseif(EXISTS "${staged}")
  652. set(obj "${staged}")
  653. message(STATUS "Staged object: \"${obj}\"")
  654. else()
  655. message(FATAL_ERROR "Object ${algo}=${hash} not found at:${tried}")
  656. endif()
  657. set("${var_obj}" "${obj}" PARENT_SCOPE)
  658. endfunction()
  659. if("${ExternalData_ACTION}" STREQUAL "fetch")
  660. foreach(v ExternalData_OBJECT_STORES file name ext)
  661. if(NOT DEFINED "${v}")
  662. message(FATAL_ERROR "No \"-D${v}=\" value provided!")
  663. endif()
  664. endforeach()
  665. file(READ "${name}${ext}" hash)
  666. string(STRIP "${hash}" hash)
  667. if("${ext}" MATCHES "^\\.(${_ExternalData_REGEX_EXT})$")
  668. string(TOUPPER "${CMAKE_MATCH_1}" algo)
  669. else()
  670. message(FATAL_ERROR "Unknown hash algorithm extension \"${ext}\"")
  671. endif()
  672. _ExternalData_download_object("${name}" "${hash}" "${algo}" obj)
  673. # Check if file already corresponds to the object.
  674. set(stamp "${ext}-stamp")
  675. set(file_up_to_date 0)
  676. if(EXISTS "${file}" AND EXISTS "${file}${stamp}")
  677. file(READ "${file}${stamp}" f_hash)
  678. string(STRIP "${f_hash}" f_hash)
  679. if("${f_hash}" STREQUAL "${hash}")
  680. #message(STATUS "File already corresponds to object")
  681. set(file_up_to_date 1)
  682. endif()
  683. endif()
  684. if(file_up_to_date)
  685. # Touch the file to convince the build system it is up to date.
  686. execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${file}")
  687. else()
  688. _ExternalData_link_or_copy("${obj}" "${file}")
  689. endif()
  690. # Atomically update the hash/timestamp file to record the object referenced.
  691. _ExternalData_atomic_write("${file}${stamp}" "${hash}\n")
  692. elseif("${ExternalData_ACTION}" STREQUAL "local")
  693. foreach(v file name)
  694. if(NOT DEFINED "${v}")
  695. message(FATAL_ERROR "No \"-D${v}=\" value provided!")
  696. endif()
  697. endforeach()
  698. _ExternalData_link_or_copy("${name}" "${file}")
  699. else()
  700. message(FATAL_ERROR "Unknown ExternalData_ACTION=[${ExternalData_ACTION}]")
  701. endif()