FetchContent.cmake 46 KB

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