FetchContent.cmake 48 KB

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