ExternalData.cmake 45 KB

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