FetchContent.cmake 49 KB

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