FetchContent.cmake 48 KB

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