FetchContent.cmake 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. FetchContent
  5. ------------------
  6. .. only:: html
  7. .. contents::
  8. Overview
  9. ^^^^^^^^
  10. This module enables populating content at configure time via any method
  11. supported by the :module:`ExternalProject` module. Whereas
  12. :command:`ExternalProject_Add` downloads at build time, the
  13. ``FetchContent`` module makes content available immediately, allowing the
  14. configure step to use the content in commands like :command:`add_subdirectory`,
  15. :command:`include` or :command:`file` operations.
  16. Content population details would normally be defined separately from the
  17. command that performs the actual population. Projects should also
  18. check whether the content has already been populated somewhere else in the
  19. project hierarchy. Typical usage would look something like this:
  20. .. code-block:: cmake
  21. FetchContent_Declare(
  22. googletest
  23. GIT_REPOSITORY https://github.com/google/googletest.git
  24. GIT_TAG release-1.8.0
  25. )
  26. FetchContent_GetProperties(googletest)
  27. if(NOT googletest_POPULATED)
  28. FetchContent_Populate(googletest)
  29. add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
  30. endif()
  31. When using the above pattern with a hierarchical project arrangement,
  32. projects at higher levels in the hierarchy are able to define or override
  33. the population details of content specified anywhere lower in the project
  34. hierarchy. The ability to detect whether content has already been
  35. populated ensures that even if multiple child projects want certain content
  36. to be available, the first one to populate it wins. The other child project
  37. can simply make use of the already available content instead of repeating
  38. the population for itself. See the
  39. :ref:`Examples <fetch-content-examples>` section which demonstrates
  40. this scenario.
  41. The ``FetchContent`` module also supports defining and populating
  42. content in a single call, with no check for whether the content has been
  43. populated elsewhere in the project already. This is a more low level
  44. operation and would not normally be the way the module is used, but it is
  45. sometimes useful as part of implementing some higher level feature or to
  46. populate some content in CMake's script mode.
  47. Declaring Content Details
  48. ^^^^^^^^^^^^^^^^^^^^^^^^^
  49. .. command:: FetchContent_Declare
  50. .. code-block:: cmake
  51. FetchContent_Declare(<name> <contentOptions>...)
  52. The ``FetchContent_Declare()`` function records the options that describe
  53. how to populate the specified content, but if such details have already
  54. been recorded earlier in this project (regardless of where in the project
  55. hierarchy), this and all later calls for the same content ``<name>`` are
  56. ignored. This "first to record, wins" approach is what allows hierarchical
  57. projects to have parent projects override content details of child projects.
  58. The content ``<name>`` can be any string without spaces, but good practice
  59. would be to use only letters, numbers and underscores. The name will be
  60. treated case-insensitively and it should be obvious for the content it
  61. represents, often being the name of the child project or the value given
  62. to its top level :command:`project` command (if it is a CMake project).
  63. For well-known public projects, the name should generally be the official
  64. name of the project. Choosing an unusual name makes it unlikely that other
  65. projects needing that same content will use the same name, leading to
  66. the content being populated multiple times.
  67. The ``<contentOptions>`` can be any of the download or update/patch options
  68. that the :command:`ExternalProject_Add` command understands. The configure,
  69. build, install and test steps are explicitly disabled and therefore options
  70. related to them will be ignored. In most cases, ``<contentOptions>`` will
  71. just be a couple of options defining the download method and method-specific
  72. details like a commit tag or archive hash. For example:
  73. .. code-block:: cmake
  74. FetchContent_Declare(
  75. googletest
  76. GIT_REPOSITORY https://github.com/google/googletest.git
  77. GIT_TAG release-1.8.0
  78. )
  79. FetchContent_Declare(
  80. myCompanyIcons
  81. URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  82. URL_HASH 5588a7b18261c20068beabfb4f530b87
  83. )
  84. FetchContent_Declare(
  85. myCompanyCertificates
  86. SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs
  87. SVN_REVISION -r12345
  88. )
  89. Populating The Content
  90. ^^^^^^^^^^^^^^^^^^^^^^
  91. .. command:: FetchContent_Populate
  92. .. code-block:: cmake
  93. FetchContent_Populate( <name> )
  94. In most cases, the only argument given to ``FetchContent_Populate()`` is the
  95. ``<name>``. When used this way, the command assumes the content details have
  96. been recorded by an earlier call to :command:`FetchContent_Declare`. The
  97. details are stored in a global property, so they are unaffected by things
  98. like variable or directory scope. Therefore, it doesn't matter where in the
  99. project the details were previously declared, as long as they have been
  100. declared before the call to ``FetchContent_Populate()``. Those saved details
  101. are then used to construct a call to :command:`ExternalProject_Add` in a
  102. private sub-build to perform the content population immediately. The
  103. implementation of ``ExternalProject_Add()`` ensures that if the content has
  104. already been populated in a previous CMake run, that content will be reused
  105. rather than repopulating them again. For the common case where population
  106. involves downloading content, the cost of the download is only paid once.
  107. An internal global property records when a particular content population
  108. request has been processed. If ``FetchContent_Populate()`` is called more
  109. than once for the same content name within a configure run, the second call
  110. will halt with an error. Projects can and should check whether content
  111. population has already been processed with the
  112. :command:`FetchContent_GetProperties` command before calling
  113. ``FetchContent_Populate()``.
  114. ``FetchContent_Populate()`` will set three variables in the scope of the
  115. caller; ``<lcName>_POPULATED``, ``<lcName>_SOURCE_DIR`` and
  116. ``<lcName>_BINARY_DIR``, where ``<lcName>`` is the lowercased ``<name>``.
  117. ``<lcName>_POPULATED`` will always be set to ``True`` by the call.
  118. ``<lcName>_SOURCE_DIR`` is the location where the
  119. content can be found upon return (it will have already been populated), while
  120. ``<lcName>_BINARY_DIR`` is a directory intended for use as a corresponding
  121. build directory. The main use case for the two directory variables is to
  122. call :command:`add_subdirectory` immediately after population, i.e.:
  123. .. code-block:: cmake
  124. FetchContent_Populate(FooBar ...)
  125. add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
  126. The values of the three variables can also be retrieved from anywhere in the
  127. project hierarchy using the :command:`FetchContent_GetProperties` command.
  128. A number of cache variables influence the behavior of all content population
  129. performed using details saved from a :command:`FetchContent_Declare` call:
  130. ``FETCHCONTENT_BASE_DIR``
  131. In most cases, the saved details do not specify any options relating to the
  132. directories to use for the internal sub-build, final source and build areas.
  133. It is generally best to leave these decisions up to the ``FetchContent``
  134. module to handle on the project's behalf. The ``FETCHCONTENT_BASE_DIR``
  135. cache variable controls the point under which all content population
  136. directories are collected, but in most cases developers would not need to
  137. change this. The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
  138. developers change this value, they should aim to keep the path short and
  139. just below the top level of the build tree to avoid running into path
  140. length problems on Windows.
  141. ``FETCHCONTENT_QUIET``
  142. The logging output during population can be quite verbose, making the
  143. configure stage quite noisy. This cache option (``ON`` by default) hides
  144. all population output unless an error is encountered. If experiencing
  145. problems with hung downloads, temporarily switching this option off may
  146. help diagnose which content population is causing the issue.
  147. ``FETCHCONTENT_FULLY_DISCONNECTED``
  148. When this option is enabled, no attempt is made to download or update
  149. any content. It is assumed that all content has already been populated in
  150. a previous run or the source directories have been pointed at existing
  151. contents the developer has provided manually (using options described
  152. further below). When the developer knows that no changes have been made to
  153. any content details, turning this option ``ON`` can significantly speed up
  154. the configure stage. It is ``OFF`` by default.
  155. ``FETCHCONTENT_UPDATES_DISCONNECTED``
  156. This is a less severe download/update control compared to
  157. ``FETCHCONTENT_FULLY_DISCONNECTED``. Instead of bypassing all download and
  158. update logic, the ``FETCHCONTENT_UPDATES_DISCONNECTED`` only disables the
  159. update stage. Therefore, if content has not been downloaded previously,
  160. it will still be downloaded when this option is enabled. This can speed up
  161. the configure stage, but not as much as
  162. ``FETCHCONTENT_FULLY_DISCONNECTED``. It is ``OFF`` by default.
  163. In addition to the above cache variables, the following cache variables are
  164. also defined for each content name (``<ucName>`` is the uppercased value of
  165. ``<name>``):
  166. ``FETCHCONTENT_SOURCE_DIR_<ucName>``
  167. If this is set, no download or update steps are performed for the specified
  168. content and the ``<lcName>_SOURCE_DIR`` variable returned to the caller is
  169. pointed at this location. This gives developers a way to have a separate
  170. checkout of the content that they can modify freely without interference
  171. from the build. The build simply uses that existing source, but it still
  172. defines ``<lcName>_BINARY_DIR`` to point inside its own build area.
  173. Developers are strongly encouraged to use this mechanism rather than
  174. editing the sources populated in the default location, as changes to
  175. sources in the default location can be lost when content population details
  176. are changed by the project.
  177. ``FETCHCONTENT_UPDATES_DISCONNECTED_<ucName>``
  178. This is the per-content equivalent of
  179. ``FETCHCONTENT_UPDATES_DISCONNECTED``. If the global option or this option
  180. is ``ON``, then updates will be disabled for the named content.
  181. Disabling updates for individual content can be useful for content whose
  182. details rarely change, while still leaving other frequently changing
  183. content with updates enabled.
  184. The ``FetchContent_Populate()`` command also supports a syntax allowing the
  185. content details to be specified directly rather than using any saved
  186. details. This is more low-level and use of this form is generally to be
  187. avoided in favour of using saved content details as outlined above.
  188. Nevertheless, in certain situations it can be useful to invoke the content
  189. population as an isolated operation (typically as part of implementing some
  190. other higher level feature or when using CMake in script mode):
  191. .. code-block:: cmake
  192. FetchContent_Populate( <name>
  193. [QUIET]
  194. [SUBBUILD_DIR <subBuildDir>]
  195. [SOURCE_DIR <srcDir>]
  196. [BINARY_DIR <binDir>]
  197. ...
  198. )
  199. This form has a number of key differences to that where only ``<name>`` is
  200. provided:
  201. - All required population details are assumed to have been provided directly
  202. in the call to ``FetchContent_Populate()``. Any saved details for
  203. ``<name>`` are ignored.
  204. - No check is made for whether content for ``<name>`` has already been
  205. populated.
  206. - No global property is set to record that the population has occurred.
  207. - No global properties record the source or binary directories used for the
  208. populated content.
  209. - The ``FETCHCONTENT_FULLY_DISCONNECTED`` and
  210. ``FETCHCONTENT_UPDATES_DISCONNECTED`` cache variables are ignored.
  211. The ``<lcName>_SOURCE_DIR`` and ``<lcName>_BINARY_DIR`` variables are still
  212. returned to the caller, but since these locations are not stored as global
  213. properties when this form is used, they are only available to the calling
  214. scope and below rather than the entire project hierarchy. No
  215. ``<lcName>_POPULATED`` variable is set in the caller's scope with this form.
  216. The supported options for ``FetchContent_Populate()`` are the same as those
  217. for :command:`FetchContent_Declare()`. Those few options shown just
  218. above are either specific to ``FetchContent_Populate()`` or their behavior is
  219. slightly modified from how :command:`ExternalProject_Add` treats them.
  220. ``QUIET``
  221. The ``QUIET`` option can be given to hide the output associated with
  222. populating the specified content. If the population fails, the output will
  223. be shown regardless of whether this option was given or not so that the
  224. cause of the failure can be diagnosed. The global ``FETCHCONTENT_QUIET``
  225. cache variable has no effect on ``FetchContent_Populate()`` calls where the
  226. content details are provided directly.
  227. ``SUBBUILD_DIR``
  228. The ``SUBBUILD_DIR`` argument can be provided to change the location of the
  229. sub-build created to perform the population. The default value is
  230. ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-subbuild`` and it would be unusual
  231. to need to override this default. If a relative path is specified, it will
  232. be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
  233. ``SOURCE_DIR``, ``BINARY_DIR``
  234. The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments are supported by
  235. :command:`ExternalProject_Add`, but different default values are used by
  236. ``FetchContent_Populate()``. ``SOURCE_DIR`` defaults to
  237. ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-src`` and ``BINARY_DIR`` defaults to
  238. ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-build``. If a relative path is
  239. specified, it will be interpreted as relative to
  240. :variable:`CMAKE_CURRENT_BINARY_DIR`.
  241. In addition to the above explicit options, any other unrecognized options are
  242. passed through unmodified to :command:`ExternalProject_Add` to perform the
  243. download, patch and update steps. The following options are explicitly
  244. prohibited (they are disabled by the ``FetchContent_Populate()`` command):
  245. - ``CONFIGURE_COMMAND``
  246. - ``BUILD_COMMAND``
  247. - ``INSTALL_COMMAND``
  248. - ``TEST_COMMAND``
  249. If using ``FetchContent_Populate()`` within CMake's script mode, be aware
  250. that the implementation sets up a sub-build which therefore requires a CMake
  251. generator and build tool to be available. If these cannot be found by
  252. default, then the :variable:`CMAKE_GENERATOR` and/or
  253. :variable:`CMAKE_MAKE_PROGRAM` variables will need to be set appropriately
  254. on the command line invoking the script.
  255. Retrieve Population Properties
  256. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  257. .. command:: FetchContent_GetProperties
  258. When using saved content details, a call to :command:`FetchContent_Populate`
  259. records information in global properties which can be queried at any time.
  260. This information includes the source and binary directories associated with
  261. the content and also whether or not the content population has been processed
  262. during the current configure run.
  263. .. code-block:: cmake
  264. FetchContent_GetProperties( <name>
  265. [SOURCE_DIR <srcDirVar>]
  266. [BINARY_DIR <binDirVar>]
  267. [POPULATED <doneVar>]
  268. )
  269. The ``SOURCE_DIR``, ``BINARY_DIR`` and ``POPULATED`` options can be used to
  270. specify which properties should be retrieved. Each option accepts a value
  271. which is the name of the variable in which to store that property. Most of
  272. the time though, only ``<name>`` is given, in which case the call will then
  273. set the same variables as a call to
  274. :command:`FetchContent_Populate(name) <FetchContent_Populate>`. This allows
  275. the following canonical pattern to be used, which ensures that the relevant
  276. variables will always be defined regardless of whether or not the population
  277. has been performed elsewhere in the project already:
  278. .. code-block:: cmake
  279. FetchContent_GetProperties(foobar)
  280. if(NOT foobar_POPULATED)
  281. FetchContent_Populate(foobar)
  282. # Set any custom variables, etc. here, then
  283. # populate the content as part of this build
  284. add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
  285. endif()
  286. The above pattern allows other parts of the overall project hierarchy to
  287. re-use the same content and ensure that it is only populated once.
  288. .. _`fetch-content-examples`:
  289. Examples
  290. ^^^^^^^^
  291. Consider a project hierarchy where ``projA`` is the top level project and it
  292. depends on projects ``projB`` and ``projC``. Both ``projB`` and ``projC``
  293. can be built standalone and they also both depend on another project
  294. ``projD``. For simplicity, this example will assume that all four projects
  295. are available on a company git server. The ``CMakeLists.txt`` of each project
  296. might have sections like the following:
  297. *projA*:
  298. .. code-block:: cmake
  299. include(FetchContent)
  300. FetchContent_Declare(
  301. projB
  302. GIT_REPOSITORY git@mycompany.com/git/projB.git
  303. GIT_TAG 4a89dc7e24ff212a7b5167bef7ab079d
  304. )
  305. FetchContent_Declare(
  306. projC
  307. GIT_REPOSITORY git@mycompany.com/git/projC.git
  308. GIT_TAG 4ad4016bd1d8d5412d135cf8ceea1bb9
  309. )
  310. FetchContent_Declare(
  311. projD
  312. GIT_REPOSITORY git@mycompany.com/git/projD.git
  313. GIT_TAG origin/integrationBranch
  314. )
  315. FetchContent_GetProperties(projB)
  316. if(NOT projb_POPULATED)
  317. FetchContent_Populate(projB)
  318. add_subdirectory(${projb_SOURCE_DIR} ${projb_BINARY_DIR})
  319. endif()
  320. FetchContent_GetProperties(projC)
  321. if(NOT projc_POPULATED)
  322. FetchContent_Populate(projC)
  323. add_subdirectory(${projc_SOURCE_DIR} ${projc_BINARY_DIR})
  324. endif()
  325. *projB*:
  326. .. code-block:: cmake
  327. include(FetchContent)
  328. FetchContent_Declare(
  329. projD
  330. GIT_REPOSITORY git@mycompany.com/git/projD.git
  331. GIT_TAG 20b415f9034bbd2a2e8216e9a5c9e632
  332. )
  333. FetchContent_GetProperties(projD)
  334. if(NOT projd_POPULATED)
  335. FetchContent_Populate(projD)
  336. add_subdirectory(${projd_SOURCE_DIR} ${projd_BINARY_DIR})
  337. endif()
  338. *projC*:
  339. .. code-block:: cmake
  340. include(FetchContent)
  341. FetchContent_Declare(
  342. projD
  343. GIT_REPOSITORY git@mycompany.com/git/projD.git
  344. GIT_TAG 7d9a17ad2c962aa13e2fbb8043fb6b8a
  345. )
  346. FetchContent_GetProperties(projD)
  347. if(NOT projd_POPULATED)
  348. FetchContent_Populate(projD)
  349. add_subdirectory(${projd_SOURCE_DIR} ${projd_BINARY_DIR})
  350. endif()
  351. A few key points should be noted in the above:
  352. - ``projB`` and ``projC`` define different content details for ``projD``,
  353. but ``projA`` also defines a set of content details for ``projD`` and
  354. because ``projA`` will define them first, the details from ``projB`` and
  355. ``projC`` will not be used. The override details defined by ``projA``
  356. are not required to match either of those from ``projB`` or ``projC``, but
  357. it is up to the higher level project to ensure that the details it does
  358. define still make sense for the child projects.
  359. - While ``projA`` defined content details for ``projD``, it did not need
  360. to explicitly call ``FetchContent_Populate(projD)`` itself. Instead, it
  361. leaves that to a child project to do (in this case it will be ``projB``
  362. since it is added to the build ahead of ``projC``). If ``projA`` needed to
  363. customize how the ``projD`` content was brought into the build as well
  364. (e.g. define some CMake variables before calling
  365. :command:`add_subdirectory` after populating), it would do the call to
  366. ``FetchContent_Populate()``, etc. just as it did for the ``projB`` and
  367. ``projC`` content. For higher level projects, it is usually enough to
  368. just define the override content details and leave the actual population
  369. to the child projects. This saves repeating the same thing at each level
  370. of the project hierarchy unnecessarily.
  371. - Even though ``projA`` is the top level project in this example, it still
  372. checks whether ``projB`` and ``projC`` have already been populated before
  373. going ahead to do those populations. This makes ``projA`` able to be more
  374. easily incorporated as a child of some other higher level project in the
  375. future if required. Always protect a call to
  376. :command:`FetchContent_Populate` with a check to
  377. :command:`FetchContent_GetProperties`, even in what may be considered a top
  378. level project at the time.
  379. The following example demonstrates how one might download and unpack a
  380. firmware tarball using CMake's :manual:`script mode <cmake(1)>`. The call to
  381. :command:`FetchContent_Populate` specifies all the content details and the
  382. unpacked firmware will be placed in a ``firmware`` directory below the
  383. current working directory.
  384. *getFirmware.cmake*:
  385. .. code-block:: cmake
  386. # NOTE: Intended to be run in script mode with cmake -P
  387. include(FetchContent)
  388. FetchContent_Populate(
  389. firmware
  390. URL https://mycompany.com/assets/firmware-1.23-arm.tar.gz
  391. URL_HASH MD5=68247684da89b608d466253762b0ff11
  392. SOURCE_DIR firmware
  393. )
  394. #]=======================================================================]
  395. set(__FetchContent_privateDir "${CMAKE_CURRENT_LIST_DIR}/FetchContent")
  396. #=======================================================================
  397. # Recording and retrieving content details for later population
  398. #=======================================================================
  399. # Internal use, projects must not call this directly. It is
  400. # intended for use by FetchContent_Declare() only.
  401. #
  402. # Sets a content-specific global property (not meant for use
  403. # outside of functions defined here in this file) which can later
  404. # be retrieved using __FetchContent_getSavedDetails() with just the
  405. # same content name. If there is already a value stored in the
  406. # property, it is left unchanged and this call has no effect.
  407. # This allows parent projects to define the content details,
  408. # overriding anything a child project may try to set (properties
  409. # are not cached between runs, so the first thing to set it in a
  410. # build will be in control).
  411. function(__FetchContent_declareDetails contentName)
  412. string(TOLOWER ${contentName} contentNameLower)
  413. set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
  414. get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
  415. if(NOT alreadyDefined)
  416. define_property(GLOBAL PROPERTY ${propertyName}
  417. BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
  418. FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
  419. )
  420. set_property(GLOBAL PROPERTY ${propertyName} ${ARGN})
  421. endif()
  422. endfunction()
  423. # Internal use, projects must not call this directly. It is
  424. # intended for use by the FetchContent_Declare() function.
  425. #
  426. # Retrieves details saved for the specified content in an
  427. # earlier call to __FetchContent_declareDetails().
  428. function(__FetchContent_getSavedDetails contentName outVar)
  429. string(TOLOWER ${contentName} contentNameLower)
  430. set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
  431. get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
  432. if(NOT alreadyDefined)
  433. message(FATAL_ERROR "No content details recorded for ${contentName}")
  434. endif()
  435. get_property(propertyValue GLOBAL PROPERTY ${propertyName})
  436. set(${outVar} "${propertyValue}" PARENT_SCOPE)
  437. endfunction()
  438. # Saves population details of the content, sets defaults for the
  439. # SOURCE_DIR and BUILD_DIR.
  440. function(FetchContent_Declare contentName)
  441. set(options "")
  442. set(oneValueArgs SVN_REPOSITORY)
  443. set(multiValueArgs "")
  444. cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  445. unset(srcDirSuffix)
  446. unset(svnRepoArgs)
  447. if(ARG_SVN_REPOSITORY)
  448. # Add a hash of the svn repository URL to the source dir. This works
  449. # around the problem where if the URL changes, the download would
  450. # fail because it tries to checkout/update rather than switch the
  451. # old URL to the new one. We limit the hash to the first 7 characters
  452. # so that the source path doesn't get overly long (which can be a
  453. # problem on windows due to path length limits).
  454. string(SHA1 urlSHA ${ARG_SVN_REPOSITORY})
  455. string(SUBSTRING ${urlSHA} 0 7 urlSHA)
  456. set(srcDirSuffix "-${urlSHA}")
  457. set(svnRepoArgs SVN_REPOSITORY ${ARG_SVN_REPOSITORY})
  458. endif()
  459. string(TOLOWER ${contentName} contentNameLower)
  460. __FetchContent_declareDetails(
  461. ${contentNameLower}
  462. SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src${srcDirSuffix}"
  463. BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build"
  464. ${svnRepoArgs}
  465. # List these last so they can override things we set above
  466. ${ARG_UNPARSED_ARGUMENTS}
  467. )
  468. endfunction()
  469. #=======================================================================
  470. # Set/get whether the specified content has been populated yet.
  471. # The setter also records the source and binary dirs used.
  472. #=======================================================================
  473. # Internal use, projects must not call this directly. It is
  474. # intended for use by the FetchContent_Populate() function to
  475. # record when FetchContent_Populate() is called for a particular
  476. # content name.
  477. function(__FetchContent_setPopulated contentName sourceDir binaryDir)
  478. string(TOLOWER ${contentName} contentNameLower)
  479. set(prefix "_FetchContent_${contentNameLower}")
  480. set(propertyName "${prefix}_sourceDir")
  481. define_property(GLOBAL PROPERTY ${propertyName}
  482. BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
  483. FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
  484. )
  485. set_property(GLOBAL PROPERTY ${propertyName} ${sourceDir})
  486. set(propertyName "${prefix}_binaryDir")
  487. define_property(GLOBAL PROPERTY ${propertyName}
  488. BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
  489. FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
  490. )
  491. set_property(GLOBAL PROPERTY ${propertyName} ${binaryDir})
  492. set(propertyName "${prefix}_populated")
  493. define_property(GLOBAL PROPERTY ${propertyName}
  494. BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
  495. FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
  496. )
  497. set_property(GLOBAL PROPERTY ${propertyName} True)
  498. endfunction()
  499. # Set variables in the calling scope for any of the retrievable
  500. # properties. If no specific properties are requested, variables
  501. # will be set for all retrievable properties.
  502. #
  503. # This function is intended to also be used by projects as the canonical
  504. # way to detect whether they should call FetchContent_Populate()
  505. # and pull the populated source into the build with add_subdirectory(),
  506. # if they are using the populated content in that way.
  507. function(FetchContent_GetProperties contentName)
  508. string(TOLOWER ${contentName} contentNameLower)
  509. set(options "")
  510. set(oneValueArgs SOURCE_DIR BINARY_DIR POPULATED)
  511. set(multiValueArgs "")
  512. cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  513. if(NOT ARG_SOURCE_DIR AND
  514. NOT ARG_BINARY_DIR AND
  515. NOT ARG_POPULATED)
  516. # No specific properties requested, provide them all
  517. set(ARG_SOURCE_DIR ${contentNameLower}_SOURCE_DIR)
  518. set(ARG_BINARY_DIR ${contentNameLower}_BINARY_DIR)
  519. set(ARG_POPULATED ${contentNameLower}_POPULATED)
  520. endif()
  521. set(prefix "_FetchContent_${contentNameLower}")
  522. if(ARG_SOURCE_DIR)
  523. set(propertyName "${prefix}_sourceDir")
  524. get_property(value GLOBAL PROPERTY ${propertyName})
  525. if(value)
  526. set(${ARG_SOURCE_DIR} ${value} PARENT_SCOPE)
  527. endif()
  528. endif()
  529. if(ARG_BINARY_DIR)
  530. set(propertyName "${prefix}_binaryDir")
  531. get_property(value GLOBAL PROPERTY ${propertyName})
  532. if(value)
  533. set(${ARG_BINARY_DIR} ${value} PARENT_SCOPE)
  534. endif()
  535. endif()
  536. if(ARG_POPULATED)
  537. set(propertyName "${prefix}_populated")
  538. get_property(value GLOBAL PROPERTY ${propertyName} DEFINED)
  539. set(${ARG_POPULATED} ${value} PARENT_SCOPE)
  540. endif()
  541. endfunction()
  542. #=======================================================================
  543. # Performing the population
  544. #=======================================================================
  545. # The value of contentName will always have been lowercased by the caller.
  546. # All other arguments are assumed to be options that are understood by
  547. # ExternalProject_Add(), except for QUIET and SUBBUILD_DIR.
  548. function(__FetchContent_directPopulate contentName)
  549. set(options
  550. QUIET
  551. )
  552. set(oneValueArgs
  553. SUBBUILD_DIR
  554. SOURCE_DIR
  555. BINARY_DIR
  556. # Prevent the following from being passed through
  557. CONFIGURE_COMMAND
  558. BUILD_COMMAND
  559. INSTALL_COMMAND
  560. TEST_COMMAND
  561. )
  562. set(multiValueArgs "")
  563. cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  564. if(NOT ARG_SUBBUILD_DIR)
  565. message(FATAL_ERROR "Internal error: SUBBUILD_DIR not set")
  566. elseif(NOT IS_ABSOLUTE "${ARG_SUBBUILD_DIR}")
  567. set(ARG_SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SUBBUILD_DIR}")
  568. endif()
  569. if(NOT ARG_SOURCE_DIR)
  570. message(FATAL_ERROR "Internal error: SOURCE_DIR not set")
  571. elseif(NOT IS_ABSOLUTE "${ARG_SOURCE_DIR}")
  572. set(ARG_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SOURCE_DIR}")
  573. endif()
  574. if(NOT ARG_BINARY_DIR)
  575. message(FATAL_ERROR "Internal error: BINARY_DIR not set")
  576. elseif(NOT IS_ABSOLUTE "${ARG_BINARY_DIR}")
  577. set(ARG_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_BINARY_DIR}")
  578. endif()
  579. # Ensure the caller can know where to find the source and build directories
  580. # with some convenient variables. Doing this here ensures the caller sees
  581. # the correct result in the case where the default values are overridden by
  582. # the content details set by the project.
  583. set(${contentName}_SOURCE_DIR "${ARG_SOURCE_DIR}" PARENT_SCOPE)
  584. set(${contentName}_BINARY_DIR "${ARG_BINARY_DIR}" PARENT_SCOPE)
  585. # The unparsed arguments may contain spaces, so build up ARG_EXTRA
  586. # in such a way that it correctly substitutes into the generated
  587. # CMakeLists.txt file with each argument quoted.
  588. unset(ARG_EXTRA)
  589. foreach(arg IN LISTS ARG_UNPARSED_ARGUMENTS)
  590. set(ARG_EXTRA "${ARG_EXTRA} \"${arg}\"")
  591. endforeach()
  592. # Hide output if requested, but save it to a variable in case there's an
  593. # error so we can show the output upon failure. When not quiet, don't
  594. # capture the output to a variable because the user may want to see the
  595. # output as it happens (e.g. progress during long downloads). Combine both
  596. # stdout and stderr in the one capture variable so the output stays in order.
  597. if (ARG_QUIET)
  598. set(outputOptions
  599. OUTPUT_VARIABLE capturedOutput
  600. ERROR_VARIABLE capturedOutput
  601. )
  602. else()
  603. set(capturedOutput)
  604. set(outputOptions)
  605. message(STATUS "Populating ${contentName}")
  606. endif()
  607. if(CMAKE_GENERATOR)
  608. set(generatorOpts "-G${CMAKE_GENERATOR}")
  609. if(CMAKE_GENERATOR_PLATFORM)
  610. list(APPEND generatorOpts "-A${CMAKE_GENERATOR_PLATFORM}")
  611. endif()
  612. if(CMAKE_GENERATOR_TOOLSET)
  613. list(APPEND generatorOpts "-T${CMAKE_GENERATOR_TOOLSET}")
  614. endif()
  615. if(CMAKE_MAKE_PROGRAM)
  616. list(APPEND generatorOpts "-DCMAKE_MAKE_PROGRAM:FILEPATH=${CMAKE_MAKE_PROGRAM}")
  617. endif()
  618. else()
  619. # Likely we've been invoked via CMake's script mode where no
  620. # generator is set (and hence CMAKE_MAKE_PROGRAM could not be
  621. # trusted even if provided). We will have to rely on being
  622. # able to find the default generator and build tool.
  623. unset(generatorOpts)
  624. endif()
  625. # Create and build a separate CMake project to carry out the population.
  626. # If we've already previously done these steps, they will not cause
  627. # anything to be updated, so extra rebuilds of the project won't occur.
  628. # Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
  629. # has this set to something not findable on the PATH.
  630. configure_file("${__FetchContent_privateDir}/CMakeLists.cmake.in"
  631. "${ARG_SUBBUILD_DIR}/CMakeLists.txt")
  632. execute_process(
  633. COMMAND ${CMAKE_COMMAND} ${generatorOpts} .
  634. RESULT_VARIABLE result
  635. ${outputOptions}
  636. WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
  637. )
  638. if(result)
  639. if(capturedOutput)
  640. message("${capturedOutput}")
  641. endif()
  642. message(FATAL_ERROR "CMake step for ${contentName} failed: ${result}")
  643. endif()
  644. execute_process(
  645. COMMAND ${CMAKE_COMMAND} --build .
  646. RESULT_VARIABLE result
  647. ${outputOptions}
  648. WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
  649. )
  650. if(result)
  651. if(capturedOutput)
  652. message("${capturedOutput}")
  653. endif()
  654. message(FATAL_ERROR "Build step for ${contentName} failed: ${result}")
  655. endif()
  656. endfunction()
  657. option(FETCHCONTENT_FULLY_DISCONNECTED "Disables all attempts to download or update content and assumes source dirs already exist")
  658. option(FETCHCONTENT_UPDATES_DISCONNECTED "Enables UPDATE_DISCONNECTED behavior for all content population")
  659. option(FETCHCONTENT_QUIET "Enables QUIET option for all content population" ON)
  660. set(FETCHCONTENT_BASE_DIR "${CMAKE_BINARY_DIR}/_deps" CACHE PATH "Directory under which to collect all populated content")
  661. # Populate the specified content using details stored from
  662. # an earlier call to FetchContent_Declare().
  663. function(FetchContent_Populate contentName)
  664. if(NOT contentName)
  665. message(FATAL_ERROR "Empty contentName not allowed for FetchContent_Populate()")
  666. endif()
  667. string(TOLOWER ${contentName} contentNameLower)
  668. if(ARGN)
  669. # This is the direct population form with details fully specified
  670. # as part of the call, so we already have everything we need
  671. __FetchContent_directPopulate(
  672. ${contentNameLower}
  673. SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-subbuild"
  674. SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-src"
  675. BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-build"
  676. ${ARGN} # Could override any of the above ..._DIR variables
  677. )
  678. # Pass source and binary dir variables back to the caller
  679. set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
  680. set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
  681. # Don't set global properties, or record that we did this population, since
  682. # this was a direct call outside of the normal declared details form.
  683. # We only want to save values in the global properties for content that
  684. # honours the hierarchical details mechanism so that projects are not
  685. # robbed of the ability to override details set in nested projects.
  686. return()
  687. endif()
  688. # No details provided, so assume they were saved from an earlier call
  689. # to FetchContent_Declare(). Do a check that we haven't already
  690. # populated this content before in case the caller forgot to check.
  691. FetchContent_GetProperties(${contentName})
  692. if(${contentNameLower}_POPULATED)
  693. message(FATAL_ERROR "Content ${contentName} already populated in ${${contentNameLower}_SOURCE_DIR}")
  694. endif()
  695. string(TOUPPER ${contentName} contentNameUpper)
  696. set(FETCHCONTENT_SOURCE_DIR_${contentNameUpper}
  697. "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}"
  698. CACHE PATH "When not empty, overrides where to find pre-populated content for ${contentName}")
  699. if(FETCHCONTENT_SOURCE_DIR_${contentNameUpper})
  700. # The source directory has been explicitly provided in the cache,
  701. # so no population is required
  702. set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  703. set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  704. elseif(FETCHCONTENT_FULLY_DISCONNECTED)
  705. # Bypass population and assume source is already there from a previous run
  706. set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
  707. set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  708. else()
  709. # Support both a global "disconnect all updates" and a per-content
  710. # update test (either one being set disables updates for this content).
  711. option(FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper}
  712. "Enables UPDATE_DISCONNECTED behavior just for population of ${contentName}")
  713. if(FETCHCONTENT_UPDATES_DISCONNECTED OR
  714. FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper})
  715. set(disconnectUpdates True)
  716. else()
  717. set(disconnectUpdates False)
  718. endif()
  719. if(FETCHCONTENT_QUIET)
  720. set(quietFlag QUIET)
  721. else()
  722. unset(quietFlag)
  723. endif()
  724. __FetchContent_getSavedDetails(${contentName} contentDetails)
  725. if("${contentDetails}" STREQUAL "")
  726. message(FATAL_ERROR "No details have been set for content: ${contentName}")
  727. endif()
  728. __FetchContent_directPopulate(
  729. ${contentNameLower}
  730. ${quietFlag}
  731. UPDATE_DISCONNECTED ${disconnectUpdates}
  732. SUBBUILD_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-subbuild"
  733. SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src"
  734. BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build"
  735. # Put the saved details last so they can override any of the
  736. # the options we set above (this can include SOURCE_DIR or
  737. # BUILD_DIR)
  738. ${contentDetails}
  739. )
  740. endif()
  741. __FetchContent_setPopulated(
  742. ${contentName}
  743. ${${contentNameLower}_SOURCE_DIR}
  744. ${${contentNameLower}_BINARY_DIR}
  745. )
  746. # Pass variables back to the caller. The variables passed back here
  747. # must match what FetchContent_GetProperties() sets when it is called
  748. # with just the content name.
  749. set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
  750. set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
  751. set(${contentNameLower}_POPULATED True PARENT_SCOPE)
  752. endfunction()