ExternalData.cmake 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. ExternalData
  5. ------------
  6. .. only:: html
  7. .. contents::
  8. Manage data files stored outside source tree
  9. Introduction
  10. ^^^^^^^^^^^^
  11. Use this module to unambiguously reference data files stored outside
  12. the source tree and fetch them at build time from arbitrary local and
  13. remote content-addressed locations. Functions provided by this module
  14. recognize arguments with the syntax ``DATA{<name>}`` as references to
  15. external data, replace them with full paths to local copies of those
  16. data, and create build rules to fetch and update the local copies.
  17. For example:
  18. .. code-block:: cmake
  19. include(ExternalData)
  20. set(ExternalData_URL_TEMPLATES "file:///local/%(algo)/%(hash)"
  21. "file:////host/share/%(algo)/%(hash)"
  22. "http://data.org/%(algo)/%(hash)")
  23. ExternalData_Add_Test(MyData
  24. NAME MyTest
  25. COMMAND MyExe DATA{MyInput.png}
  26. )
  27. ExternalData_Add_Target(MyData)
  28. When test ``MyTest`` runs the ``DATA{MyInput.png}`` argument will be
  29. replaced by the full path to a real instance of the data file
  30. ``MyInput.png`` on disk. If the source tree contains a content link
  31. such as ``MyInput.png.md5`` then the ``MyData`` target creates a real
  32. ``MyInput.png`` in the build tree.
  33. Module Functions
  34. ^^^^^^^^^^^^^^^^
  35. .. command:: ExternalData_Expand_Arguments
  36. The ``ExternalData_Expand_Arguments`` function evaluates ``DATA{}``
  37. references in its arguments and constructs a new list of arguments::
  38. ExternalData_Expand_Arguments(
  39. <target> # Name of data management target
  40. <outVar> # Output variable
  41. [args...] # Input arguments, DATA{} allowed
  42. )
  43. It replaces each ``DATA{}`` reference in an argument with the full path of
  44. a real data file on disk that will exist after the ``<target>`` builds.
  45. .. command:: ExternalData_Add_Test
  46. The ``ExternalData_Add_Test`` function wraps around the CMake
  47. :command:`add_test` command but supports ``DATA{}`` references in
  48. its arguments::
  49. ExternalData_Add_Test(
  50. <target> # Name of data management target
  51. ... # Arguments of add_test(), DATA{} allowed
  52. )
  53. It passes its arguments through ``ExternalData_Expand_Arguments`` and then
  54. invokes the :command:`add_test` command using the results.
  55. .. command:: ExternalData_Add_Target
  56. The ``ExternalData_Add_Target`` function creates a custom target to
  57. manage local instances of data files stored externally::
  58. ExternalData_Add_Target(
  59. <target> # Name of data management target
  60. )
  61. It creates custom commands in the target as necessary to make data
  62. files available for each ``DATA{}`` reference previously evaluated by
  63. other functions provided by this module.
  64. Data files may be fetched from one of the URL templates specified in
  65. the ``ExternalData_URL_TEMPLATES`` variable, or may be found locally
  66. in one of the paths specified in the ``ExternalData_OBJECT_STORES``
  67. variable.
  68. Typically only one target is needed to manage all external data within
  69. a project. Call this function once at the end of configuration after
  70. all data references have been processed.
  71. Module Variables
  72. ^^^^^^^^^^^^^^^^
  73. The following variables configure behavior. They should be set before
  74. calling any of the functions provided by this module.
  75. .. variable:: ExternalData_BINARY_ROOT
  76. The ``ExternalData_BINARY_ROOT`` variable may be set to the directory to
  77. hold the real data files named by expanded ``DATA{}`` references. The
  78. default is ``CMAKE_BINARY_DIR``. The directory layout will mirror that of
  79. content links under ``ExternalData_SOURCE_ROOT``.
  80. .. variable:: ExternalData_CUSTOM_SCRIPT_<key>
  81. Specify a full path to a ``.cmake`` custom fetch script identified by
  82. ``<key>`` in entries of the ``ExternalData_URL_TEMPLATES`` list.
  83. See `Custom Fetch Scripts`_.
  84. .. variable:: ExternalData_LINK_CONTENT
  85. The ``ExternalData_LINK_CONTENT`` variable may be set to the name of a
  86. supported hash algorithm to enable automatic conversion of real data
  87. files referenced by the ``DATA{}`` syntax into content links. For each
  88. such ``<file>`` a content link named ``<file><ext>`` is created. The
  89. original file is renamed to the form ``.ExternalData_<algo>_<hash>`` to
  90. stage it for future transmission to one of the locations in the list
  91. of URL templates (by means outside the scope of this module). The
  92. data fetch rule created for the content link will use the staged
  93. object if it cannot be found using any URL template.
  94. .. variable:: ExternalData_NO_SYMLINKS
  95. The real data files named by expanded ``DATA{}`` references may be made
  96. available under ``ExternalData_BINARY_ROOT`` using symbolic links on
  97. some platforms. The ``ExternalData_NO_SYMLINKS`` variable may be set
  98. to disable use of symbolic links and enable use of copies instead.
  99. .. variable:: ExternalData_OBJECT_STORES
  100. The ``ExternalData_OBJECT_STORES`` variable may be set to a list of local
  101. directories that store objects using the layout ``<dir>/%(algo)/%(hash)``.
  102. These directories will be searched first for a needed object. If the
  103. object is not available in any store then it will be fetched remotely
  104. using the URL templates and added to the first local store listed. If
  105. no stores are specified the default is a location inside the build
  106. tree.
  107. .. variable:: ExternalData_SERIES_PARSE
  108. ExternalData_SERIES_PARSE_PREFIX
  109. ExternalData_SERIES_PARSE_NUMBER
  110. ExternalData_SERIES_PARSE_SUFFIX
  111. ExternalData_SERIES_MATCH
  112. See `Referencing File Series`_.
  113. .. variable:: ExternalData_SOURCE_ROOT
  114. The ``ExternalData_SOURCE_ROOT`` variable may be set to the highest source
  115. directory containing any path named by a ``DATA{}`` reference. The
  116. default is ``CMAKE_SOURCE_DIR``. ``ExternalData_SOURCE_ROOT`` and
  117. ``CMAKE_SOURCE_DIR`` must refer to directories within a single source
  118. distribution (e.g. they come together in one tarball).
  119. .. variable:: ExternalData_TIMEOUT_ABSOLUTE
  120. The ``ExternalData_TIMEOUT_ABSOLUTE`` variable sets the download
  121. absolute timeout, in seconds, with a default of ``300`` seconds.
  122. Set to ``0`` to disable enforcement.
  123. .. variable:: ExternalData_TIMEOUT_INACTIVITY
  124. The ``ExternalData_TIMEOUT_INACTIVITY`` variable sets the download
  125. inactivity timeout, in seconds, with a default of ``60`` seconds.
  126. Set to ``0`` to disable enforcement.
  127. .. variable:: ExternalData_URL_ALGO_<algo>_<key>
  128. Specify a custom URL component to be substituted for URL template
  129. placeholders of the form ``%(algo:<key>)``, where ``<key>`` is a
  130. valid C identifier, when fetching an object referenced via hash
  131. algorithm ``<algo>``. If not defined, the default URL component
  132. is just ``<algo>`` for any ``<key>``.
  133. .. variable:: ExternalData_URL_TEMPLATES
  134. The ``ExternalData_URL_TEMPLATES`` may be set to provide a list of
  135. of URL templates using the placeholders ``%(algo)`` and ``%(hash)``
  136. in each template. Data fetch rules try each URL template in order
  137. by substituting the hash algorithm name for ``%(algo)`` and the hash
  138. value for ``%(hash)``. Alternatively one may use ``%(algo:<key>)``
  139. with ``ExternalData_URL_ALGO_<algo>_<key>`` variables to gain more
  140. flexibility in remote URLs.
  141. Referencing Files
  142. ^^^^^^^^^^^^^^^^^
  143. Referencing Single Files
  144. """"""""""""""""""""""""
  145. The ``DATA{}`` syntax is literal and the ``<name>`` is a full or relative path
  146. within the source tree. The source tree must contain either a real
  147. data file at ``<name>`` or a "content link" at ``<name><ext>`` containing a
  148. hash of the real file using a hash algorithm corresponding to ``<ext>``.
  149. For example, the argument ``DATA{img.png}`` may be satisfied by either a
  150. real ``img.png`` file in the current source directory or a ``img.png.md5``
  151. file containing its MD5 sum.
  152. Multiple content links of the same name with different hash algorithms
  153. are supported (e.g. ``img.png.sha256`` and ``img.png.sha1``) so long as
  154. they all correspond to the same real file. This allows objects to be
  155. fetched from sources indexed by different hash algorithms.
  156. Referencing File Series
  157. """""""""""""""""""""""
  158. The ``DATA{}`` syntax can be told to fetch a file series using the form
  159. ``DATA{<name>,:}``, where the ``:`` is literal. If the source tree
  160. contains a group of files or content links named like a series then a
  161. reference to one member adds rules to fetch all of them. Although all
  162. members of a series are fetched, only the file originally named by the
  163. ``DATA{}`` argument is substituted for it. The default configuration
  164. recognizes file series names ending with ``#.ext``, ``_#.ext``, ``.#.ext``,
  165. or ``-#.ext`` where ``#`` is a sequence of decimal digits and ``.ext`` is
  166. any single extension. Configure it with a regex that parses ``<number>``
  167. and ``<suffix>`` parts from the end of ``<name>``::
  168. ExternalData_SERIES_PARSE = regex of the form (<number>)(<suffix>)$
  169. For more complicated cases set::
  170. ExternalData_SERIES_PARSE = regex with at least two () groups
  171. ExternalData_SERIES_PARSE_PREFIX = <prefix> regex group number, if any
  172. ExternalData_SERIES_PARSE_NUMBER = <number> regex group number
  173. ExternalData_SERIES_PARSE_SUFFIX = <suffix> regex group number
  174. Configure series number matching with a regex that matches the
  175. ``<number>`` part of series members named ``<prefix><number><suffix>``::
  176. ExternalData_SERIES_MATCH = regex matching <number> in all series members
  177. Note that the ``<suffix>`` of a series does not include a hash-algorithm
  178. extension.
  179. Referencing Associated Files
  180. """"""""""""""""""""""""""""
  181. The ``DATA{}`` syntax can alternatively match files associated with the
  182. named file and contained in the same directory. Associated files may
  183. be specified by options using the syntax
  184. ``DATA{<name>,<opt1>,<opt2>,...}``. Each option may specify one file by
  185. name or specify a regular expression to match file names using the
  186. syntax ``REGEX:<regex>``. For example, the arguments::
  187. DATA{MyData/MyInput.mhd,MyInput.img} # File pair
  188. DATA{MyData/MyFrames00.png,REGEX:MyFrames[0-9]+\\.png} # Series
  189. will pass ``MyInput.mha`` and ``MyFrames00.png`` on the command line but
  190. ensure that the associated files are present next to them.
  191. Referencing Directories
  192. """""""""""""""""""""""
  193. The ``DATA{}`` syntax may reference a directory using a trailing slash and
  194. a list of associated files. The form ``DATA{<name>/,<opt1>,<opt2>,...}``
  195. adds rules to fetch any files in the directory that match one of the
  196. associated file options. For example, the argument
  197. ``DATA{MyDataDir/,REGEX:.*}`` will pass the full path to a ``MyDataDir``
  198. directory on the command line and ensure that the directory contains
  199. files corresponding to every file or content link in the ``MyDataDir``
  200. source directory. In order to match associated files in subdirectories,
  201. specify a ``RECURSE:`` option, e.g. ``DATA{MyDataDir/,RECURSE:,REGEX:.*}``.
  202. Hash Algorithms
  203. ^^^^^^^^^^^^^^^
  204. The following hash algorithms are supported::
  205. %(algo) <ext> Description
  206. ------- ----- -----------
  207. MD5 .md5 Message-Digest Algorithm 5, RFC 1321
  208. SHA1 .sha1 US Secure Hash Algorithm 1, RFC 3174
  209. SHA224 .sha224 US Secure Hash Algorithms, RFC 4634
  210. SHA256 .sha256 US Secure Hash Algorithms, RFC 4634
  211. SHA384 .sha384 US Secure Hash Algorithms, RFC 4634
  212. SHA512 .sha512 US Secure Hash Algorithms, RFC 4634
  213. SHA3_224 .sha3-224 Keccak SHA-3
  214. SHA3_256 .sha3-256 Keccak SHA-3
  215. SHA3_384 .sha3-384 Keccak SHA-3
  216. SHA3_512 .sha3-512 Keccak SHA-3
  217. Note that the hashes are used only for unique data identification and
  218. download verification.
  219. .. _`ExternalData Custom Fetch Scripts`:
  220. Custom Fetch Scripts
  221. ^^^^^^^^^^^^^^^^^^^^
  222. When a data file must be fetched from one of the URL templates
  223. specified in the ``ExternalData_URL_TEMPLATES`` variable, it is
  224. normally downloaded using the :command:`file(DOWNLOAD)` command.
  225. One may specify usage of a custom fetch script by using a URL
  226. template of the form ``ExternalDataCustomScript://<key>/<loc>``.
  227. The ``<key>`` must be a C identifier, and the ``<loc>`` must
  228. contain the ``%(algo)`` and ``%(hash)`` placeholders.
  229. A variable corresponding to the key, ``ExternalData_CUSTOM_SCRIPT_<key>``,
  230. must be set to the full path to a ``.cmake`` script file. The script
  231. will be included to perform the actual fetch, and provided with
  232. the following variables:
  233. .. variable:: ExternalData_CUSTOM_LOCATION
  234. When a custom fetch script is loaded, this variable is set to the
  235. location part of the URL, which will contain the substituted hash
  236. algorithm name and content hash value.
  237. .. variable:: ExternalData_CUSTOM_FILE
  238. When a custom fetch script is loaded, this variable is set to the
  239. full path to a file in which the script must store the fetched
  240. content. The name of the file is unspecified and should not be
  241. interpreted in any way.
  242. The custom fetch script is expected to store fetched content in the
  243. file or set a variable:
  244. .. variable:: ExternalData_CUSTOM_ERROR
  245. When a custom fetch script fails to fetch the requested content,
  246. it must set this variable to a short one-line message describing
  247. the reason for failure.
  248. #]=======================================================================]
  249. function(ExternalData_add_test target)
  250. # Expand all arguments as a single string to preserve escaped semicolons.
  251. ExternalData_expand_arguments("${target}" testArgs "${ARGN}")
  252. add_test(${testArgs})
  253. endfunction()
  254. function(ExternalData_add_target target)
  255. if(NOT ExternalData_URL_TEMPLATES AND NOT ExternalData_OBJECT_STORES)
  256. message(FATAL_ERROR
  257. "Neither ExternalData_URL_TEMPLATES nor ExternalData_OBJECT_STORES is set!")
  258. endif()
  259. if(NOT ExternalData_OBJECT_STORES)
  260. set(ExternalData_OBJECT_STORES ${CMAKE_BINARY_DIR}/ExternalData/Objects)
  261. endif()
  262. set(_ExternalData_CONFIG_CODE "")
  263. # Store custom script configuration.
  264. foreach(url_template IN LISTS ExternalData_URL_TEMPLATES)
  265. if("${url_template}" MATCHES "^ExternalDataCustomScript://([^/]*)/(.*)$")
  266. set(key "${CMAKE_MATCH_1}")
  267. if(key MATCHES "^[A-Za-z_][A-Za-z0-9_]*$")
  268. if(ExternalData_CUSTOM_SCRIPT_${key})
  269. if(IS_ABSOLUTE "${ExternalData_CUSTOM_SCRIPT_${key}}")
  270. string(CONCAT _ExternalData_CONFIG_CODE "${_ExternalData_CONFIG_CODE}\n"
  271. "set(ExternalData_CUSTOM_SCRIPT_${key} \"${ExternalData_CUSTOM_SCRIPT_${key}}\")")
  272. else()
  273. message(FATAL_ERROR
  274. "No ExternalData_CUSTOM_SCRIPT_${key} is not set to a full path:\n"
  275. " ${ExternalData_CUSTOM_SCRIPT_${key}}")
  276. endif()
  277. else()
  278. message(FATAL_ERROR
  279. "No ExternalData_CUSTOM_SCRIPT_${key} is set for URL template:\n"
  280. " ${url_template}")
  281. endif()
  282. else()
  283. message(FATAL_ERROR
  284. "Bad ExternalDataCustomScript key '${key}' in URL template:\n"
  285. " ${url_template}\n"
  286. "The key must be a valid C identifier.")
  287. endif()
  288. endif()
  289. # Store custom algorithm name to URL component maps.
  290. if("${url_template}" MATCHES "%\\(algo:([^)]*)\\)")
  291. set(key "${CMAKE_MATCH_1}")
  292. if(key MATCHES "^[A-Za-z_][A-Za-z0-9_]*$")
  293. string(REPLACE "|" ";" _algos "${_ExternalData_REGEX_ALGO}")
  294. foreach(algo ${_algos})
  295. if(DEFINED ExternalData_URL_ALGO_${algo}_${key})
  296. string(CONCAT _ExternalData_CONFIG_CODE "${_ExternalData_CONFIG_CODE}\n"
  297. "set(ExternalData_URL_ALGO_${algo}_${key} \"${ExternalData_URL_ALGO_${algo}_${key}}\")")
  298. endif()
  299. endforeach()
  300. else()
  301. message(FATAL_ERROR
  302. "Bad %(algo:${key}) in URL template:\n"
  303. " ${url_template}\n"
  304. "The transform name must be a valid C identifier.")
  305. endif()
  306. endif()
  307. endforeach()
  308. # Store configuration for use by build-time script.
  309. set(config ${CMAKE_CURRENT_BINARY_DIR}/${target}_config.cmake)
  310. configure_file(${_ExternalData_SELF_DIR}/ExternalData_config.cmake.in ${config} @ONLY)
  311. set(files "")
  312. # Set a "_ExternalData_FILE_${file}" variable for each output file to avoid
  313. # duplicate entries within this target. Set a directory property of the same
  314. # name to avoid repeating custom commands with the same output in this directory.
  315. # Repeating custom commands with the same output across directories or across
  316. # targets in the same directory may be a race, but this is likely okay because
  317. # we use atomic replacement of output files.
  318. #
  319. # Use local data first to prefer real files over content links.
  320. # Custom commands to copy or link local data.
  321. get_property(data_local GLOBAL PROPERTY _ExternalData_${target}_LOCAL)
  322. foreach(entry IN LISTS data_local)
  323. string(REPLACE "|" ";" tuple "${entry}")
  324. list(GET tuple 0 file)
  325. list(GET tuple 1 name)
  326. if(NOT DEFINED "_ExternalData_FILE_${file}")
  327. set("_ExternalData_FILE_${file}" 1)
  328. get_property(added DIRECTORY PROPERTY "_ExternalData_FILE_${file}")
  329. if(NOT added)
  330. set_property(DIRECTORY PROPERTY "_ExternalData_FILE_${file}" 1)
  331. add_custom_command(
  332. COMMENT "Generating ${file}"
  333. OUTPUT "${file}"
  334. COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
  335. -Dfile=${file} -Dname=${name}
  336. -DExternalData_ACTION=local
  337. -DExternalData_CONFIG=${config}
  338. -P ${_ExternalData_SELF}
  339. MAIN_DEPENDENCY "${name}"
  340. )
  341. endif()
  342. list(APPEND files "${file}")
  343. endif()
  344. endforeach()
  345. # Custom commands to fetch remote data.
  346. get_property(data_fetch GLOBAL PROPERTY _ExternalData_${target}_FETCH)
  347. foreach(entry IN LISTS data_fetch)
  348. string(REPLACE "|" ";" tuple "${entry}")
  349. list(GET tuple 0 file)
  350. list(GET tuple 1 name)
  351. list(GET tuple 2 exts)
  352. string(REPLACE "+" ";" exts_list "${exts}")
  353. list(GET exts_list 0 first_ext)
  354. set(stamp "-hash-stamp")
  355. if(NOT DEFINED "_ExternalData_FILE_${file}")
  356. set("_ExternalData_FILE_${file}" 1)
  357. get_property(added DIRECTORY PROPERTY "_ExternalData_FILE_${file}")
  358. if(NOT added)
  359. set_property(DIRECTORY PROPERTY "_ExternalData_FILE_${file}" 1)
  360. add_custom_command(
  361. # Users care about the data file, so hide the hash/timestamp file.
  362. COMMENT "Generating ${file}"
  363. # The hash/timestamp file is the output from the build perspective.
  364. # List the real file as a second output in case it is a broken link.
  365. # The files must be listed in this order so CMake can hide from the
  366. # make tool that a symlink target may not be newer than the input.
  367. OUTPUT "${file}${stamp}" "${file}"
  368. # Run the data fetch/update script.
  369. COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
  370. -Dfile=${file} -Dname=${name} -Dexts=${exts}
  371. -DExternalData_ACTION=fetch
  372. -DExternalData_CONFIG=${config}
  373. -P ${_ExternalData_SELF}
  374. # Update whenever the object hash changes.
  375. MAIN_DEPENDENCY "${name}${first_ext}"
  376. )
  377. endif()
  378. list(APPEND files "${file}${stamp}")
  379. endif()
  380. endforeach()
  381. # Custom target to drive all update commands.
  382. add_custom_target(${target} ALL DEPENDS ${files})
  383. endfunction()
  384. function(ExternalData_expand_arguments target outArgsVar)
  385. # Replace DATA{} references with real arguments.
  386. set(data_regex "DATA{([^;{}\r\n]*)}")
  387. set(other_regex "([^D]|D[^A]|DA[^T]|DAT[^A]|DATA[^{])+|.")
  388. set(outArgs "")
  389. # This list expansion un-escapes semicolons in list element values so we
  390. # must re-escape them below anywhere a new list expansion will occur.
  391. foreach(arg IN LISTS ARGN)
  392. if("x${arg}" MATCHES "${data_regex}")
  393. # Re-escape in-value semicolons before expansion in foreach below.
  394. string(REPLACE ";" "\\;" tmp "${arg}")
  395. # Split argument into DATA{}-pieces and other pieces.
  396. string(REGEX MATCHALL "${data_regex}|${other_regex}" pieces "${tmp}")
  397. # Compose output argument with DATA{}-pieces replaced.
  398. set(outArg "")
  399. foreach(piece IN LISTS pieces)
  400. if("x${piece}" MATCHES "^x${data_regex}$")
  401. # Replace this DATA{}-piece with a file path.
  402. _ExternalData_arg("${target}" "${piece}" "${CMAKE_MATCH_1}" file)
  403. string(APPEND outArg "${file}")
  404. else()
  405. # No replacement needed for this piece.
  406. string(APPEND outArg "${piece}")
  407. endif()
  408. endforeach()
  409. else()
  410. # No replacements needed in this argument.
  411. set(outArg "${arg}")
  412. endif()
  413. # Re-escape in-value semicolons in resulting list.
  414. string(REPLACE ";" "\\;" outArg "${outArg}")
  415. list(APPEND outArgs "${outArg}")
  416. endforeach()
  417. set("${outArgsVar}" "${outArgs}" PARENT_SCOPE)
  418. endfunction()
  419. #-----------------------------------------------------------------------------
  420. # Private helper interface
  421. set(_ExternalData_REGEX_ALGO "MD5|SHA1|SHA224|SHA256|SHA384|SHA512|SHA3_224|SHA3_256|SHA3_384|SHA3_512")
  422. set(_ExternalData_REGEX_EXT "md5|sha1|sha224|sha256|sha384|sha512|sha3-224|sha3-256|sha3-384|sha3-512")
  423. set(_ExternalData_SELF "${CMAKE_CURRENT_LIST_FILE}")
  424. get_filename_component(_ExternalData_SELF_DIR "${_ExternalData_SELF}" PATH)
  425. function(_ExternalData_compute_hash var_hash algo file)
  426. if("${algo}" MATCHES "^${_ExternalData_REGEX_ALGO}$")
  427. file("${algo}" "${file}" hash)
  428. set("${var_hash}" "${hash}" PARENT_SCOPE)
  429. else()
  430. message(FATAL_ERROR "Hash algorithm ${algo} unimplemented.")
  431. endif()
  432. endfunction()
  433. function(_ExternalData_random var)
  434. string(RANDOM LENGTH 6 random)
  435. set("${var}" "${random}" PARENT_SCOPE)
  436. endfunction()
  437. function(_ExternalData_exact_regex regex_var string)
  438. string(REGEX REPLACE "([][+.*()^])" "\\\\\\1" regex "${string}")
  439. set("${regex_var}" "${regex}" PARENT_SCOPE)
  440. endfunction()
  441. function(_ExternalData_atomic_write file content)
  442. _ExternalData_random(random)
  443. set(tmp "${file}.tmp${random}")
  444. file(WRITE "${tmp}" "${content}")
  445. file(RENAME "${tmp}" "${file}")
  446. endfunction()
  447. function(_ExternalData_link_content name var_ext)
  448. if("${ExternalData_LINK_CONTENT}" MATCHES "^(${_ExternalData_REGEX_ALGO})$")
  449. set(algo "${ExternalData_LINK_CONTENT}")
  450. else()
  451. message(FATAL_ERROR
  452. "Unknown hash algorithm specified by ExternalData_LINK_CONTENT:\n"
  453. " ${ExternalData_LINK_CONTENT}")
  454. endif()
  455. _ExternalData_compute_hash(hash "${algo}" "${name}")
  456. get_filename_component(dir "${name}" PATH)
  457. set(staged "${dir}/.ExternalData_${algo}_${hash}")
  458. string(TOLOWER ".${algo}" ext)
  459. _ExternalData_atomic_write("${name}${ext}" "${hash}\n")
  460. file(RENAME "${name}" "${staged}")
  461. set("${var_ext}" "${ext}" PARENT_SCOPE)
  462. file(RELATIVE_PATH relname "${ExternalData_SOURCE_ROOT}" "${name}${ext}")
  463. message(STATUS "Linked ${relname} to ExternalData ${algo}/${hash}")
  464. endfunction()
  465. function(_ExternalData_arg target arg options var_file)
  466. # Separate data path from the options.
  467. string(REPLACE "," ";" options "${options}")
  468. list(GET options 0 data)
  469. list(REMOVE_AT options 0)
  470. # Interpret trailing slashes as directories.
  471. set(data_is_directory 0)
  472. if("x${data}" MATCHES "^x(.*)([/\\])$")
  473. set(data_is_directory 1)
  474. set(data "${CMAKE_MATCH_1}")
  475. endif()
  476. # Convert to full path.
  477. if(IS_ABSOLUTE "${data}")
  478. set(absdata "${data}")
  479. else()
  480. set(absdata "${CMAKE_CURRENT_SOURCE_DIR}/${data}")
  481. endif()
  482. get_filename_component(absdata "${absdata}" ABSOLUTE)
  483. # Convert to relative path under the source tree.
  484. if(NOT ExternalData_SOURCE_ROOT)
  485. set(ExternalData_SOURCE_ROOT "${CMAKE_SOURCE_DIR}")
  486. endif()
  487. set(top_src "${ExternalData_SOURCE_ROOT}")
  488. file(RELATIVE_PATH reldata "${top_src}" "${absdata}")
  489. if(IS_ABSOLUTE "${reldata}" OR "${reldata}" MATCHES "^\\.\\./")
  490. message(FATAL_ERROR "Data file referenced by argument\n"
  491. " ${arg}\n"
  492. "does not lie under the top-level source directory\n"
  493. " ${top_src}\n")
  494. endif()
  495. if(data_is_directory AND NOT IS_DIRECTORY "${top_src}/${reldata}")
  496. message(FATAL_ERROR "Data directory referenced by argument\n"
  497. " ${arg}\n"
  498. "corresponds to source tree path\n"
  499. " ${reldata}\n"
  500. "that does not exist as a directory!")
  501. endif()
  502. if(NOT ExternalData_BINARY_ROOT)
  503. set(ExternalData_BINARY_ROOT "${CMAKE_BINARY_DIR}")
  504. endif()
  505. set(top_bin "${ExternalData_BINARY_ROOT}")
  506. # Handle in-source builds gracefully.
  507. if("${top_src}" STREQUAL "${top_bin}")
  508. if(ExternalData_LINK_CONTENT)
  509. message(WARNING "ExternalData_LINK_CONTENT cannot be used in-source")
  510. set(ExternalData_LINK_CONTENT 0)
  511. endif()
  512. set(top_same 1)
  513. endif()
  514. set(external "") # Entries external to the source tree.
  515. set(internal "") # Entries internal to the source tree.
  516. set(have_original ${data_is_directory})
  517. set(have_original_as_dir 0)
  518. # Process options.
  519. set(series_option "")
  520. set(recurse_option "")
  521. set(associated_files "")
  522. set(associated_regex "")
  523. foreach(opt ${options})
  524. # Regular expression to match associated files.
  525. if("x${opt}" MATCHES "^xREGEX:([^:/]+)$")
  526. list(APPEND associated_regex "${CMAKE_MATCH_1}")
  527. elseif(opt STREQUAL ":")
  528. # Activate series matching.
  529. set(series_option "${opt}")
  530. elseif(opt STREQUAL "RECURSE:")
  531. # Activate recursive matching in directories.
  532. set(recurse_option "${opt}")
  533. elseif("x${opt}" MATCHES "^[^][:/*?]+$")
  534. # Specific associated file.
  535. list(APPEND associated_files "${opt}")
  536. else()
  537. message(FATAL_ERROR "Unknown option \"${opt}\" in argument\n"
  538. " ${arg}\n")
  539. endif()
  540. endforeach()
  541. if(series_option)
  542. if(data_is_directory)
  543. message(FATAL_ERROR "Series option \"${series_option}\" not allowed with directories.")
  544. endif()
  545. if(associated_files OR associated_regex)
  546. message(FATAL_ERROR "Series option \"${series_option}\" not allowed with associated files.")
  547. endif()
  548. if(recurse_option)
  549. message(FATAL_ERROR "Recurse option \"${recurse_option}\" allowed only with directories.")
  550. endif()
  551. # Load a whole file series.
  552. _ExternalData_arg_series()
  553. elseif(data_is_directory)
  554. if(associated_files OR associated_regex)
  555. # Load listed/matching associated files in the directory.
  556. _ExternalData_arg_associated()
  557. else()
  558. message(FATAL_ERROR "Data directory referenced by argument\n"
  559. " ${arg}\n"
  560. "must list associated files.")
  561. endif()
  562. else()
  563. if(recurse_option)
  564. message(FATAL_ERROR "Recurse option \"${recurse_option}\" allowed only with directories.")
  565. endif()
  566. # Load the named data file.
  567. _ExternalData_arg_single()
  568. if(associated_files OR associated_regex)
  569. # Load listed/matching associated files.
  570. _ExternalData_arg_associated()
  571. endif()
  572. endif()
  573. if(NOT have_original)
  574. if(have_original_as_dir)
  575. set(msg_kind FATAL_ERROR)
  576. set(msg "that is directory instead of a file!")
  577. else()
  578. set(msg_kind AUTHOR_WARNING)
  579. set(msg "that does not exist as a file (with or without an extension)!")
  580. endif()
  581. message(${msg_kind} "Data file referenced by argument\n"
  582. " ${arg}\n"
  583. "corresponds to source tree path\n"
  584. " ${reldata}\n"
  585. "${msg}")
  586. endif()
  587. if(external)
  588. # Make the series available in the build tree.
  589. set_property(GLOBAL APPEND PROPERTY
  590. _ExternalData_${target}_FETCH "${external}")
  591. set_property(GLOBAL APPEND PROPERTY
  592. _ExternalData_${target}_LOCAL "${internal}")
  593. set("${var_file}" "${top_bin}/${reldata}" PARENT_SCOPE)
  594. else()
  595. # The whole series is in the source tree.
  596. set("${var_file}" "${top_src}/${reldata}" PARENT_SCOPE)
  597. endif()
  598. endfunction()
  599. macro(_ExternalData_arg_associated)
  600. # Associated files lie in the same directory.
  601. if(data_is_directory)
  602. set(reldir "${reldata}")
  603. else()
  604. get_filename_component(reldir "${reldata}" PATH)
  605. endif()
  606. if(reldir)
  607. string(APPEND reldir "/")
  608. endif()
  609. _ExternalData_exact_regex(reldir_regex "${reldir}")
  610. if(recurse_option)
  611. set(glob GLOB_RECURSE)
  612. string(APPEND reldir_regex "(.+/)?")
  613. else()
  614. set(glob GLOB)
  615. endif()
  616. # Find files named explicitly.
  617. foreach(file ${associated_files})
  618. _ExternalData_exact_regex(file_regex "${file}")
  619. _ExternalData_arg_find_files(${glob} "${reldir}${file}"
  620. "${reldir_regex}${file_regex}")
  621. endforeach()
  622. # Find files matching the given regular expressions.
  623. set(all "")
  624. set(sep "")
  625. foreach(regex ${associated_regex})
  626. string(APPEND all "${sep}${reldir_regex}${regex}")
  627. set(sep "|")
  628. endforeach()
  629. _ExternalData_arg_find_files(${glob} "${reldir}" "${all}")
  630. endmacro()
  631. macro(_ExternalData_arg_single)
  632. # Match only the named data by itself.
  633. _ExternalData_exact_regex(data_regex "${reldata}")
  634. _ExternalData_arg_find_files(GLOB "${reldata}" "${data_regex}")
  635. endmacro()
  636. macro(_ExternalData_arg_series)
  637. # Configure series parsing and matching.
  638. set(series_parse_prefix "")
  639. set(series_parse_number "\\1")
  640. set(series_parse_suffix "\\2")
  641. if(ExternalData_SERIES_PARSE)
  642. if(ExternalData_SERIES_PARSE_NUMBER AND ExternalData_SERIES_PARSE_SUFFIX)
  643. if(ExternalData_SERIES_PARSE_PREFIX)
  644. set(series_parse_prefix "\\${ExternalData_SERIES_PARSE_PREFIX}")
  645. endif()
  646. set(series_parse_number "\\${ExternalData_SERIES_PARSE_NUMBER}")
  647. set(series_parse_suffix "\\${ExternalData_SERIES_PARSE_SUFFIX}")
  648. elseif(NOT "x${ExternalData_SERIES_PARSE}" MATCHES "^x\\([^()]*\\)\\([^()]*\\)\\$$")
  649. message(FATAL_ERROR
  650. "ExternalData_SERIES_PARSE is set to\n"
  651. " ${ExternalData_SERIES_PARSE}\n"
  652. "which is not of the form\n"
  653. " (<number>)(<suffix>)$\n"
  654. "Fix the regular expression or set variables\n"
  655. " ExternalData_SERIES_PARSE_PREFIX = <prefix> regex group number, if any\n"
  656. " ExternalData_SERIES_PARSE_NUMBER = <number> regex group number\n"
  657. " ExternalData_SERIES_PARSE_SUFFIX = <suffix> regex group number\n"
  658. )
  659. endif()
  660. set(series_parse "${ExternalData_SERIES_PARSE}")
  661. else()
  662. set(series_parse "([0-9]*)(\\.[^./]*)$")
  663. endif()
  664. if(ExternalData_SERIES_MATCH)
  665. set(series_match "${ExternalData_SERIES_MATCH}")
  666. else()
  667. set(series_match "[_.-]?[0-9]*")
  668. endif()
  669. # Parse the base, number, and extension components of the series.
  670. string(REGEX REPLACE "${series_parse}" "${series_parse_prefix};${series_parse_number};${series_parse_suffix}" tuple "${reldata}")
  671. list(LENGTH tuple len)
  672. if(NOT "${len}" EQUAL 3)
  673. message(FATAL_ERROR "Data file referenced by argument\n"
  674. " ${arg}\n"
  675. "corresponds to path\n"
  676. " ${reldata}\n"
  677. "that does not match regular expression\n"
  678. " ${series_parse}")
  679. endif()
  680. list(GET tuple 0 relbase)
  681. list(GET tuple 2 ext)
  682. # Glob files that might match the series.
  683. # Then match base, number, and extension.
  684. _ExternalData_exact_regex(series_base "${relbase}")
  685. _ExternalData_exact_regex(series_ext "${ext}")
  686. _ExternalData_arg_find_files(GLOB "${relbase}*${ext}"
  687. "${series_base}${series_match}${series_ext}")
  688. endmacro()
  689. function(_ExternalData_arg_find_files glob pattern regex)
  690. cmake_policy(PUSH)
  691. cmake_policy(SET CMP0009 NEW)
  692. file(${glob} globbed RELATIVE "${top_src}" "${top_src}/${pattern}*")
  693. cmake_policy(POP)
  694. set(externals_count -1)
  695. foreach(entry IN LISTS globbed)
  696. if("x${entry}" MATCHES "^x(.*)(\\.(${_ExternalData_REGEX_EXT}))$")
  697. set(relname "${CMAKE_MATCH_1}")
  698. set(alg "${CMAKE_MATCH_2}")
  699. else()
  700. set(relname "${entry}")
  701. set(alg "")
  702. endif()
  703. if("x${relname}" MATCHES "^x${regex}$" # matches
  704. AND NOT "x${relname}" MATCHES "(^x|/)\\.ExternalData_" # not staged obj
  705. )
  706. if(IS_DIRECTORY "${top_src}/${entry}")
  707. if("${relname}" STREQUAL "${reldata}")
  708. set(have_original_as_dir 1)
  709. endif()
  710. else()
  711. set(name "${top_src}/${relname}")
  712. set(file "${top_bin}/${relname}")
  713. if(alg)
  714. if(NOT "${external_${externals_count}_file_name}" STREQUAL "${file}|${name}")
  715. math(EXPR externals_count "${externals_count} + 1")
  716. set(external_${externals_count}_file_name "${file}|${name}")
  717. endif()
  718. list(APPEND external_${externals_count}_algs "${alg}")
  719. elseif(ExternalData_LINK_CONTENT)
  720. _ExternalData_link_content("${name}" alg)
  721. list(APPEND external "${file}|${name}|${alg}")
  722. elseif(NOT top_same)
  723. list(APPEND internal "${file}|${name}")
  724. endif()
  725. if("${relname}" STREQUAL "${reldata}")
  726. set(have_original 1)
  727. endif()
  728. endif()
  729. endif()
  730. endforeach()
  731. if(${externals_count} GREATER -1)
  732. foreach(ii RANGE ${externals_count})
  733. string(REPLACE ";" "+" algs_delim "${external_${ii}_algs}")
  734. list(APPEND external "${external_${ii}_file_name}|${algs_delim}")
  735. unset(external_${ii}_algs)
  736. unset(external_${ii}_file_name)
  737. endforeach()
  738. endif()
  739. set(external "${external}" PARENT_SCOPE)
  740. set(internal "${internal}" PARENT_SCOPE)
  741. set(have_original "${have_original}" PARENT_SCOPE)
  742. set(have_original_as_dir "${have_original_as_dir}" PARENT_SCOPE)
  743. endfunction()
  744. #-----------------------------------------------------------------------------
  745. # Private script mode interface
  746. if(CMAKE_GENERATOR OR NOT ExternalData_ACTION)
  747. return()
  748. endif()
  749. if(ExternalData_CONFIG)
  750. include(${ExternalData_CONFIG})
  751. endif()
  752. if(NOT ExternalData_URL_TEMPLATES AND NOT ExternalData_OBJECT_STORES)
  753. message(FATAL_ERROR
  754. "Neither ExternalData_URL_TEMPLATES nor ExternalData_OBJECT_STORES is set!")
  755. endif()
  756. function(_ExternalData_link_or_copy src dst)
  757. # Create a temporary file first.
  758. get_filename_component(dst_dir "${dst}" PATH)
  759. file(MAKE_DIRECTORY "${dst_dir}")
  760. _ExternalData_random(random)
  761. set(tmp "${dst}.tmp${random}")
  762. if(UNIX AND NOT ExternalData_NO_SYMLINKS)
  763. # Create a symbolic link.
  764. set(tgt "${src}")
  765. if(relative_top)
  766. # Use relative path if files are close enough.
  767. file(RELATIVE_PATH relsrc "${relative_top}" "${src}")
  768. file(RELATIVE_PATH relfile "${relative_top}" "${dst}")
  769. if(NOT IS_ABSOLUTE "${relsrc}" AND NOT "${relsrc}" MATCHES "^\\.\\./" AND
  770. NOT IS_ABSOLUTE "${reldst}" AND NOT "${reldst}" MATCHES "^\\.\\./")
  771. file(RELATIVE_PATH tgt "${dst_dir}" "${src}")
  772. endif()
  773. endif()
  774. execute_process(COMMAND "${CMAKE_COMMAND}" -E create_symlink "${tgt}" "${tmp}" RESULT_VARIABLE result)
  775. else()
  776. # Create a copy.
  777. execute_process(COMMAND "${CMAKE_COMMAND}" -E copy "${src}" "${tmp}" RESULT_VARIABLE result)
  778. endif()
  779. if(result)
  780. file(REMOVE "${tmp}")
  781. message(FATAL_ERROR "Failed to create\n ${tmp}\nfrom\n ${obj}")
  782. endif()
  783. # Atomically create/replace the real destination.
  784. file(RENAME "${tmp}" "${dst}")
  785. endfunction()
  786. function(_ExternalData_download_file url file err_var msg_var)
  787. set(retry 3)
  788. while(retry)
  789. math(EXPR retry "${retry} - 1")
  790. if(ExternalData_TIMEOUT_INACTIVITY)
  791. set(inactivity_timeout INACTIVITY_TIMEOUT ${ExternalData_TIMEOUT_INACTIVITY})
  792. elseif(NOT "${ExternalData_TIMEOUT_INACTIVITY}" EQUAL 0)
  793. set(inactivity_timeout INACTIVITY_TIMEOUT 60)
  794. else()
  795. set(inactivity_timeout "")
  796. endif()
  797. if(ExternalData_TIMEOUT_ABSOLUTE)
  798. set(absolute_timeout TIMEOUT ${ExternalData_TIMEOUT_ABSOLUTE})
  799. elseif(NOT "${ExternalData_TIMEOUT_ABSOLUTE}" EQUAL 0)
  800. set(absolute_timeout TIMEOUT 300)
  801. else()
  802. set(absolute_timeout "")
  803. endif()
  804. file(DOWNLOAD "${url}" "${file}" STATUS status LOG log ${inactivity_timeout} ${absolute_timeout} SHOW_PROGRESS)
  805. list(GET status 0 err)
  806. list(GET status 1 msg)
  807. if(err)
  808. if("${msg}" MATCHES "HTTP response code said error" AND
  809. "${log}" MATCHES "error: 503")
  810. set(msg "temporarily unavailable")
  811. endif()
  812. elseif("${log}" MATCHES "\nHTTP[^\n]* 503")
  813. set(err TRUE)
  814. set(msg "temporarily unavailable")
  815. endif()
  816. if(NOT err OR NOT "${msg}" MATCHES "partial|timeout|temporarily")
  817. break()
  818. elseif(retry)
  819. message(STATUS "[download terminated: ${msg}, retries left: ${retry}]")
  820. endif()
  821. endwhile()
  822. set("${err_var}" "${err}" PARENT_SCOPE)
  823. set("${msg_var}" "${msg}" PARENT_SCOPE)
  824. endfunction()
  825. function(_ExternalData_custom_fetch key loc file err_var msg_var)
  826. if(NOT ExternalData_CUSTOM_SCRIPT_${key})
  827. set(err 1)
  828. set(msg "No ExternalData_CUSTOM_SCRIPT_${key} set!")
  829. elseif(NOT EXISTS "${ExternalData_CUSTOM_SCRIPT_${key}}")
  830. set(err 1)
  831. set(msg "No '${ExternalData_CUSTOM_SCRIPT_${key}}' exists!")
  832. else()
  833. set(ExternalData_CUSTOM_LOCATION "${loc}")
  834. set(ExternalData_CUSTOM_FILE "${file}")
  835. unset(ExternalData_CUSTOM_ERROR)
  836. include("${ExternalData_CUSTOM_SCRIPT_${key}}")
  837. if(DEFINED ExternalData_CUSTOM_ERROR)
  838. set(err 1)
  839. set(msg "${ExternalData_CUSTOM_ERROR}")
  840. else()
  841. set(err 0)
  842. set(msg "no error")
  843. endif()
  844. endif()
  845. set("${err_var}" "${err}" PARENT_SCOPE)
  846. set("${msg_var}" "${msg}" PARENT_SCOPE)
  847. endfunction()
  848. function(_ExternalData_get_from_object_store hash algo var_obj var_success)
  849. # Search all object stores for an existing object.
  850. foreach(dir ${ExternalData_OBJECT_STORES})
  851. set(obj "${dir}/${algo}/${hash}")
  852. if(EXISTS "${obj}")
  853. message(STATUS "Found object: \"${obj}\"")
  854. set("${var_obj}" "${obj}" PARENT_SCOPE)
  855. set("${var_success}" 1 PARENT_SCOPE)
  856. return()
  857. endif()
  858. endforeach()
  859. endfunction()
  860. function(_ExternalData_download_object name hash algo var_obj var_success var_errorMsg)
  861. # Search all object stores for an existing object.
  862. set(success 1)
  863. foreach(dir ${ExternalData_OBJECT_STORES})
  864. set(obj "${dir}/${algo}/${hash}")
  865. if(EXISTS "${obj}")
  866. message(STATUS "Found object: \"${obj}\"")
  867. set("${var_obj}" "${obj}" PARENT_SCOPE)
  868. set("${var_success}" "${success}" PARENT_SCOPE)
  869. return()
  870. endif()
  871. endforeach()
  872. # Download object to the first store.
  873. list(GET ExternalData_OBJECT_STORES 0 store)
  874. set(obj "${store}/${algo}/${hash}")
  875. _ExternalData_random(random)
  876. set(tmp "${obj}.tmp${random}")
  877. set(found 0)
  878. set(tried "")
  879. foreach(url_template IN LISTS ExternalData_URL_TEMPLATES)
  880. string(REPLACE "%(hash)" "${hash}" url_tmp "${url_template}")
  881. string(REPLACE "%(algo)" "${algo}" url "${url_tmp}")
  882. if(url MATCHES "^(.*)%\\(algo:([A-Za-z_][A-Za-z0-9_]*)\\)(.*)$")
  883. set(lhs "${CMAKE_MATCH_1}")
  884. set(key "${CMAKE_MATCH_2}")
  885. set(rhs "${CMAKE_MATCH_3}")
  886. if(DEFINED ExternalData_URL_ALGO_${algo}_${key})
  887. set(url "${lhs}${ExternalData_URL_ALGO_${algo}_${key}}${rhs}")
  888. else()
  889. set(url "${lhs}${algo}${rhs}")
  890. endif()
  891. endif()
  892. string(REGEX REPLACE "((https?|ftp)://)([^@]+@)?(.*)" "\\1\\4" secured_url "${url}")
  893. message(STATUS "Fetching \"${secured_url}\"")
  894. if(url MATCHES "^ExternalDataCustomScript://([A-Za-z_][A-Za-z0-9_]*)/(.*)$")
  895. _ExternalData_custom_fetch("${CMAKE_MATCH_1}" "${CMAKE_MATCH_2}" "${tmp}" err errMsg)
  896. else()
  897. _ExternalData_download_file("${url}" "${tmp}" err errMsg)
  898. endif()
  899. string(APPEND tried "\n ${url}")
  900. if(err)
  901. string(APPEND tried " (${errMsg})")
  902. else()
  903. # Verify downloaded object.
  904. _ExternalData_compute_hash(dl_hash "${algo}" "${tmp}")
  905. if("${dl_hash}" STREQUAL "${hash}")
  906. set(found 1)
  907. break()
  908. else()
  909. string(APPEND tried " (wrong hash ${algo}=${dl_hash})")
  910. if("$ENV{ExternalData_DEBUG_DOWNLOAD}" MATCHES ".")
  911. file(RENAME "${tmp}" "${store}/${algo}/${dl_hash}")
  912. endif()
  913. endif()
  914. endif()
  915. file(REMOVE "${tmp}")
  916. endforeach()
  917. get_filename_component(dir "${name}" PATH)
  918. set(staged "${dir}/.ExternalData_${algo}_${hash}")
  919. set(success 1)
  920. if(found)
  921. file(RENAME "${tmp}" "${obj}")
  922. message(STATUS "Downloaded object: \"${obj}\"")
  923. elseif(EXISTS "${staged}")
  924. set(obj "${staged}")
  925. message(STATUS "Staged object: \"${obj}\"")
  926. else()
  927. if(NOT tried)
  928. set(tried "\n (No ExternalData_URL_TEMPLATES given)")
  929. endif()
  930. set(success 0)
  931. set("${var_errorMsg}" "Object ${algo}=${hash} not found at:${tried}" PARENT_SCOPE)
  932. endif()
  933. set("${var_obj}" "${obj}" PARENT_SCOPE)
  934. set("${var_success}" "${success}" PARENT_SCOPE)
  935. endfunction()
  936. if("${ExternalData_ACTION}" STREQUAL "fetch")
  937. foreach(v ExternalData_OBJECT_STORES file name exts)
  938. if(NOT DEFINED "${v}")
  939. message(FATAL_ERROR "No \"-D${v}=\" value provided!")
  940. endif()
  941. endforeach()
  942. string(REPLACE "+" ";" exts_list "${exts}")
  943. set(succeeded 0)
  944. set(errorMsg "")
  945. set(hash_list )
  946. set(algo_list )
  947. set(hash )
  948. set(algo )
  949. foreach(ext ${exts_list})
  950. file(READ "${name}${ext}" hash)
  951. string(STRIP "${hash}" hash)
  952. if("${ext}" MATCHES "^\\.(${_ExternalData_REGEX_EXT})$")
  953. string(TOUPPER "${CMAKE_MATCH_1}" algo)
  954. string(REPLACE "-" "_" algo "${algo}")
  955. else()
  956. message(FATAL_ERROR "Unknown hash algorithm extension \"${ext}\"")
  957. endif()
  958. list(APPEND hash_list ${hash})
  959. list(APPEND algo_list ${algo})
  960. endforeach()
  961. list(LENGTH exts_list num_extensions)
  962. math(EXPR exts_range "${num_extensions} - 1")
  963. foreach(ii RANGE 0 ${exts_range})
  964. list(GET hash_list ${ii} hash)
  965. list(GET algo_list ${ii} algo)
  966. _ExternalData_get_from_object_store("${hash}" "${algo}" obj succeeded)
  967. if(succeeded)
  968. break()
  969. endif()
  970. endforeach()
  971. if(NOT succeeded)
  972. foreach(ii RANGE 0 ${exts_range})
  973. list(GET hash_list ${ii} hash)
  974. list(GET algo_list ${ii} algo)
  975. _ExternalData_download_object("${name}" "${hash}" "${algo}"
  976. obj succeeded algoErrorMsg)
  977. string(APPEND errorMsg "\n${algoErrorMsg}")
  978. if(succeeded)
  979. break()
  980. endif()
  981. endforeach()
  982. endif()
  983. if(NOT succeeded)
  984. message(FATAL_ERROR "${errorMsg}")
  985. endif()
  986. # Check if file already corresponds to the object.
  987. set(stamp "-hash-stamp")
  988. set(file_up_to_date 0)
  989. if(EXISTS "${file}" AND EXISTS "${file}${stamp}")
  990. file(READ "${file}${stamp}" f_hash)
  991. string(STRIP "${f_hash}" f_hash)
  992. if("${f_hash}" STREQUAL "${hash}")
  993. set(file_up_to_date 1)
  994. endif()
  995. endif()
  996. if(file_up_to_date)
  997. # Touch the file to convince the build system it is up to date.
  998. file(TOUCH "${file}")
  999. else()
  1000. _ExternalData_link_or_copy("${obj}" "${file}")
  1001. endif()
  1002. # Atomically update the hash/timestamp file to record the object referenced.
  1003. _ExternalData_atomic_write("${file}${stamp}" "${hash}\n")
  1004. elseif("${ExternalData_ACTION}" STREQUAL "local")
  1005. foreach(v file name)
  1006. if(NOT DEFINED "${v}")
  1007. message(FATAL_ERROR "No \"-D${v}=\" value provided!")
  1008. endif()
  1009. endforeach()
  1010. _ExternalData_link_or_copy("${name}" "${file}")
  1011. else()
  1012. message(FATAL_ERROR "Unknown ExternalData_ACTION=[${ExternalData_ACTION}]")
  1013. endif()