ExternalData.cmake 27 KB

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