FetchContent.cmake 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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. FetchContent
  5. ------------------
  6. .. versionadded:: 3.11
  7. .. only:: html
  8. .. contents::
  9. Overview
  10. ^^^^^^^^
  11. This module enables populating content at configure time via any method
  12. supported by the :module:`ExternalProject` module. Whereas
  13. :command:`ExternalProject_Add` downloads at build time, the
  14. ``FetchContent`` module makes content available immediately, allowing the
  15. configure step to use the content in commands like :command:`add_subdirectory`,
  16. :command:`include` or :command:`file` operations.
  17. Content population details should be defined separately from the command that
  18. performs the actual population. This separation ensures that all the
  19. dependency details are defined before anything might try to use them to
  20. populate content. This is particularly important in more complex project
  21. hierarchies where dependencies may be shared between multiple projects.
  22. The following shows a typical example of declaring content details for some
  23. dependencies and then ensuring they are populated with a separate call:
  24. .. code-block:: cmake
  25. FetchContent_Declare(
  26. googletest
  27. GIT_REPOSITORY https://github.com/google/googletest.git
  28. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  29. )
  30. FetchContent_Declare(
  31. myCompanyIcons
  32. URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  33. URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
  34. )
  35. FetchContent_MakeAvailable(googletest secret_sauce)
  36. The :command:`FetchContent_MakeAvailable` command ensures the named
  37. dependencies have been populated, either by an earlier call or by populating
  38. them itself. When performing the population, it will also add them to the
  39. main build, if possible, so that the main build can use the populated
  40. projects' targets, etc. See the command's documentation for how these steps
  41. are performed.
  42. When using a hierarchical project arrangement, projects at higher levels in
  43. the hierarchy are able to override the declared details of content specified
  44. anywhere lower in the project hierarchy. The first details to be declared
  45. for a given dependency take precedence, regardless of where in the project
  46. hierarchy that occurs. Similarly, the first call that tries to populate a
  47. dependency "wins", with subsequent populations reusing the result of the
  48. first instead of repeating the population again.
  49. See the :ref:`Examples <fetch-content-examples>` which demonstrate
  50. this scenario.
  51. In some cases, the main project may need to have more precise control over
  52. the population, or it may be required to explicitly define the population
  53. steps in a way that cannot be captured by the declared details alone.
  54. For such situations, the lower level :command:`FetchContent_GetProperties` and
  55. :command:`FetchContent_Populate` commands can be used. These lack the richer
  56. features provided by :command:`FetchContent_MakeAvailable` though, so their
  57. direct use should be considered a last resort. The typical pattern of such
  58. custom steps looks like this:
  59. .. code-block:: cmake
  60. # NOTE: Where possible, prefer to use FetchContent_MakeAvailable()
  61. # instead of custom logic like this
  62. # Check if population has already been performed
  63. FetchContent_GetProperties(depname)
  64. if(NOT depname_POPULATED)
  65. # Fetch the content using previously declared details
  66. FetchContent_Populate(depname)
  67. # Set custom variables, policies, etc.
  68. # ...
  69. # Bring the populated content into the build
  70. add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
  71. endif()
  72. The ``FetchContent`` module also supports defining and populating
  73. content in a single call, with no check for whether the content has been
  74. populated elsewhere already. This should not be done in projects, but may
  75. be appropriate for populating content in CMake's script mode.
  76. See :command:`FetchContent_Populate` for details.
  77. Commands
  78. ^^^^^^^^
  79. .. command:: FetchContent_Declare
  80. .. code-block:: cmake
  81. FetchContent_Declare(<name> <contentOptions>...)
  82. The ``FetchContent_Declare()`` function records the options that describe
  83. how to populate the specified content. If such details have already
  84. been recorded earlier in this project (regardless of where in the project
  85. hierarchy), this and all later calls for the same content ``<name>`` are
  86. ignored. This "first to record, wins" approach is what allows hierarchical
  87. projects to have parent projects override content details of child projects.
  88. The content ``<name>`` can be any string without spaces, but good practice
  89. would be to use only letters, numbers and underscores. The name will be
  90. treated case-insensitively and it should be obvious for the content it
  91. represents, often being the name of the child project or the value given
  92. to its top level :command:`project` command (if it is a CMake project).
  93. For well-known public projects, the name should generally be the official
  94. name of the project. Choosing an unusual name makes it unlikely that other
  95. projects needing that same content will use the same name, leading to
  96. the content being populated multiple times.
  97. The ``<contentOptions>`` can be any of the download, update or patch options
  98. that the :command:`ExternalProject_Add` command understands. The configure,
  99. build, install and test steps are explicitly disabled and therefore options
  100. related to them will be ignored. The ``SOURCE_SUBDIR`` option is an
  101. exception, see :command:`FetchContent_MakeAvailable` for details on how that
  102. affects behavior.
  103. In most cases, ``<contentOptions>`` will just be a couple of options defining
  104. the download method and method-specific details like a commit tag or archive
  105. hash. For example:
  106. .. code-block:: cmake
  107. FetchContent_Declare(
  108. googletest
  109. GIT_REPOSITORY https://github.com/google/googletest.git
  110. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  111. )
  112. FetchContent_Declare(
  113. myCompanyIcons
  114. URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  115. URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
  116. )
  117. FetchContent_Declare(
  118. myCompanyCertificates
  119. SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs
  120. SVN_REVISION -r12345
  121. )
  122. Where contents are being fetched from a remote location and you do not
  123. control that server, it is advisable to use a hash for ``GIT_TAG`` rather
  124. than a branch or tag name. A commit hash is more secure and helps to
  125. confirm that the downloaded contents are what you expected.
  126. .. versionchanged:: 3.14
  127. Commands for the download, update or patch steps can access the terminal.
  128. This may be needed for things like password prompts or real-time display
  129. of command progress.
  130. .. versionadded:: 3.22
  131. The :variable:`CMAKE_TLS_VERIFY`, :variable:`CMAKE_TLS_CAINFO`,
  132. :variable:`CMAKE_NETRC` and :variable:`CMAKE_NETRC_FILE` variables now
  133. provide the defaults for their corresponding content options, just like
  134. they do for :command:`ExternalProject_Add`. Previously, these variables
  135. were ignored by the ``FetchContent`` module.
  136. .. command:: FetchContent_MakeAvailable
  137. .. versionadded:: 3.14
  138. .. code-block:: cmake
  139. FetchContent_MakeAvailable(<name1> [<name2>...])
  140. This command ensures that each of the named dependencies are populated and
  141. potentially added to the build by the time it returns. It iterates over
  142. the list, and for each dependency, the following logic is applied:
  143. * If the dependency has already been populated earlier in this run, set
  144. the ``<lowercaseName>_POPULATED``, ``<lowercaseName>_SOURCE_DIR`` and
  145. ``<lowercaseName>_BINARY_DIR`` variables in the same way as a call to
  146. :command:`FetchContent_GetProperties`, then skip the remaining steps
  147. below and move on to the next dependency in the list.
  148. * Call :command:`FetchContent_Populate` to populate the dependency using
  149. the details recorded by an earlier call to :command:`FetchContent_Declare`.
  150. Halt with a fatal error if no such details have been recorded.
  151. :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>` can be used to override
  152. the declared details and use content provided at the specified location
  153. instead.
  154. * If the top directory of the populated content contains a ``CMakeLists.txt``
  155. file, call :command:`add_subdirectory` to add it to the main build.
  156. It is not an error for there to be no ``CMakeLists.txt`` file, which
  157. allows the command to be used for dependencies that make downloaded
  158. content available at a known location, but which do not need or support
  159. being added directly to the build.
  160. .. versionadded:: 3.18
  161. The ``SOURCE_SUBDIR`` option can be given in the declared details to
  162. look somewhere below the top directory instead (i.e. the same way that
  163. ``SOURCE_SUBDIR`` is used by the :command:`ExternalProject_Add`
  164. command). The path provided with ``SOURCE_SUBDIR`` must be relative
  165. and will be treated as relative to the top directory. It can also
  166. point to a directory that does not contain a ``CMakeLists.txt`` file
  167. or even to a directory that doesn't exist. This can be used to avoid
  168. adding a project that contains a ``CMakeLists.txt`` file in its top
  169. directory.
  170. Projects should aim to declare the details of all dependencies they might
  171. use before they call ``FetchContent_MakeAvailable()`` for any of them.
  172. This ensures that if any of the dependencies are also sub-dependencies of
  173. one or more of the others, the main project still controls the details
  174. that will be used (because it will declare them first before the
  175. dependencies get a chance to). In the following code samples, assume that
  176. the ``uses_other`` dependency also uses ``FetchContent`` to add the ``other``
  177. dependency internally:
  178. .. code-block:: cmake
  179. # WRONG: Should declare all details first
  180. FetchContent_Declare(uses_other ...)
  181. FetchContent_MakeAvailable(uses_other)
  182. FetchContent_Declare(other ...) # Will be ignored, uses_other beat us to it
  183. FetchContent_MakeAvailable(other) # Would use details declared by uses_other
  184. .. code-block:: cmake
  185. # CORRECT: All details declared first, so they will take priority
  186. FetchContent_Declare(uses_other ...)
  187. FetchContent_Declare(other ...)
  188. FetchContent_MakeAvailable(uses_other other)
  189. .. command:: FetchContent_Populate
  190. .. note::
  191. Where possible, prefer to use :command:`FetchContent_MakeAvailable`
  192. instead of implementing population manually with this command.
  193. .. code-block:: cmake
  194. FetchContent_Populate(<name>)
  195. In most cases, the only argument given to ``FetchContent_Populate()`` is the
  196. ``<name>``. When used this way, the command assumes the content details have
  197. been recorded by an earlier call to :command:`FetchContent_Declare`. The
  198. details are stored in a global property, so they are unaffected by things
  199. like variable or directory scope. Therefore, it doesn't matter where in the
  200. project the details were previously declared, as long as they have been
  201. declared before the call to ``FetchContent_Populate()``. Those saved details
  202. are then used to construct a call to :command:`ExternalProject_Add` in a
  203. private sub-build to perform the content population immediately. The
  204. implementation of ``ExternalProject_Add()`` ensures that if the content has
  205. already been populated in a previous CMake run, that content will be reused
  206. rather than repopulating them again. For the common case where population
  207. involves downloading content, the cost of the download is only paid once.
  208. An internal global property records when a particular content population
  209. request has been processed. If ``FetchContent_Populate()`` is called more
  210. than once for the same content name within a configure run, the second call
  211. will halt with an error. Projects can and should check whether content
  212. population has already been processed with the
  213. :command:`FetchContent_GetProperties` command before calling
  214. ``FetchContent_Populate()``.
  215. ``FetchContent_Populate()`` will set three variables in the scope of the
  216. caller:
  217. ``<lowercaseName>_POPULATED``
  218. This will always be set to ``TRUE`` by the call.
  219. ``<lowercaseName>_SOURCE_DIR``
  220. The location where the populated content can be found upon return.
  221. ``<lowercaseName>_BINARY_DIR``
  222. A directory intended for use as a corresponding build directory.
  223. The main use case for the ``<lowercaseName>_SOURCE_DIR`` and
  224. ``<lowercaseName>_BINARY_DIR`` variables is to call
  225. :command:`add_subdirectory` immediately after population:
  226. .. code-block:: cmake
  227. FetchContent_Populate(FooBar)
  228. add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
  229. The values of the three variables can also be retrieved from anywhere in the
  230. project hierarchy using the :command:`FetchContent_GetProperties` command.
  231. The ``FetchContent_Populate()`` command also supports a syntax allowing the
  232. content details to be specified directly rather than using any saved
  233. details. This is more low-level and use of this form is generally to be
  234. avoided in favor of using saved content details as outlined above.
  235. Nevertheless, in certain situations it can be useful to invoke the content
  236. population as an isolated operation (typically as part of implementing some
  237. other higher level feature or when using CMake in script mode):
  238. .. code-block:: cmake
  239. FetchContent_Populate(
  240. <name>
  241. [QUIET]
  242. [SUBBUILD_DIR <subBuildDir>]
  243. [SOURCE_DIR <srcDir>]
  244. [BINARY_DIR <binDir>]
  245. ...
  246. )
  247. This form has a number of key differences to that where only ``<name>`` is
  248. provided:
  249. - All required population details are assumed to have been provided directly
  250. in the call to ``FetchContent_Populate()``. Any saved details for
  251. ``<name>`` are ignored.
  252. - No check is made for whether content for ``<name>`` has already been
  253. populated.
  254. - No global property is set to record that the population has occurred.
  255. - No global properties record the source or binary directories used for the
  256. populated content.
  257. - The ``FETCHCONTENT_FULLY_DISCONNECTED`` and
  258. ``FETCHCONTENT_UPDATES_DISCONNECTED`` cache variables are ignored.
  259. The ``<lowercaseName>_SOURCE_DIR`` and ``<lowercaseName>_BINARY_DIR``
  260. variables are still returned to the caller, but since these locations are
  261. not stored as global properties when this form is used, they are only
  262. available to the calling scope and below rather than the entire project
  263. hierarchy. No ``<lowercaseName>_POPULATED`` variable is set in the caller's
  264. scope with this form.
  265. The supported options for ``FetchContent_Populate()`` are the same as those
  266. for :command:`FetchContent_Declare()`. Those few options shown just
  267. above are either specific to ``FetchContent_Populate()`` or their behavior is
  268. slightly modified from how :command:`ExternalProject_Add` treats them:
  269. ``QUIET``
  270. The ``QUIET`` option can be given to hide the output associated with
  271. populating the specified content. If the population fails, the output will
  272. be shown regardless of whether this option was given or not so that the
  273. cause of the failure can be diagnosed. The global ``FETCHCONTENT_QUIET``
  274. cache variable has no effect on ``FetchContent_Populate()`` calls where the
  275. content details are provided directly.
  276. ``SUBBUILD_DIR``
  277. The ``SUBBUILD_DIR`` argument can be provided to change the location of the
  278. sub-build created to perform the population. The default value is
  279. ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild`` and it would be
  280. unusual to need to override this default. If a relative path is specified,
  281. it will be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
  282. This option should not be confused with the ``SOURCE_SUBDIR`` option which
  283. only affects the :command:`FetchContent_MakeAvailable` command.
  284. ``SOURCE_DIR``, ``BINARY_DIR``
  285. The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments are supported by
  286. :command:`ExternalProject_Add`, but different default values are used by
  287. ``FetchContent_Populate()``. ``SOURCE_DIR`` defaults to
  288. ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src`` and ``BINARY_DIR``
  289. defaults to ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build``.
  290. If a relative path is specified, it will be interpreted as relative to
  291. :variable:`CMAKE_CURRENT_BINARY_DIR`.
  292. In addition to the above explicit options, any other unrecognized options are
  293. passed through unmodified to :command:`ExternalProject_Add` to perform the
  294. download, patch and update steps. The following options are explicitly
  295. prohibited (they are disabled by the ``FetchContent_Populate()`` command):
  296. - ``CONFIGURE_COMMAND``
  297. - ``BUILD_COMMAND``
  298. - ``INSTALL_COMMAND``
  299. - ``TEST_COMMAND``
  300. If using ``FetchContent_Populate()`` within CMake's script mode, be aware
  301. that the implementation sets up a sub-build which therefore requires a CMake
  302. generator and build tool to be available. If these cannot be found by
  303. default, then the :variable:`CMAKE_GENERATOR` and/or
  304. :variable:`CMAKE_MAKE_PROGRAM` variables will need to be set appropriately
  305. on the command line invoking the script.
  306. .. versionadded:: 3.18
  307. Added support for the ``DOWNLOAD_NO_EXTRACT`` option.
  308. .. command:: FetchContent_GetProperties
  309. When using saved content details, a call to
  310. :command:`FetchContent_MakeAvailable` or :command:`FetchContent_Populate`
  311. records information in global properties which can be queried at any time.
  312. This information includes the source and binary directories associated with
  313. the content and also whether or not the content population has been processed
  314. during the current configure run.
  315. .. code-block:: cmake
  316. FetchContent_GetProperties(
  317. <name>
  318. [SOURCE_DIR <srcDirVar>]
  319. [BINARY_DIR <binDirVar>]
  320. [POPULATED <doneVar>]
  321. )
  322. The ``SOURCE_DIR``, ``BINARY_DIR`` and ``POPULATED`` options can be used to
  323. specify which properties should be retrieved. Each option accepts a value
  324. which is the name of the variable in which to store that property. Most of
  325. the time though, only ``<name>`` is given, in which case the call will then
  326. set the same variables as a call to
  327. :command:`FetchContent_MakeAvailable(name) <FetchContent_MakeAvailable>` or
  328. :command:`FetchContent_Populate(name) <FetchContent_Populate>`.
  329. This command is rarely needed when using
  330. :command:`FetchContent_MakeAvailable`. It is more commonly used as part of
  331. implementing the following pattern with :command:`FetchContent_Populate`,
  332. which ensures that the relevant variables will always be defined regardless
  333. of whether or not the population has been performed elsewhere in the project
  334. already:
  335. .. code-block:: cmake
  336. # Check if population has already been performed
  337. FetchContent_GetProperties(depname)
  338. if(NOT depname_POPULATED)
  339. # Fetch the content using previously declared details
  340. FetchContent_Populate(depname)
  341. # Set custom variables, policies, etc.
  342. # ...
  343. # Bring the populated content into the build
  344. add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
  345. endif()
  346. Variables
  347. ^^^^^^^^^
  348. A number of cache variables can influence the behavior where details from a
  349. :command:`FetchContent_Declare` call are used to populate content.
  350. The variables are all intended for the developer to customize behavior and
  351. should not normally be set by the project.
  352. .. variable:: FETCHCONTENT_BASE_DIR
  353. In most cases, the saved details do not specify any options relating to the
  354. directories to use for the internal sub-build, final source and build areas.
  355. It is generally best to leave these decisions up to the ``FetchContent``
  356. module to handle on the project's behalf. The ``FETCHCONTENT_BASE_DIR``
  357. cache variable controls the point under which all content population
  358. directories are collected, but in most cases, developers would not need to
  359. change this. The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
  360. developers change this value, they should aim to keep the path short and
  361. just below the top level of the build tree to avoid running into path
  362. length problems on Windows.
  363. .. variable:: FETCHCONTENT_QUIET
  364. The logging output during population can be quite verbose, making the
  365. configure stage quite noisy. This cache option (``ON`` by default) hides
  366. all population output unless an error is encountered. If experiencing
  367. problems with hung downloads, temporarily switching this option off may
  368. help diagnose which content population is causing the issue.
  369. .. variable:: FETCHCONTENT_FULLY_DISCONNECTED
  370. When this option is enabled, no attempt is made to download or update
  371. any content. It is assumed that all content has already been populated in
  372. a previous run or the source directories have been pointed at existing
  373. contents the developer has provided manually (using options described
  374. further below). When the developer knows that no changes have been made to
  375. any content details, turning this option ``ON`` can significantly speed up
  376. the configure stage. It is ``OFF`` by default.
  377. .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED
  378. This is a less severe download/update control compared to
  379. :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. Instead of bypassing all
  380. download and update logic, ``FETCHCONTENT_UPDATES_DISCONNECTED`` only
  381. disables the update stage. Therefore, if content has not been downloaded
  382. previously, it will still be downloaded when this option is enabled.
  383. This can speed up the configure stage, but not as much as
  384. :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. It is ``OFF`` by default.
  385. In addition to the above cache variables, the following cache variables are
  386. also defined for each content name:
  387. .. variable:: FETCHCONTENT_SOURCE_DIR_<uppercaseName>
  388. If this is set, no download or update steps are performed for the specified
  389. content and the ``<lowercaseName>_SOURCE_DIR`` variable returned to the
  390. caller is pointed at this location. This gives developers a way to have a
  391. separate checkout of the content that they can modify freely without
  392. interference from the build. The build simply uses that existing source,
  393. but it still defines ``<lowercaseName>_BINARY_DIR`` to point inside its own
  394. build area. Developers are strongly encouraged to use this mechanism rather
  395. than editing the sources populated in the default location, as changes to
  396. sources in the default location can be lost when content population details
  397. are changed by the project.
  398. .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED_<uppercaseName>
  399. This is the per-content equivalent of
  400. :variable:`FETCHCONTENT_UPDATES_DISCONNECTED`. If the global option or
  401. this option is ``ON``, then updates will be disabled for the named content.
  402. Disabling updates for individual content can be useful for content whose
  403. details rarely change, while still leaving other frequently changing content
  404. with updates enabled.
  405. .. _`fetch-content-examples`:
  406. Examples
  407. ^^^^^^^^
  408. This first fairly straightforward example ensures that some popular testing
  409. frameworks are available to the main build:
  410. .. code-block:: cmake
  411. include(FetchContent)
  412. FetchContent_Declare(
  413. googletest
  414. GIT_REPOSITORY https://github.com/google/googletest.git
  415. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  416. )
  417. FetchContent_Declare(
  418. Catch2
  419. GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  420. GIT_TAG de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
  421. )
  422. # After the following call, the CMake targets defined by googletest and
  423. # Catch2 will be available to the rest of the build
  424. FetchContent_MakeAvailable(googletest Catch2)
  425. If the sub-project's ``CMakeLists.txt`` file is not at the top level of its
  426. source tree, the ``SOURCE_SUBDIR`` option can be used to tell ``FetchContent``
  427. where to find it. The following example shows how to use that option and
  428. it also sets a variable which is meaningful to the subproject before pulling
  429. it into the main build:
  430. .. code-block:: cmake
  431. include(FetchContent)
  432. FetchContent_Declare(
  433. protobuf
  434. GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
  435. GIT_TAG ae50d9b9902526efd6c7a1907d09739f959c6297 # v3.15.0
  436. SOURCE_SUBDIR cmake
  437. )
  438. set(protobuf_BUILD_TESTS OFF)
  439. FetchContent_MakeAvailable(protobuf)
  440. In more complex project hierarchies, the dependency relationships can be more
  441. complicated. Consider a hierarchy where ``projA`` is the top level project and
  442. it depends directly on projects ``projB`` and ``projC``. Both ``projB`` and
  443. ``projC`` can be built standalone and they also both depend on another project
  444. ``projD``. ``projB`` additionally depends on ``projE``. This example assumes
  445. that all five projects are available on a company git server. The
  446. ``CMakeLists.txt`` of each project might have sections like the following:
  447. *projA*:
  448. .. code-block:: cmake
  449. include(FetchContent)
  450. FetchContent_Declare(
  451. projB
  452. GIT_REPOSITORY [email protected]:git/projB.git
  453. GIT_TAG 4a89dc7e24ff212a7b5167bef7ab079d
  454. )
  455. FetchContent_Declare(
  456. projC
  457. GIT_REPOSITORY [email protected]:git/projC.git
  458. GIT_TAG 4ad4016bd1d8d5412d135cf8ceea1bb9
  459. )
  460. FetchContent_Declare(
  461. projD
  462. GIT_REPOSITORY [email protected]:git/projD.git
  463. GIT_TAG origin/integrationBranch
  464. )
  465. FetchContent_Declare(
  466. projE
  467. GIT_REPOSITORY [email protected]:git/projE.git
  468. GIT_TAG v2.3-rc1
  469. )
  470. # Order is important, see notes in the discussion further below
  471. FetchContent_MakeAvailable(projD projB projC)
  472. *projB*:
  473. .. code-block:: cmake
  474. include(FetchContent)
  475. FetchContent_Declare(
  476. projD
  477. GIT_REPOSITORY [email protected]:git/projD.git
  478. GIT_TAG 20b415f9034bbd2a2e8216e9a5c9e632
  479. )
  480. FetchContent_Declare(
  481. projE
  482. GIT_REPOSITORY [email protected]:git/projE.git
  483. GIT_TAG 68e20f674a48be38d60e129f600faf7d
  484. )
  485. FetchContent_MakeAvailable(projD projE)
  486. *projC*:
  487. .. code-block:: cmake
  488. include(FetchContent)
  489. FetchContent_Declare(
  490. projD
  491. GIT_REPOSITORY [email protected]:git/projD.git
  492. GIT_TAG 7d9a17ad2c962aa13e2fbb8043fb6b8a
  493. )
  494. # This particular version of projD requires workarounds
  495. FetchContent_GetProperties(projD)
  496. if(NOT projd_POPULATED)
  497. FetchContent_Populate(projD)
  498. # Copy an additional/replacement file into the populated source
  499. file(COPY someFile.c DESTINATION ${projd_SOURCE_DIR}/src)
  500. add_subdirectory(${projd_SOURCE_DIR} ${projd_BINARY_DIR})
  501. endif()
  502. A few key points should be noted in the above:
  503. - ``projB`` and ``projC`` define different content details for ``projD``,
  504. but ``projA`` also defines a set of content details for ``projD``.
  505. Because ``projA`` will define them first, the details from ``projB`` and
  506. ``projC`` will not be used. The override details defined by ``projA``
  507. are not required to match either of those from ``projB`` or ``projC``, but
  508. it is up to the higher level project to ensure that the details it does
  509. define still make sense for the child projects.
  510. - In the ``projA`` call to :command:`FetchContent_MakeAvailable`, ``projD``
  511. is listed ahead of ``projB`` and ``projC`` to ensure that ``projA`` is in
  512. control of how ``projD`` is populated.
  513. - While ``projA`` defines content details for ``projE``, it does not need
  514. to explicitly call ``FetchContent_MakeAvailable(projE)`` or
  515. ``FetchContent_Populate(projD)`` itself. Instead, it leaves that to the
  516. child ``projB``. For higher level projects, it is often enough to just
  517. define the override content details and leave the actual population to the
  518. child projects. This saves repeating the same thing at each level of the
  519. project hierarchy unnecessarily.
  520. Projects don't always need to add the populated content to the build.
  521. Sometimes the project just wants to make the downloaded content available at
  522. a predictable location. The next example ensures that a set of standard
  523. company toolchain files (and potentially even the toolchain binaries
  524. themselves) is available early enough to be used for that same build.
  525. .. code-block:: cmake
  526. cmake_minimum_required(VERSION 3.14)
  527. include(FetchContent)
  528. FetchContent_Declare(
  529. mycom_toolchains
  530. URL https://intranet.mycompany.com//toolchains_1.3.2.tar.gz
  531. )
  532. FetchContent_MakeAvailable(mycom_toolchains)
  533. project(CrossCompileExample)
  534. The project could be configured to use one of the downloaded toolchains like
  535. so:
  536. .. code-block:: shell
  537. cmake -DCMAKE_TOOLCHAIN_FILE=_deps/mycom_toolchains-src/toolchain_arm.cmake /path/to/src
  538. When CMake processes the ``CMakeLists.txt`` file, it will download and unpack
  539. the tarball into ``_deps/mycompany_toolchains-src`` relative to the build
  540. directory. The :variable:`CMAKE_TOOLCHAIN_FILE` variable is not used until
  541. the :command:`project` command is reached, at which point CMake looks for the
  542. named toolchain file relative to the build directory. Because the tarball has
  543. already been downloaded and unpacked by then, the toolchain file will be in
  544. place, even the very first time that ``cmake`` is run in the build directory.
  545. Lastly, the following example demonstrates how one might download and unpack a
  546. firmware tarball using CMake's :manual:`script mode <cmake(1)>`. The call to
  547. :command:`FetchContent_Populate` specifies all the content details and the
  548. unpacked firmware will be placed in a ``firmware`` directory below the
  549. current working directory.
  550. *getFirmware.cmake*:
  551. .. code-block:: cmake
  552. # NOTE: Intended to be run in script mode with cmake -P
  553. include(FetchContent)
  554. FetchContent_Populate(
  555. firmware
  556. URL https://mycompany.com/assets/firmware-1.23-arm.tar.gz
  557. URL_HASH MD5=68247684da89b608d466253762b0ff11
  558. SOURCE_DIR firmware
  559. )
  560. #]=======================================================================]
  561. #=======================================================================
  562. # Recording and retrieving content details for later population
  563. #=======================================================================
  564. # Internal use, projects must not call this directly. It is
  565. # intended for use by FetchContent_Declare() only.
  566. #
  567. # Sets a content-specific global property (not meant for use
  568. # outside of functions defined here in this file) which can later
  569. # be retrieved using __FetchContent_getSavedDetails() with just the
  570. # same content name. If there is already a value stored in the
  571. # property, it is left unchanged and this call has no effect.
  572. # This allows parent projects to define the content details,
  573. # overriding anything a child project may try to set (properties
  574. # are not cached between runs, so the first thing to set it in a
  575. # build will be in control).
  576. function(__FetchContent_declareDetails contentName)
  577. string(TOLOWER ${contentName} contentNameLower)
  578. set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
  579. get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
  580. if(NOT alreadyDefined)
  581. define_property(GLOBAL PROPERTY ${propertyName}
  582. BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
  583. FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
  584. )
  585. set(__cmdArgs)
  586. foreach(__item IN LISTS ARGN)
  587. string(APPEND __cmdArgs " [==[${__item}]==]")
  588. endforeach()
  589. cmake_language(EVAL CODE
  590. "set_property(GLOBAL PROPERTY ${propertyName} ${__cmdArgs})")
  591. endif()
  592. endfunction()
  593. # Internal use, projects must not call this directly. It is
  594. # intended for use by the FetchContent_Declare() function.
  595. #
  596. # Retrieves details saved for the specified content in an
  597. # earlier call to __FetchContent_declareDetails().
  598. function(__FetchContent_getSavedDetails contentName outVar)
  599. string(TOLOWER ${contentName} contentNameLower)
  600. set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
  601. get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
  602. if(NOT alreadyDefined)
  603. message(FATAL_ERROR "No content details recorded for ${contentName}")
  604. endif()
  605. get_property(propertyValue GLOBAL PROPERTY ${propertyName})
  606. set(${outVar} "${propertyValue}" PARENT_SCOPE)
  607. endfunction()
  608. # Saves population details of the content, sets defaults for the
  609. # SOURCE_DIR and BUILD_DIR.
  610. function(FetchContent_Declare contentName)
  611. set(options "")
  612. set(oneValueArgs SVN_REPOSITORY)
  613. set(multiValueArgs "")
  614. cmake_parse_arguments(PARSE_ARGV 1 ARG
  615. "${options}" "${oneValueArgs}" "${multiValueArgs}")
  616. unset(srcDirSuffix)
  617. unset(svnRepoArgs)
  618. if(ARG_SVN_REPOSITORY)
  619. # Add a hash of the svn repository URL to the source dir. This works
  620. # around the problem where if the URL changes, the download would
  621. # fail because it tries to checkout/update rather than switch the
  622. # old URL to the new one. We limit the hash to the first 7 characters
  623. # so that the source path doesn't get overly long (which can be a
  624. # problem on windows due to path length limits).
  625. string(SHA1 urlSHA ${ARG_SVN_REPOSITORY})
  626. string(SUBSTRING ${urlSHA} 0 7 urlSHA)
  627. set(srcDirSuffix "-${urlSHA}")
  628. set(svnRepoArgs SVN_REPOSITORY ${ARG_SVN_REPOSITORY})
  629. endif()
  630. string(TOLOWER ${contentName} contentNameLower)
  631. set(__argsQuoted)
  632. foreach(__item IN LISTS ARG_UNPARSED_ARGUMENTS)
  633. string(APPEND __argsQuoted " [==[${__item}]==]")
  634. endforeach()
  635. cmake_language(EVAL CODE "
  636. __FetchContent_declareDetails(
  637. ${contentNameLower}
  638. SOURCE_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src${srcDirSuffix}\"
  639. BINARY_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build\"
  640. \${svnRepoArgs}
  641. # List these last so they can override things we set above
  642. ${__argsQuoted}
  643. )"
  644. )
  645. endfunction()
  646. #=======================================================================
  647. # Set/get whether the specified content has been populated yet.
  648. # The setter also records the source and binary dirs used.
  649. #=======================================================================
  650. # Internal use, projects must not call this directly. It is
  651. # intended for use by the FetchContent_Populate() function to
  652. # record when FetchContent_Populate() is called for a particular
  653. # content name.
  654. function(__FetchContent_setPopulated contentName sourceDir binaryDir)
  655. string(TOLOWER ${contentName} contentNameLower)
  656. set(prefix "_FetchContent_${contentNameLower}")
  657. set(propertyName "${prefix}_sourceDir")
  658. define_property(GLOBAL PROPERTY ${propertyName}
  659. BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
  660. FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
  661. )
  662. set_property(GLOBAL PROPERTY ${propertyName} ${sourceDir})
  663. set(propertyName "${prefix}_binaryDir")
  664. define_property(GLOBAL PROPERTY ${propertyName}
  665. BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
  666. FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
  667. )
  668. set_property(GLOBAL PROPERTY ${propertyName} ${binaryDir})
  669. set(propertyName "${prefix}_populated")
  670. define_property(GLOBAL PROPERTY ${propertyName}
  671. BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
  672. FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
  673. )
  674. set_property(GLOBAL PROPERTY ${propertyName} True)
  675. endfunction()
  676. # Set variables in the calling scope for any of the retrievable
  677. # properties. If no specific properties are requested, variables
  678. # will be set for all retrievable properties.
  679. #
  680. # This function is intended to also be used by projects as the canonical
  681. # way to detect whether they should call FetchContent_Populate()
  682. # and pull the populated source into the build with add_subdirectory(),
  683. # if they are using the populated content in that way.
  684. function(FetchContent_GetProperties contentName)
  685. string(TOLOWER ${contentName} contentNameLower)
  686. set(options "")
  687. set(oneValueArgs SOURCE_DIR BINARY_DIR POPULATED)
  688. set(multiValueArgs "")
  689. cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  690. if(NOT ARG_SOURCE_DIR AND
  691. NOT ARG_BINARY_DIR AND
  692. NOT ARG_POPULATED)
  693. # No specific properties requested, provide them all
  694. set(ARG_SOURCE_DIR ${contentNameLower}_SOURCE_DIR)
  695. set(ARG_BINARY_DIR ${contentNameLower}_BINARY_DIR)
  696. set(ARG_POPULATED ${contentNameLower}_POPULATED)
  697. endif()
  698. set(prefix "_FetchContent_${contentNameLower}")
  699. if(ARG_SOURCE_DIR)
  700. set(propertyName "${prefix}_sourceDir")
  701. get_property(value GLOBAL PROPERTY ${propertyName})
  702. if(value)
  703. set(${ARG_SOURCE_DIR} ${value} PARENT_SCOPE)
  704. endif()
  705. endif()
  706. if(ARG_BINARY_DIR)
  707. set(propertyName "${prefix}_binaryDir")
  708. get_property(value GLOBAL PROPERTY ${propertyName})
  709. if(value)
  710. set(${ARG_BINARY_DIR} ${value} PARENT_SCOPE)
  711. endif()
  712. endif()
  713. if(ARG_POPULATED)
  714. set(propertyName "${prefix}_populated")
  715. get_property(value GLOBAL PROPERTY ${propertyName} DEFINED)
  716. set(${ARG_POPULATED} ${value} PARENT_SCOPE)
  717. endif()
  718. endfunction()
  719. #=======================================================================
  720. # Performing the population
  721. #=======================================================================
  722. # The value of contentName will always have been lowercased by the caller.
  723. # All other arguments are assumed to be options that are understood by
  724. # ExternalProject_Add(), except for QUIET and SUBBUILD_DIR.
  725. function(__FetchContent_directPopulate contentName)
  726. set(options
  727. QUIET
  728. )
  729. set(oneValueArgs
  730. SUBBUILD_DIR
  731. SOURCE_DIR
  732. BINARY_DIR
  733. # We need special processing if DOWNLOAD_NO_EXTRACT is true
  734. DOWNLOAD_NO_EXTRACT
  735. # Prevent the following from being passed through
  736. CONFIGURE_COMMAND
  737. BUILD_COMMAND
  738. INSTALL_COMMAND
  739. TEST_COMMAND
  740. # We force both of these to be ON since we are always executing serially
  741. # and we want all steps to have access to the terminal in case they
  742. # need input from the command line (e.g. ask for a private key password)
  743. # or they want to provide timely progress. We silently absorb and
  744. # discard these if they are set by the caller.
  745. USES_TERMINAL_DOWNLOAD
  746. USES_TERMINAL_UPDATE
  747. )
  748. set(multiValueArgs "")
  749. cmake_parse_arguments(PARSE_ARGV 1 ARG
  750. "${options}" "${oneValueArgs}" "${multiValueArgs}")
  751. if(NOT ARG_SUBBUILD_DIR)
  752. message(FATAL_ERROR "Internal error: SUBBUILD_DIR not set")
  753. elseif(NOT IS_ABSOLUTE "${ARG_SUBBUILD_DIR}")
  754. set(ARG_SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SUBBUILD_DIR}")
  755. endif()
  756. if(NOT ARG_SOURCE_DIR)
  757. message(FATAL_ERROR "Internal error: SOURCE_DIR not set")
  758. elseif(NOT IS_ABSOLUTE "${ARG_SOURCE_DIR}")
  759. set(ARG_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SOURCE_DIR}")
  760. endif()
  761. if(NOT ARG_BINARY_DIR)
  762. message(FATAL_ERROR "Internal error: BINARY_DIR not set")
  763. elseif(NOT IS_ABSOLUTE "${ARG_BINARY_DIR}")
  764. set(ARG_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_BINARY_DIR}")
  765. endif()
  766. # Ensure the caller can know where to find the source and build directories
  767. # with some convenient variables. Doing this here ensures the caller sees
  768. # the correct result in the case where the default values are overridden by
  769. # the content details set by the project.
  770. set(${contentName}_SOURCE_DIR "${ARG_SOURCE_DIR}" PARENT_SCOPE)
  771. set(${contentName}_BINARY_DIR "${ARG_BINARY_DIR}" PARENT_SCOPE)
  772. # The unparsed arguments may contain spaces, so build up ARG_EXTRA
  773. # in such a way that it correctly substitutes into the generated
  774. # CMakeLists.txt file with each argument quoted.
  775. unset(ARG_EXTRA)
  776. foreach(arg IN LISTS ARG_UNPARSED_ARGUMENTS)
  777. set(ARG_EXTRA "${ARG_EXTRA} \"${arg}\"")
  778. endforeach()
  779. if(ARG_DOWNLOAD_NO_EXTRACT)
  780. set(ARG_EXTRA "${ARG_EXTRA} DOWNLOAD_NO_EXTRACT YES")
  781. set(__FETCHCONTENT_COPY_FILE
  782. "
  783. ExternalProject_Get_Property(${contentName}-populate DOWNLOADED_FILE)
  784. get_filename_component(dlFileName \"\${DOWNLOADED_FILE}\" NAME)
  785. ExternalProject_Add_Step(${contentName}-populate copyfile
  786. COMMAND \"${CMAKE_COMMAND}\" -E copy_if_different
  787. \"<DOWNLOADED_FILE>\" \"${ARG_SOURCE_DIR}\"
  788. DEPENDEES patch
  789. DEPENDERS configure
  790. BYPRODUCTS \"${ARG_SOURCE_DIR}/\${dlFileName}\"
  791. COMMENT \"Copying file to SOURCE_DIR\"
  792. )
  793. ")
  794. else()
  795. unset(__FETCHCONTENT_COPY_FILE)
  796. endif()
  797. # Hide output if requested, but save it to a variable in case there's an
  798. # error so we can show the output upon failure. When not quiet, don't
  799. # capture the output to a variable because the user may want to see the
  800. # output as it happens (e.g. progress during long downloads). Combine both
  801. # stdout and stderr in the one capture variable so the output stays in order.
  802. if (ARG_QUIET)
  803. set(outputOptions
  804. OUTPUT_VARIABLE capturedOutput
  805. ERROR_VARIABLE capturedOutput
  806. )
  807. else()
  808. set(capturedOutput)
  809. set(outputOptions)
  810. message(STATUS "Populating ${contentName}")
  811. endif()
  812. if(CMAKE_GENERATOR)
  813. set(subCMakeOpts "-G${CMAKE_GENERATOR}")
  814. if(CMAKE_GENERATOR_PLATFORM)
  815. list(APPEND subCMakeOpts "-A${CMAKE_GENERATOR_PLATFORM}")
  816. endif()
  817. if(CMAKE_GENERATOR_TOOLSET)
  818. list(APPEND subCMakeOpts "-T${CMAKE_GENERATOR_TOOLSET}")
  819. endif()
  820. if(CMAKE_MAKE_PROGRAM)
  821. list(APPEND subCMakeOpts "-DCMAKE_MAKE_PROGRAM:FILEPATH=${CMAKE_MAKE_PROGRAM}")
  822. endif()
  823. else()
  824. # Likely we've been invoked via CMake's script mode where no
  825. # generator is set (and hence CMAKE_MAKE_PROGRAM could not be
  826. # trusted even if provided). We will have to rely on being
  827. # able to find the default generator and build tool.
  828. unset(subCMakeOpts)
  829. endif()
  830. set(__FETCHCONTENT_CACHED_INFO "")
  831. set(__passthrough_vars
  832. CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY
  833. CMAKE_TLS_VERIFY
  834. CMAKE_TLS_CAINFO
  835. CMAKE_NETRC
  836. CMAKE_NETRC_FILE
  837. )
  838. foreach(var IN LISTS __passthrough_vars)
  839. if(DEFINED ${var})
  840. # Embed directly in the generated CMakeLists.txt file to avoid making
  841. # the cmake command line excessively long. It also makes debugging and
  842. # testing easier.
  843. string(APPEND __FETCHCONTENT_CACHED_INFO "set(${var} [==[${${var}}]==])\n")
  844. endif()
  845. endforeach()
  846. # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
  847. list(FIND ARG_UNPARSED_ARGUMENTS GIT_REPOSITORY indexResult)
  848. if(indexResult GREATER_EQUAL 0)
  849. find_package(Git QUIET)
  850. string(APPEND __FETCHCONTENT_CACHED_INFO "
  851. # Pass through things we've already detected in the main project to avoid
  852. # paying the cost of redetecting them again in ExternalProject_Add()
  853. set(GIT_EXECUTABLE [==[${GIT_EXECUTABLE}]==])
  854. set(GIT_VERSION_STRING [==[${GIT_VERSION_STRING}]==])
  855. set_property(GLOBAL PROPERTY _CMAKE_FindGit_GIT_EXECUTABLE_VERSION
  856. [==[${GIT_EXECUTABLE};${GIT_VERSION_STRING}]==]
  857. )
  858. ")
  859. endif()
  860. # Create and build a separate CMake project to carry out the population.
  861. # If we've already previously done these steps, they will not cause
  862. # anything to be updated, so extra rebuilds of the project won't occur.
  863. # Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
  864. # has this set to something not findable on the PATH.
  865. configure_file("${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent/CMakeLists.cmake.in"
  866. "${ARG_SUBBUILD_DIR}/CMakeLists.txt")
  867. execute_process(
  868. COMMAND ${CMAKE_COMMAND} ${subCMakeOpts} .
  869. RESULT_VARIABLE result
  870. ${outputOptions}
  871. WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
  872. )
  873. if(result)
  874. if(capturedOutput)
  875. message("${capturedOutput}")
  876. endif()
  877. message(FATAL_ERROR "CMake step for ${contentName} failed: ${result}")
  878. endif()
  879. execute_process(
  880. COMMAND ${CMAKE_COMMAND} --build .
  881. RESULT_VARIABLE result
  882. ${outputOptions}
  883. WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
  884. )
  885. if(result)
  886. if(capturedOutput)
  887. message("${capturedOutput}")
  888. endif()
  889. message(FATAL_ERROR "Build step for ${contentName} failed: ${result}")
  890. endif()
  891. endfunction()
  892. option(FETCHCONTENT_FULLY_DISCONNECTED "Disables all attempts to download or update content and assumes source dirs already exist")
  893. option(FETCHCONTENT_UPDATES_DISCONNECTED "Enables UPDATE_DISCONNECTED behavior for all content population")
  894. option(FETCHCONTENT_QUIET "Enables QUIET option for all content population" ON)
  895. set(FETCHCONTENT_BASE_DIR "${CMAKE_BINARY_DIR}/_deps" CACHE PATH "Directory under which to collect all populated content")
  896. # Populate the specified content using details stored from
  897. # an earlier call to FetchContent_Declare().
  898. function(FetchContent_Populate contentName)
  899. if(NOT contentName)
  900. message(FATAL_ERROR "Empty contentName not allowed for FetchContent_Populate()")
  901. endif()
  902. string(TOLOWER ${contentName} contentNameLower)
  903. if(ARGN)
  904. # This is the direct population form with details fully specified
  905. # as part of the call, so we already have everything we need
  906. __FetchContent_directPopulate(
  907. ${contentNameLower}
  908. SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-subbuild"
  909. SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-src"
  910. BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-build"
  911. ${ARGN} # Could override any of the above ..._DIR variables
  912. )
  913. # Pass source and binary dir variables back to the caller
  914. set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
  915. set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
  916. # Don't set global properties, or record that we did this population, since
  917. # this was a direct call outside of the normal declared details form.
  918. # We only want to save values in the global properties for content that
  919. # honors the hierarchical details mechanism so that projects are not
  920. # robbed of the ability to override details set in nested projects.
  921. return()
  922. endif()
  923. # No details provided, so assume they were saved from an earlier call
  924. # to FetchContent_Declare(). Do a check that we haven't already
  925. # populated this content before in case the caller forgot to check.
  926. FetchContent_GetProperties(${contentName})
  927. if(${contentNameLower}_POPULATED)
  928. message(FATAL_ERROR "Content ${contentName} already populated in ${${contentNameLower}_SOURCE_DIR}")
  929. endif()
  930. __FetchContent_getSavedDetails(${contentName} contentDetails)
  931. if("${contentDetails}" STREQUAL "")
  932. message(FATAL_ERROR "No details have been set for content: ${contentName}")
  933. endif()
  934. string(TOUPPER ${contentName} contentNameUpper)
  935. set(FETCHCONTENT_SOURCE_DIR_${contentNameUpper}
  936. "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}"
  937. CACHE PATH "When not empty, overrides where to find pre-populated content for ${contentName}")
  938. if(FETCHCONTENT_SOURCE_DIR_${contentNameUpper})
  939. # The source directory has been explicitly provided in the cache,
  940. # so no population is required. The build directory may still be specified
  941. # by the declared details though.
  942. if(NOT IS_ABSOLUTE "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  943. # Don't check this directory because we don't know what location it is
  944. # expected to be relative to. We can't make this a hard error for backward
  945. # compatibility reasons.
  946. message(WARNING "Relative source directory specified. This is not safe, "
  947. "as it depends on the calling directory scope.\n"
  948. " FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  949. elseif(NOT EXISTS "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  950. message(FATAL_ERROR "Manually specified source directory is missing:\n"
  951. " FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  952. endif()
  953. set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  954. cmake_parse_arguments(savedDetails "" "BINARY_DIR" "" ${contentDetails})
  955. if(savedDetails_BINARY_DIR)
  956. set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
  957. else()
  958. set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  959. endif()
  960. elseif(FETCHCONTENT_FULLY_DISCONNECTED)
  961. # Bypass population and assume source is already there from a previous run.
  962. # Declared details may override the default source or build directories.
  963. cmake_parse_arguments(savedDetails "" "SOURCE_DIR;BINARY_DIR" "" ${contentDetails})
  964. if(savedDetails_SOURCE_DIR)
  965. set(${contentNameLower}_SOURCE_DIR ${savedDetails_SOURCE_DIR})
  966. else()
  967. set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
  968. endif()
  969. if(savedDetails_BINARY_DIR)
  970. set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
  971. else()
  972. set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  973. endif()
  974. else()
  975. # Support both a global "disconnect all updates" and a per-content
  976. # update test (either one being set disables updates for this content).
  977. option(FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper}
  978. "Enables UPDATE_DISCONNECTED behavior just for population of ${contentName}")
  979. if(FETCHCONTENT_UPDATES_DISCONNECTED OR
  980. FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper})
  981. set(disconnectUpdates True)
  982. else()
  983. set(disconnectUpdates False)
  984. endif()
  985. if(FETCHCONTENT_QUIET)
  986. set(quietFlag QUIET)
  987. else()
  988. unset(quietFlag)
  989. endif()
  990. set(__detailsQuoted)
  991. foreach(__item IN LISTS contentDetails)
  992. string(APPEND __detailsQuoted " [==[${__item}]==]")
  993. endforeach()
  994. cmake_language(EVAL CODE "
  995. __FetchContent_directPopulate(
  996. ${contentNameLower}
  997. ${quietFlag}
  998. UPDATE_DISCONNECTED ${disconnectUpdates}
  999. SUBBUILD_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-subbuild\"
  1000. SOURCE_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src\"
  1001. BINARY_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build\"
  1002. # Put the saved details last so they can override any of the
  1003. # the options we set above (this can include SOURCE_DIR or
  1004. # BUILD_DIR)
  1005. ${__detailsQuoted}
  1006. )"
  1007. )
  1008. endif()
  1009. __FetchContent_setPopulated(
  1010. ${contentName}
  1011. ${${contentNameLower}_SOURCE_DIR}
  1012. ${${contentNameLower}_BINARY_DIR}
  1013. )
  1014. # Pass variables back to the caller. The variables passed back here
  1015. # must match what FetchContent_GetProperties() sets when it is called
  1016. # with just the content name.
  1017. set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
  1018. set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
  1019. set(${contentNameLower}_POPULATED True PARENT_SCOPE)
  1020. endfunction()
  1021. # Arguments are assumed to be the names of dependencies that have been
  1022. # declared previously and should be populated. It is not an error if
  1023. # any of them have already been populated (they will just be skipped in
  1024. # that case). The command is implemented as a macro so that the variables
  1025. # defined by the FetchContent_GetProperties() and FetchContent_Populate()
  1026. # calls will be available to the caller.
  1027. macro(FetchContent_MakeAvailable)
  1028. foreach(__cmake_contentName IN ITEMS ${ARGV})
  1029. string(TOLOWER ${__cmake_contentName} __cmake_contentNameLower)
  1030. FetchContent_GetProperties(${__cmake_contentName})
  1031. if(NOT ${__cmake_contentNameLower}_POPULATED)
  1032. FetchContent_Populate(${__cmake_contentName})
  1033. # Only try to call add_subdirectory() if the populated content
  1034. # can be treated that way. Protecting the call with the check
  1035. # allows this function to be used for projects that just want
  1036. # to ensure the content exists, such as to provide content at
  1037. # a known location. We check the saved details for an optional
  1038. # SOURCE_SUBDIR which can be used in the same way as its meaning
  1039. # for ExternalProject. It won't matter if it was passed through
  1040. # to the ExternalProject sub-build, since it would have been
  1041. # ignored there.
  1042. set(__cmake_srcdir "${${__cmake_contentNameLower}_SOURCE_DIR}")
  1043. __FetchContent_getSavedDetails(${__cmake_contentName} __cmake_contentDetails)
  1044. if("${__cmake_contentDetails}" STREQUAL "")
  1045. message(FATAL_ERROR "No details have been set for content: ${__cmake_contentName}")
  1046. endif()
  1047. cmake_parse_arguments(__cmake_arg "" "SOURCE_SUBDIR" "" ${__cmake_contentDetails})
  1048. if(NOT "${__cmake_arg_SOURCE_SUBDIR}" STREQUAL "")
  1049. string(APPEND __cmake_srcdir "/${__cmake_arg_SOURCE_SUBDIR}")
  1050. endif()
  1051. if(EXISTS ${__cmake_srcdir}/CMakeLists.txt)
  1052. add_subdirectory(${__cmake_srcdir} ${${__cmake_contentNameLower}_BINARY_DIR})
  1053. endif()
  1054. unset(__cmake_srcdir)
  1055. endif()
  1056. endforeach()
  1057. # clear local variables to prevent leaking into the caller's scope
  1058. unset(__cmake_contentName)
  1059. unset(__cmake_contentNameLower)
  1060. unset(__cmake_contentDetails)
  1061. unset(__cmake_arg_SOURCE_SUBDIR)
  1062. endmacro()