FetchContent.cmake 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  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 should be defined separately from the command that
  18. performs the actual population. This separation ensures that all the
  19. dependency details are defined before anything might try to use them to
  20. populate content. This is particularly important in more complex project
  21. hierarchies where dependencies may be shared between multiple projects.
  22. The following shows a typical example of declaring content details for some
  23. dependencies and then ensuring they are populated with a separate call:
  24. .. code-block:: cmake
  25. FetchContent_Declare(
  26. googletest
  27. GIT_REPOSITORY https://github.com/google/googletest.git
  28. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  29. )
  30. FetchContent_Declare(
  31. myCompanyIcons
  32. URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  33. URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
  34. )
  35. FetchContent_MakeAvailable(googletest myCompanyIcons)
  36. The :command:`FetchContent_MakeAvailable` command ensures the named
  37. dependencies have been populated, either by an earlier call or by populating
  38. them itself. When performing the population, it will also add them to the
  39. main build, if possible, so that the main build can use the populated
  40. projects' targets, etc. See the command's documentation for how these steps
  41. are performed.
  42. When using a hierarchical project arrangement, projects at higher levels in
  43. the hierarchy are able to override the declared details of content specified
  44. anywhere lower in the project hierarchy. The first details to be declared
  45. for a given dependency take precedence, regardless of where in the project
  46. hierarchy that occurs. Similarly, the first call that tries to populate a
  47. dependency "wins", with subsequent populations reusing the result of the
  48. first instead of repeating the population again.
  49. See the :ref:`Examples <fetch-content-examples>` which demonstrate
  50. this scenario.
  51. In some cases, the main project may need to have more precise control over
  52. the population, or it may be required to explicitly define the population
  53. steps in a way that cannot be captured by the declared details alone.
  54. For such situations, the lower level :command:`FetchContent_GetProperties` and
  55. :command:`FetchContent_Populate` commands can be used. These lack the richer
  56. features provided by :command:`FetchContent_MakeAvailable` though, so their
  57. direct use should be considered a last resort. The typical pattern of such
  58. custom steps looks like this:
  59. .. code-block:: cmake
  60. # NOTE: Where possible, prefer to use FetchContent_MakeAvailable()
  61. # instead of custom logic like this
  62. # Check if population has already been performed
  63. FetchContent_GetProperties(depname)
  64. if(NOT depname_POPULATED)
  65. # Fetch the content using previously declared details
  66. FetchContent_Populate(depname)
  67. # Set custom variables, policies, etc.
  68. # ...
  69. # Bring the populated content into the build
  70. add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
  71. endif()
  72. The ``FetchContent`` module also supports defining and populating
  73. content in a single call, with no check for whether the content has been
  74. populated elsewhere already. This should not be done in projects, but may
  75. be appropriate for populating content in CMake's script mode.
  76. See :command:`FetchContent_Populate` for details.
  77. Commands
  78. ^^^^^^^^
  79. .. command:: FetchContent_Declare
  80. .. code-block:: cmake
  81. FetchContent_Declare(
  82. <name>
  83. <contentOptions>...
  84. [OVERRIDE_FIND_PACKAGE |
  85. FIND_PACKAGE_ARGS args...]
  86. )
  87. The ``FetchContent_Declare()`` function records the options that describe
  88. how to populate the specified content. If such details have already
  89. been recorded earlier in this project (regardless of where in the project
  90. hierarchy), this and all later calls for the same content ``<name>`` are
  91. ignored. This "first to record, wins" approach is what allows hierarchical
  92. projects to have parent projects override content details of child projects.
  93. The content ``<name>`` can be any string without spaces, but good practice
  94. would be to use only letters, numbers and underscores. The name will be
  95. treated case-insensitively and it should be obvious for the content it
  96. represents, often being the name of the child project or the value given
  97. to its top level :command:`project` command (if it is a CMake project).
  98. For well-known public projects, the name should generally be the official
  99. name of the project. Choosing an unusual name makes it unlikely that other
  100. projects needing that same content will use the same name, leading to
  101. the content being populated multiple times.
  102. The ``<contentOptions>`` can be any of the download, update or patch options
  103. that the :command:`ExternalProject_Add` command understands. The configure,
  104. build, install and test steps are explicitly disabled and therefore options
  105. related to them will be ignored. The ``SOURCE_SUBDIR`` option is an
  106. exception, see :command:`FetchContent_MakeAvailable` for details on how that
  107. affects behavior.
  108. In most cases, ``<contentOptions>`` will just be a couple of options defining
  109. the download method and method-specific details like a commit tag or archive
  110. hash. For example:
  111. .. code-block:: cmake
  112. FetchContent_Declare(
  113. googletest
  114. GIT_REPOSITORY https://github.com/google/googletest.git
  115. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  116. )
  117. FetchContent_Declare(
  118. myCompanyIcons
  119. URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  120. URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
  121. )
  122. FetchContent_Declare(
  123. myCompanyCertificates
  124. SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs
  125. SVN_REVISION -r12345
  126. )
  127. Where contents are being fetched from a remote location and you do not
  128. control that server, it is advisable to use a hash for ``GIT_TAG`` rather
  129. than a branch or tag name. A commit hash is more secure and helps to
  130. confirm that the downloaded contents are what you expected.
  131. .. versionchanged:: 3.14
  132. Commands for the download, update or patch steps can access the terminal.
  133. This may be needed for things like password prompts or real-time display
  134. of command progress.
  135. .. versionadded:: 3.22
  136. The :variable:`CMAKE_TLS_VERIFY`, :variable:`CMAKE_TLS_CAINFO`,
  137. :variable:`CMAKE_NETRC` and :variable:`CMAKE_NETRC_FILE` variables now
  138. provide the defaults for their corresponding content options, just like
  139. they do for :command:`ExternalProject_Add`. Previously, these variables
  140. were ignored by the ``FetchContent`` module.
  141. .. versionadded:: 3.24
  142. ``FIND_PACKAGE_ARGS``
  143. This option is for scenarios where the
  144. :command:`FetchContent_MakeAvailable` command may first try a call to
  145. :command:`find_package` to satisfy the dependency for ``<name>``.
  146. By default, such a call would be simply ``find_package(<name>)``, but
  147. ``FIND_PACKAGE_ARGS`` can be used to provide additional arguments to be
  148. appended after the ``<name>``. ``FIND_PACKAGE_ARGS`` can also be given
  149. with nothing after it, which indicates that :command:`find_package` can
  150. still be called if :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` is
  151. set to ``OPT_IN`` or is not set.
  152. Everything after the ``FIND_PACKAGE_ARGS`` keyword is appended to the
  153. :command:`find_package` call, so all other ``<contentOptions>`` must
  154. come before the ``FIND_PACKAGE_ARGS`` keyword.
  155. ``OVERRIDE_FIND_PACKAGE`` cannot be used when ``FIND_PACKAGE_ARGS`` is
  156. given.
  157. ``OVERRIDE_FIND_PACKAGE``
  158. When a ``FetchContent_Declare(<name> ...)`` call includes this option,
  159. subsequent calls to ``find_package(<name> ...)`` will ensure that
  160. ``FetchContent_MakeAvailable(<name>)`` has been called, then use the
  161. config package files in the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR`
  162. directory (which are usually created by ``FetchContent_MakeAvailable()``).
  163. This effectively makes :command:`FetchContent_MakeAvailable` override
  164. :command:`find_package` for the named dependency, allowing the former to
  165. satisfy the package requirements of the latter. ``FIND_PACKAGE_ARGS``
  166. cannot be used when ``OVERRIDE_FIND_PACKAGE`` is given.
  167. .. command:: FetchContent_MakeAvailable
  168. .. versionadded:: 3.14
  169. .. code-block:: cmake
  170. FetchContent_MakeAvailable(<name1> [<name2>...])
  171. This command ensures that each of the named dependencies are made available
  172. to the project by the time it returns. There must have been a call to
  173. :command:`FetchContent_Declare` for each dependency, and the first such call
  174. will control how that dependency will be made available, as described below.
  175. .. versionadded:: 3.24
  176. If permitted, :command:`find_package(<name> [<args>...]) <find_package>`
  177. will be called, where ``<args>...`` may be provided by the
  178. ``FIND_PACKAGE_ARGS`` option in :command:`FetchContent_Declare`.
  179. The value of the :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable
  180. at the time :command:`FetchContent_Declare` was called determines whether
  181. ``FetchContent_MakeAvailable()`` can call :command:`find_package`.
  182. If :command:`find_package` was unsuccessful or was not allowed to be called,
  183. ``FetchContent_MakeAvailable()`` then uses the following logic to make the
  184. dependency available:
  185. * If the dependency has already been populated earlier in this run, set
  186. the ``<lowercaseName>_POPULATED``, ``<lowercaseName>_SOURCE_DIR`` and
  187. ``<lowercaseName>_BINARY_DIR`` variables in the same way as a call to
  188. :command:`FetchContent_GetProperties`, then skip the remaining steps
  189. below and move on to the next dependency in the list.
  190. * Call :command:`FetchContent_Populate` to populate the dependency using
  191. the details recorded by an earlier call to :command:`FetchContent_Declare`.
  192. Halt with a fatal error if no such details have been recorded.
  193. :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>` can be used to override
  194. the declared details and use content provided at the specified location
  195. instead.
  196. * .. versionadded:: 3.24
  197. Ensure the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` directory
  198. contains a ``<lowercaseName>-config.cmake`` and a
  199. ``<lowercaseName>-config-version.cmake`` file (or equivalently
  200. ``<name>Config.cmake`` and ``<name>ConfigVersion.cmake``).
  201. The directory that the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR`
  202. variable points to is cleared at the start of every CMake run.
  203. If no config file exists when :command:`FetchContent_Populate` returns,
  204. a minimal one will be written which :command:`includes <include>` any
  205. ``<lowercaseName>-extra.cmake`` or ``<name>Extra.cmake`` file with the
  206. ``OPTIONAL`` flag (so the files can be missing and won't generate a
  207. warning). Similarly, if no config version file exists, a very simple
  208. one will be written which sets ``PACKAGE_VERSION_COMPATIBLE`` to true.
  209. CMake cannot automatically determine an arbitrary dependency's version,
  210. so it cannot set ``PACKAGE_VERSION`` or ``PACKAGE_VERSION_EXACT``.
  211. When a dependency is pulled in via :command:`add_subdirectory` in the
  212. next step, it may choose to overwrite the generated config version file
  213. in :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` with one that also sets
  214. ``PACKAGE_VERSION``, and if appropriate, ``PACKAGE_VERSION_EXACT``.
  215. The dependency may also write a ``<lowercaseName>-extra.cmake`` or
  216. ``<name>Extra.cmake`` file to perform custom processing or define any
  217. variables that their normal (installed) package config file would
  218. otherwise usually define (many projects don't do any custom processing
  219. or set any variables and therefore have no need to do this).
  220. If required, the main project can write these files instead if the
  221. dependency project doesn't do so. This allows the main project to
  222. add missing details from older dependencies that haven't or can't be
  223. updated to support this functionality.
  224. See `Integrating With find_package()`_ for examples.
  225. * If the top directory of the populated content contains a ``CMakeLists.txt``
  226. file, call :command:`add_subdirectory` to add it to the main build.
  227. It is not an error for there to be no ``CMakeLists.txt`` file, which
  228. allows the command to be used for dependencies that make downloaded
  229. content available at a known location, but which do not need or support
  230. being added directly to the build.
  231. .. versionadded:: 3.18
  232. The ``SOURCE_SUBDIR`` option can be given in the declared details to
  233. look somewhere below the top directory instead (i.e. the same way that
  234. ``SOURCE_SUBDIR`` is used by the :command:`ExternalProject_Add`
  235. command). The path provided with ``SOURCE_SUBDIR`` must be relative
  236. and will be treated as relative to the top directory. It can also
  237. point to a directory that does not contain a ``CMakeLists.txt`` file
  238. or even to a directory that doesn't exist. This can be used to avoid
  239. adding a project that contains a ``CMakeLists.txt`` file in its top
  240. directory.
  241. Projects should aim to declare the details of all dependencies they might
  242. use before they call ``FetchContent_MakeAvailable()`` for any of them.
  243. This ensures that if any of the dependencies are also sub-dependencies of
  244. one or more of the others, the main project still controls the details
  245. that will be used (because it will declare them first before the
  246. dependencies get a chance to). In the following code samples, assume that
  247. the ``uses_other`` dependency also uses ``FetchContent`` to add the ``other``
  248. dependency internally:
  249. .. code-block:: cmake
  250. # WRONG: Should declare all details first
  251. FetchContent_Declare(uses_other ...)
  252. FetchContent_MakeAvailable(uses_other)
  253. FetchContent_Declare(other ...) # Will be ignored, uses_other beat us to it
  254. FetchContent_MakeAvailable(other) # Would use details declared by uses_other
  255. .. code-block:: cmake
  256. # CORRECT: All details declared first, so they will take priority
  257. FetchContent_Declare(uses_other ...)
  258. FetchContent_Declare(other ...)
  259. FetchContent_MakeAvailable(uses_other other)
  260. .. command:: FetchContent_Populate
  261. .. note::
  262. Where possible, prefer to use :command:`FetchContent_MakeAvailable`
  263. instead of implementing population manually with this command.
  264. .. code-block:: cmake
  265. FetchContent_Populate(<name>)
  266. In most cases, the only argument given to ``FetchContent_Populate()`` is the
  267. ``<name>``. When used this way, the command assumes the content details have
  268. been recorded by an earlier call to :command:`FetchContent_Declare`. The
  269. details are stored in a global property, so they are unaffected by things
  270. like variable or directory scope. Therefore, it doesn't matter where in the
  271. project the details were previously declared, as long as they have been
  272. declared before the call to ``FetchContent_Populate()``. Those saved details
  273. are then used to construct a call to :command:`ExternalProject_Add` in a
  274. private sub-build to perform the content population immediately. The
  275. implementation of ``ExternalProject_Add()`` ensures that if the content has
  276. already been populated in a previous CMake run, that content will be reused
  277. rather than repopulating them again. For the common case where population
  278. involves downloading content, the cost of the download is only paid once.
  279. An internal global property records when a particular content population
  280. request has been processed. If ``FetchContent_Populate()`` is called more
  281. than once for the same content name within a configure run, the second call
  282. will halt with an error. Projects can and should check whether content
  283. population has already been processed with the
  284. :command:`FetchContent_GetProperties` command before calling
  285. ``FetchContent_Populate()``.
  286. ``FetchContent_Populate()`` will set three variables in the scope of the
  287. caller:
  288. ``<lowercaseName>_POPULATED``
  289. This will always be set to ``TRUE`` by the call.
  290. ``<lowercaseName>_SOURCE_DIR``
  291. The location where the populated content can be found upon return.
  292. ``<lowercaseName>_BINARY_DIR``
  293. A directory intended for use as a corresponding build directory.
  294. The main use case for the ``<lowercaseName>_SOURCE_DIR`` and
  295. ``<lowercaseName>_BINARY_DIR`` variables is to call
  296. :command:`add_subdirectory` immediately after population:
  297. .. code-block:: cmake
  298. FetchContent_Populate(FooBar)
  299. add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
  300. The values of the three variables can also be retrieved from anywhere in the
  301. project hierarchy using the :command:`FetchContent_GetProperties` command.
  302. The ``FetchContent_Populate()`` command also supports a syntax allowing the
  303. content details to be specified directly rather than using any saved
  304. details. This is more low-level and use of this form is generally to be
  305. avoided in favor of using saved content details as outlined above.
  306. Nevertheless, in certain situations it can be useful to invoke the content
  307. population as an isolated operation (typically as part of implementing some
  308. other higher level feature or when using CMake in script mode):
  309. .. code-block:: cmake
  310. FetchContent_Populate(
  311. <name>
  312. [QUIET]
  313. [SUBBUILD_DIR <subBuildDir>]
  314. [SOURCE_DIR <srcDir>]
  315. [BINARY_DIR <binDir>]
  316. ...
  317. )
  318. This form has a number of key differences to that where only ``<name>`` is
  319. provided:
  320. - All required population details are assumed to have been provided directly
  321. in the call to ``FetchContent_Populate()``. Any saved details for
  322. ``<name>`` are ignored.
  323. - No check is made for whether content for ``<name>`` has already been
  324. populated.
  325. - No global property is set to record that the population has occurred.
  326. - No global properties record the source or binary directories used for the
  327. populated content.
  328. - The ``FETCHCONTENT_FULLY_DISCONNECTED`` and
  329. ``FETCHCONTENT_UPDATES_DISCONNECTED`` cache variables are ignored.
  330. The ``<lowercaseName>_SOURCE_DIR`` and ``<lowercaseName>_BINARY_DIR``
  331. variables are still returned to the caller, but since these locations are
  332. not stored as global properties when this form is used, they are only
  333. available to the calling scope and below rather than the entire project
  334. hierarchy. No ``<lowercaseName>_POPULATED`` variable is set in the caller's
  335. scope with this form.
  336. The supported options for ``FetchContent_Populate()`` are the same as those
  337. for :command:`FetchContent_Declare()`. Those few options shown just
  338. above are either specific to ``FetchContent_Populate()`` or their behavior is
  339. slightly modified from how :command:`ExternalProject_Add` treats them:
  340. ``QUIET``
  341. The ``QUIET`` option can be given to hide the output associated with
  342. populating the specified content. If the population fails, the output will
  343. be shown regardless of whether this option was given or not so that the
  344. cause of the failure can be diagnosed. The global ``FETCHCONTENT_QUIET``
  345. cache variable has no effect on ``FetchContent_Populate()`` calls where the
  346. content details are provided directly.
  347. ``SUBBUILD_DIR``
  348. The ``SUBBUILD_DIR`` argument can be provided to change the location of the
  349. sub-build created to perform the population. The default value is
  350. ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild`` and it would be
  351. unusual to need to override this default. If a relative path is specified,
  352. it will be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
  353. This option should not be confused with the ``SOURCE_SUBDIR`` option which
  354. only affects the :command:`FetchContent_MakeAvailable` command.
  355. ``SOURCE_DIR``, ``BINARY_DIR``
  356. The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments are supported by
  357. :command:`ExternalProject_Add`, but different default values are used by
  358. ``FetchContent_Populate()``. ``SOURCE_DIR`` defaults to
  359. ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src`` and ``BINARY_DIR``
  360. defaults to ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build``.
  361. If a relative path is specified, it will be interpreted as relative to
  362. :variable:`CMAKE_CURRENT_BINARY_DIR`.
  363. In addition to the above explicit options, any other unrecognized options are
  364. passed through unmodified to :command:`ExternalProject_Add` to perform the
  365. download, patch and update steps. The following options are explicitly
  366. prohibited (they are disabled by the ``FetchContent_Populate()`` command):
  367. - ``CONFIGURE_COMMAND``
  368. - ``BUILD_COMMAND``
  369. - ``INSTALL_COMMAND``
  370. - ``TEST_COMMAND``
  371. If using ``FetchContent_Populate()`` within CMake's script mode, be aware
  372. that the implementation sets up a sub-build which therefore requires a CMake
  373. generator and build tool to be available. If these cannot be found by
  374. default, then the :variable:`CMAKE_GENERATOR` and/or
  375. :variable:`CMAKE_MAKE_PROGRAM` variables will need to be set appropriately
  376. on the command line invoking the script.
  377. .. versionadded:: 3.18
  378. Added support for the ``DOWNLOAD_NO_EXTRACT`` option.
  379. .. command:: FetchContent_GetProperties
  380. When using saved content details, a call to
  381. :command:`FetchContent_MakeAvailable` or :command:`FetchContent_Populate`
  382. records information in global properties which can be queried at any time.
  383. This information includes the source and binary directories associated with
  384. the content and also whether or not the content population has been processed
  385. during the current configure run.
  386. .. code-block:: cmake
  387. FetchContent_GetProperties(
  388. <name>
  389. [SOURCE_DIR <srcDirVar>]
  390. [BINARY_DIR <binDirVar>]
  391. [POPULATED <doneVar>]
  392. )
  393. The ``SOURCE_DIR``, ``BINARY_DIR`` and ``POPULATED`` options can be used to
  394. specify which properties should be retrieved. Each option accepts a value
  395. which is the name of the variable in which to store that property. Most of
  396. the time though, only ``<name>`` is given, in which case the call will then
  397. set the same variables as a call to
  398. :command:`FetchContent_MakeAvailable(name) <FetchContent_MakeAvailable>` or
  399. :command:`FetchContent_Populate(name) <FetchContent_Populate>`.
  400. This command is rarely needed when using
  401. :command:`FetchContent_MakeAvailable`. It is more commonly used as part of
  402. implementing the following pattern with :command:`FetchContent_Populate`,
  403. which ensures that the relevant variables will always be defined regardless
  404. of whether or not the population has been performed elsewhere in the project
  405. already:
  406. .. code-block:: cmake
  407. # Check if population has already been performed
  408. FetchContent_GetProperties(depname)
  409. if(NOT depname_POPULATED)
  410. # Fetch the content using previously declared details
  411. FetchContent_Populate(depname)
  412. # Set custom variables, policies, etc.
  413. # ...
  414. # Bring the populated content into the build
  415. add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
  416. endif()
  417. Variables
  418. ^^^^^^^^^
  419. A number of cache variables can influence the behavior where details from a
  420. :command:`FetchContent_Declare` call are used to populate content.
  421. .. note::
  422. All of these variables are intended for the developer to customize behavior.
  423. They should not normally be set by the project.
  424. .. variable:: FETCHCONTENT_BASE_DIR
  425. In most cases, the saved details do not specify any options relating to the
  426. directories to use for the internal sub-build, final source and build areas.
  427. It is generally best to leave these decisions up to the ``FetchContent``
  428. module to handle on the project's behalf. The ``FETCHCONTENT_BASE_DIR``
  429. cache variable controls the point under which all content population
  430. directories are collected, but in most cases, developers would not need to
  431. change this. The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
  432. developers change this value, they should aim to keep the path short and
  433. just below the top level of the build tree to avoid running into path
  434. length problems on Windows.
  435. .. variable:: FETCHCONTENT_QUIET
  436. The logging output during population can be quite verbose, making the
  437. configure stage quite noisy. This cache option (``ON`` by default) hides
  438. all population output unless an error is encountered. If experiencing
  439. problems with hung downloads, temporarily switching this option off may
  440. help diagnose which content population is causing the issue.
  441. .. variable:: FETCHCONTENT_FULLY_DISCONNECTED
  442. When this option is enabled, no attempt is made to download or update
  443. any content. It is assumed that all content has already been populated in
  444. a previous run or the source directories have been pointed at existing
  445. contents the developer has provided manually (using options described
  446. further below). When the developer knows that no changes have been made to
  447. any content details, turning this option ``ON`` can significantly speed up
  448. the configure stage. It is ``OFF`` by default.
  449. .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED
  450. This is a less severe download/update control compared to
  451. :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. Instead of bypassing all
  452. download and update logic, ``FETCHCONTENT_UPDATES_DISCONNECTED`` only
  453. disables the update stage. Therefore, if content has not been downloaded
  454. previously, it will still be downloaded when this option is enabled.
  455. This can speed up the configure stage, but not as much as
  456. :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. It is ``OFF`` by default.
  457. .. variable:: FETCHCONTENT_TRY_FIND_PACKAGE_MODE
  458. .. versionadded:: 3.24
  459. This variable modifies the details that :command:`FetchContent_Declare`
  460. records for a given dependency. While it ultimately controls the behavior
  461. of :command:`FetchContent_MakeAvailable`, it is the variable's value when
  462. :command:`FetchContent_Declare` is called that gets used. It makes no
  463. difference what the variable is set to when
  464. :command:`FetchContent_MakeAvailable` is called. Since the variable should
  465. only be set by the user and not by projects directly, it will typically have
  466. the same value throughout anyway, so this distinction is not usually
  467. noticeable.
  468. ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` ultimately controls whether
  469. :command:`FetchContent_MakeAvailable` is allowed to call
  470. :command:`find_package` to satisfy a dependency. The variable can be set
  471. to one of the following values:
  472. ``OPT_IN``
  473. :command:`FetchContent_MakeAvailable` will only call
  474. :command:`find_package` if the :command:`FetchContent_Declare` call
  475. included a ``FIND_PACKAGE_ARGS`` keyword. This is also the default
  476. behavior if ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` is not set.
  477. ``ALWAYS``
  478. :command:`find_package` will be called by
  479. :command:`FetchContent_MakeAvailable` regardless of whether the
  480. :command:`FetchContent_Declare` call included a ``FIND_PACKAGE_ARGS``
  481. keyword or not. If no ``FIND_PACKAGE_ARGS`` keyword was given, the
  482. behavior will be as though ``FIND_PACKAGE_ARGS`` had been provided,
  483. with no additional arguments after it.
  484. ``NEVER``
  485. :command:`FetchContent_MakeAvailable` will not call
  486. :command:`find_package`. Any ``FIND_PACKAGE_ARGS`` given to the
  487. :command:`FetchContent_Declare` call will be ignored.
  488. As a special case, if the :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>`
  489. variable has a non-empty value for a dependency, it is assumed that the
  490. user is overriding all other methods of making that dependency available.
  491. ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` will have no effect on that
  492. dependency and :command:`FetchContent_MakeAvailable` will not try to call
  493. :command:`find_package` for it.
  494. In addition to the above, the following variables are also defined for each
  495. content name:
  496. .. variable:: FETCHCONTENT_SOURCE_DIR_<uppercaseName>
  497. If this is set, no download or update steps are performed for the specified
  498. content and the ``<lowercaseName>_SOURCE_DIR`` variable returned to the
  499. caller is pointed at this location. This gives developers a way to have a
  500. separate checkout of the content that they can modify freely without
  501. interference from the build. The build simply uses that existing source,
  502. but it still defines ``<lowercaseName>_BINARY_DIR`` to point inside its own
  503. build area. Developers are strongly encouraged to use this mechanism rather
  504. than editing the sources populated in the default location, as changes to
  505. sources in the default location can be lost when content population details
  506. are changed by the project.
  507. .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED_<uppercaseName>
  508. This is the per-content equivalent of
  509. :variable:`FETCHCONTENT_UPDATES_DISCONNECTED`. If the global option or
  510. this option is ``ON``, then updates will be disabled for the named content.
  511. Disabling updates for individual content can be useful for content whose
  512. details rarely change, while still leaving other frequently changing content
  513. with updates enabled.
  514. .. _`fetch-content-examples`:
  515. Examples
  516. ^^^^^^^^
  517. Typical Case
  518. """"""""""""
  519. This first fairly straightforward example ensures that some popular testing
  520. frameworks are available to the main build:
  521. .. code-block:: cmake
  522. include(FetchContent)
  523. FetchContent_Declare(
  524. googletest
  525. GIT_REPOSITORY https://github.com/google/googletest.git
  526. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  527. )
  528. FetchContent_Declare(
  529. Catch2
  530. GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  531. GIT_TAG de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
  532. )
  533. # After the following call, the CMake targets defined by googletest and
  534. # Catch2 will be available to the rest of the build
  535. FetchContent_MakeAvailable(googletest Catch2)
  536. .. _FetchContent-find_package-integration:
  537. Integrating With find_package()
  538. """""""""""""""""""""""""""""""
  539. For the previous example, if the user wanted to try to find ``googletest``
  540. and ``Catch2`` via :command:`find_package` first before trying to download
  541. and build them from source, they could set the
  542. :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable to ``ALWAYS``.
  543. This would also affect any other calls to :command:`FetchContent_Declare`
  544. throughout the project, which might not be acceptable. The behavior can be
  545. enabled for just these two dependencies instead by adding ``FIND_PACKAGE_ARGS``
  546. to the declared details and leaving
  547. :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` unset, or set to ``OPT_IN``:
  548. .. code-block:: cmake
  549. include(FetchContent)
  550. FetchContent_Declare(
  551. googletest
  552. GIT_REPOSITORY https://github.com/google/googletest.git
  553. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  554. FIND_PACKAGE_ARGS NAMES gtest
  555. )
  556. FetchContent_Declare(
  557. Catch2
  558. GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  559. GIT_TAG de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
  560. FIND_PACKAGE_ARGS
  561. )
  562. # This will try calling find_package() first for both dependencies
  563. FetchContent_MakeAvailable(googletest Catch2)
  564. For ``Catch2``, no additional arguments to :command:`find_package` are needed,
  565. so no additional arguments are provided after the ``FIND_PACKAGE_ARGS``
  566. keyword. For ``googletest``, its package is more commonly called ``gtest``,
  567. so arguments are added to support it being found by that name.
  568. If the user wanted to disable :command:`FetchContent_MakeAvailable` from
  569. calling :command:`find_package` for any dependency, even if it provided
  570. ``FIND_PACKAGE_ARGS`` in its declared details, they could set
  571. :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` to ``NEVER``.
  572. If the project wanted to indicate that these two dependencies should be
  573. downloaded and built from source and that :command:`find_package` calls
  574. should be redirected to use the built dependencies, the
  575. ``OVERRIDE_FIND_PACKAGE`` option should be used when declaring the content
  576. details:
  577. .. code-block:: cmake
  578. include(FetchContent)
  579. FetchContent_Declare(
  580. googletest
  581. GIT_REPOSITORY https://github.com/google/googletest.git
  582. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  583. OVERRIDE_FIND_PACKAGE
  584. )
  585. FetchContent_Declare(
  586. Catch2
  587. GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  588. GIT_TAG de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
  589. OVERRIDE_FIND_PACKAGE
  590. )
  591. # The following will automatically forward through to FetchContent_MakeAvailable()
  592. find_package(googletest)
  593. find_package(Catch2)
  594. CMake provides a FindGTest module which defines some variables that older
  595. projects may use instead of linking to the imported targets. To support
  596. those cases, we can provide an extras file. In keeping with the
  597. "first to define, wins" philosophy of ``FetchContent``, we only write out
  598. that file if something else hasn't already done so.
  599. .. code-block:: cmake
  600. FetchContent_MakeAvailable(googletest)
  601. if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extras.cmake AND
  602. NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestExtras.cmake)
  603. file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extras.cmake
  604. [=[
  605. if("${GTEST_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest)
  606. set(GTEST_LIBRARIES GTest::gtest)
  607. endif()
  608. if("${GTEST_MAIN_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest_main)
  609. set(GTEST_MAIN_LIBRARIES GTest::gtest_main)
  610. endif()
  611. if("${GTEST_BOTH_LIBRARIES}" STREQUAL "")
  612. set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
  613. endif()
  614. ]=]
  615. endif()
  616. Projects will also likely be using ``find_package(GTest)`` rather than
  617. ``find_package(googletest)``, but it is possible to make use of the
  618. :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` area to pull in the latter as
  619. a dependency of the former. This is likely to be sufficient to satisfy
  620. a typical ``find_package(GTest)`` call.
  621. .. code-block:: cmake
  622. FetchContent_MakeAvailable(googletest)
  623. if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake AND
  624. NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfig.cmake)
  625. file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake
  626. [=[
  627. include(CMakeFindDependencyMacro)
  628. find_dependency(googletest)
  629. ]=]
  630. endif()
  631. if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake AND
  632. NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfigVersion.cmake)
  633. file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake
  634. [=[
  635. include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-config-version.cmake OPTIONAL)
  636. if(NOT PACKAGE_VERSION_COMPATIBLE)
  637. include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestConfigVersion.cmake OPTIONAL)
  638. endif()
  639. ]=]
  640. endif()
  641. Overriding Where To Find CMakeLists.txt
  642. """""""""""""""""""""""""""""""""""""""
  643. If the sub-project's ``CMakeLists.txt`` file is not at the top level of its
  644. source tree, the ``SOURCE_SUBDIR`` option can be used to tell ``FetchContent``
  645. where to find it. The following example shows how to use that option and
  646. it also sets a variable which is meaningful to the subproject before pulling
  647. it into the main build:
  648. .. code-block:: cmake
  649. include(FetchContent)
  650. FetchContent_Declare(
  651. protobuf
  652. GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
  653. GIT_TAG ae50d9b9902526efd6c7a1907d09739f959c6297 # v3.15.0
  654. SOURCE_SUBDIR cmake
  655. )
  656. set(protobuf_BUILD_TESTS OFF)
  657. FetchContent_MakeAvailable(protobuf)
  658. Complex Dependency Hierarchies
  659. """"""""""""""""""""""""""""""
  660. In more complex project hierarchies, the dependency relationships can be more
  661. complicated. Consider a hierarchy where ``projA`` is the top level project and
  662. it depends directly on projects ``projB`` and ``projC``. Both ``projB`` and
  663. ``projC`` can be built standalone and they also both depend on another project
  664. ``projD``. ``projB`` additionally depends on ``projE``. This example assumes
  665. that all five projects are available on a company git server. The
  666. ``CMakeLists.txt`` of each project might have sections like the following:
  667. *projA*:
  668. .. code-block:: cmake
  669. include(FetchContent)
  670. FetchContent_Declare(
  671. projB
  672. GIT_REPOSITORY [email protected]:git/projB.git
  673. GIT_TAG 4a89dc7e24ff212a7b5167bef7ab079d
  674. )
  675. FetchContent_Declare(
  676. projC
  677. GIT_REPOSITORY [email protected]:git/projC.git
  678. GIT_TAG 4ad4016bd1d8d5412d135cf8ceea1bb9
  679. )
  680. FetchContent_Declare(
  681. projD
  682. GIT_REPOSITORY [email protected]:git/projD.git
  683. GIT_TAG origin/integrationBranch
  684. )
  685. FetchContent_Declare(
  686. projE
  687. GIT_REPOSITORY [email protected]:git/projE.git
  688. GIT_TAG v2.3-rc1
  689. )
  690. # Order is important, see notes in the discussion further below
  691. FetchContent_MakeAvailable(projD projB projC)
  692. *projB*:
  693. .. code-block:: cmake
  694. include(FetchContent)
  695. FetchContent_Declare(
  696. projD
  697. GIT_REPOSITORY [email protected]:git/projD.git
  698. GIT_TAG 20b415f9034bbd2a2e8216e9a5c9e632
  699. )
  700. FetchContent_Declare(
  701. projE
  702. GIT_REPOSITORY [email protected]:git/projE.git
  703. GIT_TAG 68e20f674a48be38d60e129f600faf7d
  704. )
  705. FetchContent_MakeAvailable(projD projE)
  706. *projC*:
  707. .. code-block:: cmake
  708. include(FetchContent)
  709. FetchContent_Declare(
  710. projD
  711. GIT_REPOSITORY [email protected]:git/projD.git
  712. GIT_TAG 7d9a17ad2c962aa13e2fbb8043fb6b8a
  713. )
  714. # This particular version of projD requires workarounds
  715. FetchContent_GetProperties(projD)
  716. if(NOT projd_POPULATED)
  717. FetchContent_Populate(projD)
  718. # Copy an additional/replacement file into the populated source
  719. file(COPY someFile.c DESTINATION ${projd_SOURCE_DIR}/src)
  720. add_subdirectory(${projd_SOURCE_DIR} ${projd_BINARY_DIR})
  721. endif()
  722. A few key points should be noted in the above:
  723. - ``projB`` and ``projC`` define different content details for ``projD``,
  724. but ``projA`` also defines a set of content details for ``projD``.
  725. Because ``projA`` will define them first, the details from ``projB`` and
  726. ``projC`` will not be used. The override details defined by ``projA``
  727. are not required to match either of those from ``projB`` or ``projC``, but
  728. it is up to the higher level project to ensure that the details it does
  729. define still make sense for the child projects.
  730. - In the ``projA`` call to :command:`FetchContent_MakeAvailable`, ``projD``
  731. is listed ahead of ``projB`` and ``projC`` to ensure that ``projA`` is in
  732. control of how ``projD`` is populated.
  733. - While ``projA`` defines content details for ``projE``, it does not need
  734. to explicitly call ``FetchContent_MakeAvailable(projE)`` or
  735. ``FetchContent_Populate(projD)`` itself. Instead, it leaves that to the
  736. child ``projB``. For higher level projects, it is often enough to just
  737. define the override content details and leave the actual population to the
  738. child projects. This saves repeating the same thing at each level of the
  739. project hierarchy unnecessarily.
  740. Populating Content Without Adding It To The Build
  741. """""""""""""""""""""""""""""""""""""""""""""""""
  742. Projects don't always need to add the populated content to the build.
  743. Sometimes the project just wants to make the downloaded content available at
  744. a predictable location. The next example ensures that a set of standard
  745. company toolchain files (and potentially even the toolchain binaries
  746. themselves) is available early enough to be used for that same build.
  747. .. code-block:: cmake
  748. cmake_minimum_required(VERSION 3.14)
  749. include(FetchContent)
  750. FetchContent_Declare(
  751. mycom_toolchains
  752. URL https://intranet.mycompany.com//toolchains_1.3.2.tar.gz
  753. )
  754. FetchContent_MakeAvailable(mycom_toolchains)
  755. project(CrossCompileExample)
  756. The project could be configured to use one of the downloaded toolchains like
  757. so:
  758. .. code-block:: shell
  759. cmake -DCMAKE_TOOLCHAIN_FILE=_deps/mycom_toolchains-src/toolchain_arm.cmake /path/to/src
  760. When CMake processes the ``CMakeLists.txt`` file, it will download and unpack
  761. the tarball into ``_deps/mycompany_toolchains-src`` relative to the build
  762. directory. The :variable:`CMAKE_TOOLCHAIN_FILE` variable is not used until
  763. the :command:`project` command is reached, at which point CMake looks for the
  764. named toolchain file relative to the build directory. Because the tarball has
  765. already been downloaded and unpacked by then, the toolchain file will be in
  766. place, even the very first time that ``cmake`` is run in the build directory.
  767. Populating Content In CMake Script Mode
  768. """""""""""""""""""""""""""""""""""""""
  769. This last example demonstrates how one might download and unpack a
  770. firmware tarball using CMake's :manual:`script mode <cmake(1)>`. The call to
  771. :command:`FetchContent_Populate` specifies all the content details and the
  772. unpacked firmware will be placed in a ``firmware`` directory below the
  773. current working directory.
  774. *getFirmware.cmake*:
  775. .. code-block:: cmake
  776. # NOTE: Intended to be run in script mode with cmake -P
  777. include(FetchContent)
  778. FetchContent_Populate(
  779. firmware
  780. URL https://mycompany.com/assets/firmware-1.23-arm.tar.gz
  781. URL_HASH MD5=68247684da89b608d466253762b0ff11
  782. SOURCE_DIR firmware
  783. )
  784. #]=======================================================================]
  785. #=======================================================================
  786. # Recording and retrieving content details for later population
  787. #=======================================================================
  788. # Internal use, projects must not call this directly. It is
  789. # intended for use by FetchContent_Declare() only.
  790. #
  791. # Sets a content-specific global property (not meant for use
  792. # outside of functions defined here in this file) which can later
  793. # be retrieved using __FetchContent_getSavedDetails() with just the
  794. # same content name. If there is already a value stored in the
  795. # property, it is left unchanged and this call has no effect.
  796. # This allows parent projects to define the content details,
  797. # overriding anything a child project may try to set (properties
  798. # are not cached between runs, so the first thing to set it in a
  799. # build will be in control).
  800. function(__FetchContent_declareDetails contentName)
  801. string(TOLOWER ${contentName} contentNameLower)
  802. set(savedDetailsPropertyName "_FetchContent_${contentNameLower}_savedDetails")
  803. get_property(alreadyDefined GLOBAL PROPERTY ${savedDetailsPropertyName} DEFINED)
  804. if(alreadyDefined)
  805. return()
  806. endif()
  807. if("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "ALWAYS")
  808. set(__tryFindPackage TRUE)
  809. set(__tryFindPackageAllowed TRUE)
  810. elseif("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "NEVER")
  811. set(__tryFindPackage FALSE)
  812. set(__tryFindPackageAllowed FALSE)
  813. elseif("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "OPT_IN" OR
  814. NOT DEFINED FETCHCONTENT_TRY_FIND_PACKAGE_MODE)
  815. set(__tryFindPackage FALSE)
  816. set(__tryFindPackageAllowed TRUE)
  817. else()
  818. message(FATAL_ERROR
  819. "Unsupported value for FETCHCONTENT_TRY_FIND_PACKAGE_MODE: "
  820. "${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}"
  821. )
  822. endif()
  823. set(__cmdArgs)
  824. set(__findPackageArgs)
  825. foreach(__item IN LISTS ARGN)
  826. if(DEFINED __findPackageArgs)
  827. # All remaining args are for find_package()
  828. string(APPEND __findPackageArgs " [==[${__item}]==]")
  829. continue()
  830. endif()
  831. # Still processing non-find_package() args
  832. if(__item STREQUAL "FIND_PACKAGE_ARGS")
  833. if(__tryFindPackageAllowed)
  834. set(__tryFindPackage TRUE)
  835. endif()
  836. # All arguments after this keyword are for find_package(). Define the
  837. # variable but with an empty value initially. This allows us to check
  838. # at the start of the loop whether to store remaining items in this
  839. # variable or not. Note that there could be no more args, which is still
  840. # a valid case because we automatically provide ${contentName} as the
  841. # package name and there may not need to be any further arguments.
  842. set(__findPackageArgs "")
  843. continue() # Don't store this item
  844. elseif(__item STREQUAL "OVERRIDE_FIND_PACKAGE")
  845. set(__tryFindPackageAllowed FALSE)
  846. # Define a separate dedicated property for find_package() to check
  847. # in its implementation. This will be a placeholder until FetchContent
  848. # actually does the population. After that, we will have created a
  849. # stand-in config file that find_package() will pick up instead.
  850. set(propertyName "_FetchContent_${contentNameLower}_override_find_package")
  851. define_property(GLOBAL PROPERTY ${propertyName})
  852. set_property(GLOBAL PROPERTY ${propertyName} TRUE)
  853. endif()
  854. string(APPEND __cmdArgs " [==[${__item}]==]")
  855. endforeach()
  856. define_property(GLOBAL PROPERTY ${savedDetailsPropertyName})
  857. cmake_language(EVAL CODE
  858. "set_property(GLOBAL PROPERTY ${savedDetailsPropertyName} ${__cmdArgs})"
  859. )
  860. if(__tryFindPackage AND __tryFindPackageAllowed)
  861. set(propertyName "_FetchContent_${contentNameLower}_find_package_args")
  862. define_property(GLOBAL PROPERTY ${propertyName})
  863. if(NOT QUIET IN_LIST __findPackageArgs)
  864. list(INSERT __findPackageArgs 0 QUIET)
  865. endif()
  866. cmake_language(EVAL CODE
  867. "set_property(GLOBAL PROPERTY ${propertyName} ${__findPackageArgs})"
  868. )
  869. endif()
  870. endfunction()
  871. # Internal use, projects must not call this directly. It is
  872. # intended for use by the FetchContent_Declare() function.
  873. #
  874. # Retrieves details saved for the specified content in an
  875. # earlier call to __FetchContent_declareDetails().
  876. function(__FetchContent_getSavedDetails contentName outVar)
  877. string(TOLOWER ${contentName} contentNameLower)
  878. set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
  879. get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
  880. if(NOT alreadyDefined)
  881. message(FATAL_ERROR "No content details recorded for ${contentName}")
  882. endif()
  883. get_property(propertyValue GLOBAL PROPERTY ${propertyName})
  884. set(${outVar} "${propertyValue}" PARENT_SCOPE)
  885. endfunction()
  886. # Saves population details of the content, sets defaults for the
  887. # SOURCE_DIR and BUILD_DIR.
  888. function(FetchContent_Declare contentName)
  889. # Always check this even if we won't save these details.
  890. # This helps projects catch errors earlier.
  891. if("OVERRIDE_FIND_PACKAGE" IN_LIST ARGN AND "FIND_PACKAGE_ARGS" IN_LIST ARGN)
  892. message(FATAL_ERROR
  893. "Cannot specify both OVERRIDE_FIND_PACKAGE and FIND_PACKAGE_ARGS "
  894. "when declaring details for ${contentName}"
  895. )
  896. endif()
  897. set(options "")
  898. set(oneValueArgs SVN_REPOSITORY)
  899. set(multiValueArgs "")
  900. cmake_parse_arguments(PARSE_ARGV 1 ARG
  901. "${options}" "${oneValueArgs}" "${multiValueArgs}")
  902. unset(srcDirSuffix)
  903. unset(svnRepoArgs)
  904. if(ARG_SVN_REPOSITORY)
  905. # Add a hash of the svn repository URL to the source dir. This works
  906. # around the problem where if the URL changes, the download would
  907. # fail because it tries to checkout/update rather than switch the
  908. # old URL to the new one. We limit the hash to the first 7 characters
  909. # so that the source path doesn't get overly long (which can be a
  910. # problem on windows due to path length limits).
  911. string(SHA1 urlSHA ${ARG_SVN_REPOSITORY})
  912. string(SUBSTRING ${urlSHA} 0 7 urlSHA)
  913. set(srcDirSuffix "-${urlSHA}")
  914. set(svnRepoArgs SVN_REPOSITORY ${ARG_SVN_REPOSITORY})
  915. endif()
  916. string(TOLOWER ${contentName} contentNameLower)
  917. set(__argsQuoted)
  918. foreach(__item IN LISTS ARG_UNPARSED_ARGUMENTS)
  919. string(APPEND __argsQuoted " [==[${__item}]==]")
  920. endforeach()
  921. cmake_language(EVAL CODE "
  922. __FetchContent_declareDetails(
  923. ${contentNameLower}
  924. SOURCE_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src${srcDirSuffix}\"
  925. BINARY_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build\"
  926. \${svnRepoArgs}
  927. # List these last so they can override things we set above
  928. ${__argsQuoted}
  929. )"
  930. )
  931. endfunction()
  932. #=======================================================================
  933. # Set/get whether the specified content has been populated yet.
  934. # The setter also records the source and binary dirs used.
  935. #=======================================================================
  936. # Internal use, projects must not call this directly. It is intended
  937. # for use by things like the FetchContent_Populate() function to
  938. # record when FetchContent_Populate() is called for a particular
  939. # content name.
  940. function(__FetchContent_setPopulated contentName)
  941. cmake_parse_arguments(PARSE_ARGV 1 arg
  942. ""
  943. "SOURCE_DIR;BINARY_DIR"
  944. ""
  945. )
  946. if(NOT "${arg_UNPARSED_ARGUMENTS}" STREQUAL "")
  947. message(FATAL_ERROR "Unsupported arguments: ${arg_UNPARSED_ARGUMENTS}")
  948. endif()
  949. string(TOLOWER ${contentName} contentNameLower)
  950. set(prefix "_FetchContent_${contentNameLower}")
  951. set(propertyName "${prefix}_sourceDir")
  952. define_property(GLOBAL PROPERTY ${propertyName})
  953. if("${arg_SOURCE_DIR}" STREQUAL "")
  954. # Don't discard a previously provided SOURCE_DIR
  955. get_property(arg_SOURCE_DIR GLOBAL PROPERTY ${propertyName})
  956. endif()
  957. set_property(GLOBAL PROPERTY ${propertyName} "${arg_SOURCE_DIR}")
  958. set(propertyName "${prefix}_binaryDir")
  959. define_property(GLOBAL PROPERTY ${propertyName})
  960. if("${arg_BINARY_DIR}" STREQUAL "")
  961. # Don't discard a previously provided BINARY_DIR
  962. get_property(arg_BINARY_DIR GLOBAL PROPERTY ${propertyName})
  963. endif()
  964. set_property(GLOBAL PROPERTY ${propertyName} "${arg_BINARY_DIR}")
  965. set(propertyName "${prefix}_populated")
  966. define_property(GLOBAL PROPERTY ${propertyName})
  967. set_property(GLOBAL PROPERTY ${propertyName} TRUE)
  968. endfunction()
  969. # Set variables in the calling scope for any of the retrievable
  970. # properties. If no specific properties are requested, variables
  971. # will be set for all retrievable properties.
  972. #
  973. # This function is intended to also be used by projects as the canonical
  974. # way to detect whether they should call FetchContent_Populate()
  975. # and pull the populated source into the build with add_subdirectory(),
  976. # if they are using the populated content in that way.
  977. function(FetchContent_GetProperties contentName)
  978. string(TOLOWER ${contentName} contentNameLower)
  979. set(options "")
  980. set(oneValueArgs SOURCE_DIR BINARY_DIR POPULATED)
  981. set(multiValueArgs "")
  982. cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  983. if(NOT ARG_SOURCE_DIR AND
  984. NOT ARG_BINARY_DIR AND
  985. NOT ARG_POPULATED)
  986. # No specific properties requested, provide them all
  987. set(ARG_SOURCE_DIR ${contentNameLower}_SOURCE_DIR)
  988. set(ARG_BINARY_DIR ${contentNameLower}_BINARY_DIR)
  989. set(ARG_POPULATED ${contentNameLower}_POPULATED)
  990. endif()
  991. set(prefix "_FetchContent_${contentNameLower}")
  992. if(ARG_SOURCE_DIR)
  993. set(propertyName "${prefix}_sourceDir")
  994. get_property(value GLOBAL PROPERTY ${propertyName})
  995. if(value)
  996. set(${ARG_SOURCE_DIR} ${value} PARENT_SCOPE)
  997. endif()
  998. endif()
  999. if(ARG_BINARY_DIR)
  1000. set(propertyName "${prefix}_binaryDir")
  1001. get_property(value GLOBAL PROPERTY ${propertyName})
  1002. if(value)
  1003. set(${ARG_BINARY_DIR} ${value} PARENT_SCOPE)
  1004. endif()
  1005. endif()
  1006. if(ARG_POPULATED)
  1007. set(propertyName "${prefix}_populated")
  1008. get_property(value GLOBAL PROPERTY ${propertyName} DEFINED)
  1009. set(${ARG_POPULATED} ${value} PARENT_SCOPE)
  1010. endif()
  1011. endfunction()
  1012. #=======================================================================
  1013. # Performing the population
  1014. #=======================================================================
  1015. # The value of contentName will always have been lowercased by the caller.
  1016. # All other arguments are assumed to be options that are understood by
  1017. # ExternalProject_Add(), except for QUIET and SUBBUILD_DIR.
  1018. function(__FetchContent_directPopulate contentName)
  1019. set(options
  1020. QUIET
  1021. )
  1022. set(oneValueArgs
  1023. SUBBUILD_DIR
  1024. SOURCE_DIR
  1025. BINARY_DIR
  1026. # We need special processing if DOWNLOAD_NO_EXTRACT is true
  1027. DOWNLOAD_NO_EXTRACT
  1028. # Prevent the following from being passed through
  1029. CONFIGURE_COMMAND
  1030. BUILD_COMMAND
  1031. INSTALL_COMMAND
  1032. TEST_COMMAND
  1033. # We force these to be ON since we are always executing serially
  1034. # and we want all steps to have access to the terminal in case they
  1035. # need input from the command line (e.g. ask for a private key password)
  1036. # or they want to provide timely progress. We silently absorb and
  1037. # discard these if they are set by the caller.
  1038. USES_TERMINAL_DOWNLOAD
  1039. USES_TERMINAL_UPDATE
  1040. USES_TERMINAL_PATCH
  1041. )
  1042. set(multiValueArgs "")
  1043. cmake_parse_arguments(PARSE_ARGV 1 ARG
  1044. "${options}" "${oneValueArgs}" "${multiValueArgs}")
  1045. if(NOT ARG_SUBBUILD_DIR)
  1046. message(FATAL_ERROR "Internal error: SUBBUILD_DIR not set")
  1047. elseif(NOT IS_ABSOLUTE "${ARG_SUBBUILD_DIR}")
  1048. set(ARG_SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SUBBUILD_DIR}")
  1049. endif()
  1050. if(NOT ARG_SOURCE_DIR)
  1051. message(FATAL_ERROR "Internal error: SOURCE_DIR not set")
  1052. elseif(NOT IS_ABSOLUTE "${ARG_SOURCE_DIR}")
  1053. set(ARG_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SOURCE_DIR}")
  1054. endif()
  1055. if(NOT ARG_BINARY_DIR)
  1056. message(FATAL_ERROR "Internal error: BINARY_DIR not set")
  1057. elseif(NOT IS_ABSOLUTE "${ARG_BINARY_DIR}")
  1058. set(ARG_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_BINARY_DIR}")
  1059. endif()
  1060. # Ensure the caller can know where to find the source and build directories
  1061. # with some convenient variables. Doing this here ensures the caller sees
  1062. # the correct result in the case where the default values are overridden by
  1063. # the content details set by the project.
  1064. set(${contentName}_SOURCE_DIR "${ARG_SOURCE_DIR}" PARENT_SCOPE)
  1065. set(${contentName}_BINARY_DIR "${ARG_BINARY_DIR}" PARENT_SCOPE)
  1066. # The unparsed arguments may contain spaces, so build up ARG_EXTRA
  1067. # in such a way that it correctly substitutes into the generated
  1068. # CMakeLists.txt file with each argument quoted.
  1069. unset(ARG_EXTRA)
  1070. foreach(arg IN LISTS ARG_UNPARSED_ARGUMENTS)
  1071. set(ARG_EXTRA "${ARG_EXTRA} \"${arg}\"")
  1072. endforeach()
  1073. if(ARG_DOWNLOAD_NO_EXTRACT)
  1074. set(ARG_EXTRA "${ARG_EXTRA} DOWNLOAD_NO_EXTRACT YES")
  1075. set(__FETCHCONTENT_COPY_FILE
  1076. "
  1077. ExternalProject_Get_Property(${contentName}-populate DOWNLOADED_FILE)
  1078. get_filename_component(dlFileName \"\${DOWNLOADED_FILE}\" NAME)
  1079. ExternalProject_Add_Step(${contentName}-populate copyfile
  1080. COMMAND \"${CMAKE_COMMAND}\" -E copy_if_different
  1081. \"<DOWNLOADED_FILE>\" \"${ARG_SOURCE_DIR}\"
  1082. DEPENDEES patch
  1083. DEPENDERS configure
  1084. BYPRODUCTS \"${ARG_SOURCE_DIR}/\${dlFileName}\"
  1085. COMMENT \"Copying file to SOURCE_DIR\"
  1086. )
  1087. ")
  1088. else()
  1089. unset(__FETCHCONTENT_COPY_FILE)
  1090. endif()
  1091. # Hide output if requested, but save it to a variable in case there's an
  1092. # error so we can show the output upon failure. When not quiet, don't
  1093. # capture the output to a variable because the user may want to see the
  1094. # output as it happens (e.g. progress during long downloads). Combine both
  1095. # stdout and stderr in the one capture variable so the output stays in order.
  1096. if (ARG_QUIET)
  1097. set(outputOptions
  1098. OUTPUT_VARIABLE capturedOutput
  1099. ERROR_VARIABLE capturedOutput
  1100. )
  1101. else()
  1102. set(capturedOutput)
  1103. set(outputOptions)
  1104. message(STATUS "Populating ${contentName}")
  1105. endif()
  1106. if(CMAKE_GENERATOR)
  1107. set(subCMakeOpts "-G${CMAKE_GENERATOR}")
  1108. if(CMAKE_GENERATOR_PLATFORM)
  1109. list(APPEND subCMakeOpts "-A${CMAKE_GENERATOR_PLATFORM}")
  1110. endif()
  1111. if(CMAKE_GENERATOR_TOOLSET)
  1112. list(APPEND subCMakeOpts "-T${CMAKE_GENERATOR_TOOLSET}")
  1113. endif()
  1114. if(CMAKE_MAKE_PROGRAM)
  1115. list(APPEND subCMakeOpts "-DCMAKE_MAKE_PROGRAM:FILEPATH=${CMAKE_MAKE_PROGRAM}")
  1116. endif()
  1117. # Override the sub-build's configuration types for multi-config generators.
  1118. # This ensures we are not affected by any custom setting from the project
  1119. # and can always request a known configuration further below.
  1120. get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
  1121. if(is_multi_config)
  1122. list(APPEND subCMakeOpts "-DCMAKE_CONFIGURATION_TYPES:STRING=Release")
  1123. endif()
  1124. else()
  1125. # Likely we've been invoked via CMake's script mode where no
  1126. # generator is set (and hence CMAKE_MAKE_PROGRAM could not be
  1127. # trusted even if provided). We will have to rely on being
  1128. # able to find the default generator and build tool.
  1129. unset(subCMakeOpts)
  1130. endif()
  1131. set(__FETCHCONTENT_CACHED_INFO "")
  1132. set(__passthrough_vars
  1133. CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY
  1134. CMAKE_TLS_VERIFY
  1135. CMAKE_TLS_CAINFO
  1136. CMAKE_NETRC
  1137. CMAKE_NETRC_FILE
  1138. )
  1139. foreach(var IN LISTS __passthrough_vars)
  1140. if(DEFINED ${var})
  1141. # Embed directly in the generated CMakeLists.txt file to avoid making
  1142. # the cmake command line excessively long. It also makes debugging and
  1143. # testing easier.
  1144. string(APPEND __FETCHCONTENT_CACHED_INFO "set(${var} [==[${${var}}]==])\n")
  1145. endif()
  1146. endforeach()
  1147. # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
  1148. list(FIND ARG_UNPARSED_ARGUMENTS GIT_REPOSITORY indexResult)
  1149. if(indexResult GREATER_EQUAL 0)
  1150. find_package(Git QUIET)
  1151. string(APPEND __FETCHCONTENT_CACHED_INFO "
  1152. # Pass through things we've already detected in the main project to avoid
  1153. # paying the cost of redetecting them again in ExternalProject_Add()
  1154. set(GIT_EXECUTABLE [==[${GIT_EXECUTABLE}]==])
  1155. set(GIT_VERSION_STRING [==[${GIT_VERSION_STRING}]==])
  1156. set_property(GLOBAL PROPERTY _CMAKE_FindGit_GIT_EXECUTABLE_VERSION
  1157. [==[${GIT_EXECUTABLE};${GIT_VERSION_STRING}]==]
  1158. )
  1159. ")
  1160. endif()
  1161. # Create and build a separate CMake project to carry out the population.
  1162. # If we've already previously done these steps, they will not cause
  1163. # anything to be updated, so extra rebuilds of the project won't occur.
  1164. # Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
  1165. # has this set to something not findable on the PATH. We also ensured above
  1166. # that the Release config will be defined for multi-config generators.
  1167. configure_file("${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent/CMakeLists.cmake.in"
  1168. "${ARG_SUBBUILD_DIR}/CMakeLists.txt")
  1169. execute_process(
  1170. COMMAND ${CMAKE_COMMAND} ${subCMakeOpts} .
  1171. RESULT_VARIABLE result
  1172. ${outputOptions}
  1173. WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
  1174. )
  1175. if(result)
  1176. if(capturedOutput)
  1177. message("${capturedOutput}")
  1178. endif()
  1179. message(FATAL_ERROR "CMake step for ${contentName} failed: ${result}")
  1180. endif()
  1181. execute_process(
  1182. COMMAND ${CMAKE_COMMAND} --build . --config Release
  1183. RESULT_VARIABLE result
  1184. ${outputOptions}
  1185. WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
  1186. )
  1187. if(result)
  1188. if(capturedOutput)
  1189. message("${capturedOutput}")
  1190. endif()
  1191. message(FATAL_ERROR "Build step for ${contentName} failed: ${result}")
  1192. endif()
  1193. endfunction()
  1194. option(FETCHCONTENT_FULLY_DISCONNECTED "Disables all attempts to download or update content and assumes source dirs already exist")
  1195. option(FETCHCONTENT_UPDATES_DISCONNECTED "Enables UPDATE_DISCONNECTED behavior for all content population")
  1196. option(FETCHCONTENT_QUIET "Enables QUIET option for all content population" ON)
  1197. set(FETCHCONTENT_BASE_DIR "${CMAKE_BINARY_DIR}/_deps" CACHE PATH "Directory under which to collect all populated content")
  1198. # Populate the specified content using details stored from
  1199. # an earlier call to FetchContent_Declare().
  1200. function(FetchContent_Populate contentName)
  1201. if(NOT contentName)
  1202. message(FATAL_ERROR "Empty contentName not allowed for FetchContent_Populate()")
  1203. endif()
  1204. string(TOLOWER ${contentName} contentNameLower)
  1205. if(ARGN)
  1206. # This is the direct population form with details fully specified
  1207. # as part of the call, so we already have everything we need
  1208. __FetchContent_directPopulate(
  1209. ${contentNameLower}
  1210. SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-subbuild"
  1211. SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-src"
  1212. BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-build"
  1213. ${ARGN} # Could override any of the above ..._DIR variables
  1214. )
  1215. # Pass source and binary dir variables back to the caller
  1216. set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
  1217. set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
  1218. # Don't set global properties, or record that we did this population, since
  1219. # this was a direct call outside of the normal declared details form.
  1220. # We only want to save values in the global properties for content that
  1221. # honors the hierarchical details mechanism so that projects are not
  1222. # robbed of the ability to override details set in nested projects.
  1223. return()
  1224. endif()
  1225. # No details provided, so assume they were saved from an earlier call
  1226. # to FetchContent_Declare(). Do a check that we haven't already
  1227. # populated this content before in case the caller forgot to check.
  1228. FetchContent_GetProperties(${contentName})
  1229. if(${contentNameLower}_POPULATED)
  1230. if("${${contentNameLower}_SOURCE_DIR}" STREQUAL "")
  1231. message(FATAL_ERROR
  1232. "Content ${contentName} already populated by find_package()"
  1233. )
  1234. else()
  1235. message(FATAL_ERROR
  1236. "Content ${contentName} already populated in ${${contentNameLower}_SOURCE_DIR}"
  1237. )
  1238. endif()
  1239. endif()
  1240. __FetchContent_getSavedDetails(${contentName} contentDetails)
  1241. if("${contentDetails}" STREQUAL "")
  1242. message(FATAL_ERROR "No details have been set for content: ${contentName}")
  1243. endif()
  1244. string(TOUPPER ${contentName} contentNameUpper)
  1245. set(FETCHCONTENT_SOURCE_DIR_${contentNameUpper}
  1246. "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}"
  1247. CACHE PATH "When not empty, overrides where to find pre-populated content for ${contentName}")
  1248. if(FETCHCONTENT_SOURCE_DIR_${contentNameUpper})
  1249. # The source directory has been explicitly provided in the cache,
  1250. # so no population is required. The build directory may still be specified
  1251. # by the declared details though.
  1252. if(NOT IS_ABSOLUTE "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1253. # Don't check this directory because we don't know what location it is
  1254. # expected to be relative to. We can't make this a hard error for backward
  1255. # compatibility reasons.
  1256. message(WARNING "Relative source directory specified. This is not safe, "
  1257. "as it depends on the calling directory scope.\n"
  1258. " FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1259. elseif(NOT EXISTS "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1260. message(FATAL_ERROR "Manually specified source directory is missing:\n"
  1261. " FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1262. endif()
  1263. set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1264. cmake_parse_arguments(savedDetails "" "BINARY_DIR" "" ${contentDetails})
  1265. if(savedDetails_BINARY_DIR)
  1266. set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
  1267. else()
  1268. set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  1269. endif()
  1270. elseif(FETCHCONTENT_FULLY_DISCONNECTED)
  1271. # Bypass population and assume source is already there from a previous run.
  1272. # Declared details may override the default source or build directories.
  1273. cmake_parse_arguments(savedDetails "" "SOURCE_DIR;BINARY_DIR" "" ${contentDetails})
  1274. if(savedDetails_SOURCE_DIR)
  1275. set(${contentNameLower}_SOURCE_DIR ${savedDetails_SOURCE_DIR})
  1276. else()
  1277. set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
  1278. endif()
  1279. if(savedDetails_BINARY_DIR)
  1280. set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
  1281. else()
  1282. set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  1283. endif()
  1284. else()
  1285. # Support both a global "disconnect all updates" and a per-content
  1286. # update test (either one being set disables updates for this content).
  1287. option(FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper}
  1288. "Enables UPDATE_DISCONNECTED behavior just for population of ${contentName}")
  1289. if(FETCHCONTENT_UPDATES_DISCONNECTED OR
  1290. FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper})
  1291. set(disconnectUpdates True)
  1292. else()
  1293. set(disconnectUpdates False)
  1294. endif()
  1295. if(FETCHCONTENT_QUIET)
  1296. set(quietFlag QUIET)
  1297. else()
  1298. unset(quietFlag)
  1299. endif()
  1300. set(__detailsQuoted)
  1301. foreach(__item IN LISTS contentDetails)
  1302. if(NOT __item STREQUAL "OVERRIDE_FIND_PACKAGE")
  1303. string(APPEND __detailsQuoted " [==[${__item}]==]")
  1304. endif()
  1305. endforeach()
  1306. cmake_language(EVAL CODE "
  1307. __FetchContent_directPopulate(
  1308. ${contentNameLower}
  1309. ${quietFlag}
  1310. UPDATE_DISCONNECTED ${disconnectUpdates}
  1311. SUBBUILD_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-subbuild\"
  1312. SOURCE_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src\"
  1313. BINARY_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build\"
  1314. # Put the saved details last so they can override any of the
  1315. # the options we set above (this can include SOURCE_DIR or
  1316. # BUILD_DIR)
  1317. ${__detailsQuoted}
  1318. )"
  1319. )
  1320. endif()
  1321. __FetchContent_setPopulated(
  1322. ${contentName}
  1323. SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}"
  1324. BINARY_DIR "${${contentNameLower}_BINARY_DIR}"
  1325. )
  1326. # Pass variables back to the caller. The variables passed back here
  1327. # must match what FetchContent_GetProperties() sets when it is called
  1328. # with just the content name.
  1329. set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
  1330. set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
  1331. set(${contentNameLower}_POPULATED True PARENT_SCOPE)
  1332. endfunction()
  1333. function(__FetchContent_setupFindPackageRedirection contentName)
  1334. __FetchContent_getSavedDetails(${contentName} contentDetails)
  1335. string(TOLOWER ${contentName} contentNameLower)
  1336. get_property(wantFindPackage GLOBAL PROPERTY
  1337. _FetchContent_${contentNameLower}_find_package_args
  1338. DEFINED
  1339. )
  1340. if(NOT wantFindPackage AND NOT OVERRIDE_FIND_PACKAGE IN_LIST contentDetails)
  1341. # No find_package() redirection allowed
  1342. return()
  1343. endif()
  1344. # We write out dep-config.cmake and dep-config-version.cmake file name
  1345. # forms here because they are forced to lowercase. FetchContent
  1346. # dependency names are case-insensitive, but find_package() config files
  1347. # are only case-insensitive for the -config and -config-version forms,
  1348. # not the Config and ConfigVersion forms.
  1349. set(inFileDir ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent)
  1350. set(configFilePrefix1 "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${contentName}Config")
  1351. set(configFilePrefix2 "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${contentNameLower}-config")
  1352. if(NOT EXISTS "${configFilePrefix1}.cmake" AND
  1353. NOT EXISTS "${configFilePrefix2}.cmake")
  1354. configure_file(${inFileDir}/package-config.cmake.in
  1355. "${configFilePrefix2}.cmake" @ONLY
  1356. )
  1357. endif()
  1358. if(NOT EXISTS "${configFilePrefix1}Version.cmake" AND
  1359. NOT EXISTS "${configFilePrefix2}-version.cmake")
  1360. configure_file(${inFileDir}/package-config-version.cmake.in
  1361. "${configFilePrefix2}-version.cmake" @ONLY
  1362. )
  1363. endif()
  1364. # Now that we've created the redirected package config files, prevent
  1365. # find_package() from delegating to FetchContent and let it find these
  1366. # config files through its normal processing.
  1367. set(propertyName "${prefix}_override_find_package")
  1368. set(GLOBAL PROPERTY ${propertyName} FALSE)
  1369. set(${contentName}_DIR "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}"
  1370. CACHE INTERNAL "Redirected by FetchContent"
  1371. )
  1372. endfunction()
  1373. # Arguments are assumed to be the names of dependencies that have been
  1374. # declared previously and should be populated. It is not an error if
  1375. # any of them have already been populated (they will just be skipped in
  1376. # that case). The command is implemented as a macro so that the variables
  1377. # defined by the FetchContent_GetProperties() and FetchContent_Populate()
  1378. # calls will be available to the caller.
  1379. macro(FetchContent_MakeAvailable)
  1380. foreach(__cmake_contentName IN ITEMS ${ARGV})
  1381. string(TOLOWER ${__cmake_contentName} __cmake_contentNameLower)
  1382. # If user specified FETCHCONTENT_SOURCE_DIR_... for this dependency, that
  1383. # overrides everything else and we shouldn't try to use find_package().
  1384. string(TOUPPER ${__cmake_contentName} __cmake_contentNameUpper)
  1385. if("${FETCHCONTENT_SOURCE_DIR_${__cmake_contentNameUpper}}" STREQUAL "")
  1386. # Check if we've been asked to try find_package() first, even if we
  1387. # have already populated this dependency. If we previously tried to
  1388. # use find_package() for this and it succeeded, those things might
  1389. # no longer be in scope, so we have to do it again.
  1390. get_property(__cmake_haveFpArgs GLOBAL PROPERTY
  1391. _FetchContent_${__cmake_contentNameLower}_find_package_args DEFINED
  1392. )
  1393. if(__cmake_haveFpArgs)
  1394. unset(__cmake_haveFpArgs)
  1395. message(VERBOSE "Trying find_package(${__cmake_contentName} ...) before FetchContent")
  1396. get_property(__cmake_fpArgs GLOBAL PROPERTY
  1397. _FetchContent_${__cmake_contentNameLower}_find_package_args
  1398. )
  1399. # This call could lead to FetchContent_MakeAvailable() being called for
  1400. # a nested dependency and it may occur in the current variable scope.
  1401. # We have to save/restore the variables we need to preserve.
  1402. list(APPEND __cmake_fcCurrentNameStack
  1403. ${__cmake_contentName}
  1404. ${__cmake_contentNameLower}
  1405. )
  1406. find_package(${__cmake_contentName} ${__cmake_fpArgs})
  1407. list(POP_BACK __cmake_fcCurrentNameStack
  1408. __cmake_contentNameLower
  1409. __cmake_contentName
  1410. )
  1411. unset(__cmake_fpArgs)
  1412. if(${__cmake_contentName}_FOUND)
  1413. __FetchContent_setPopulated(${__cmake_contentName})
  1414. FetchContent_GetProperties(${__cmake_contentName})
  1415. continue()
  1416. endif()
  1417. endif()
  1418. else()
  1419. unset(__cmake_haveFpArgs)
  1420. endif()
  1421. FetchContent_GetProperties(${__cmake_contentName})
  1422. if(NOT ${__cmake_contentNameLower}_POPULATED)
  1423. FetchContent_Populate(${__cmake_contentName})
  1424. __FetchContent_setupFindPackageRedirection(${__cmake_contentName})
  1425. # Only try to call add_subdirectory() if the populated content
  1426. # can be treated that way. Protecting the call with the check
  1427. # allows this function to be used for projects that just want
  1428. # to ensure the content exists, such as to provide content at
  1429. # a known location. We check the saved details for an optional
  1430. # SOURCE_SUBDIR which can be used in the same way as its meaning
  1431. # for ExternalProject. It won't matter if it was passed through
  1432. # to the ExternalProject sub-build, since it would have been
  1433. # ignored there.
  1434. set(__cmake_srcdir "${${__cmake_contentNameLower}_SOURCE_DIR}")
  1435. __FetchContent_getSavedDetails(${__cmake_contentName} __cmake_contentDetails)
  1436. if("${__cmake_contentDetails}" STREQUAL "")
  1437. message(FATAL_ERROR "No details have been set for content: ${__cmake_contentName}")
  1438. endif()
  1439. cmake_parse_arguments(__cmake_arg "" "SOURCE_SUBDIR" "" ${__cmake_contentDetails})
  1440. if(NOT "${__cmake_arg_SOURCE_SUBDIR}" STREQUAL "")
  1441. string(APPEND __cmake_srcdir "/${__cmake_arg_SOURCE_SUBDIR}")
  1442. endif()
  1443. if(EXISTS ${__cmake_srcdir}/CMakeLists.txt)
  1444. add_subdirectory(${__cmake_srcdir} ${${__cmake_contentNameLower}_BINARY_DIR})
  1445. endif()
  1446. unset(__cmake_srcdir)
  1447. unset(__cmake_contentDetails)
  1448. unset(__cmake_arg_SOURCE_SUBDIR)
  1449. endif()
  1450. endforeach()
  1451. # clear local variables to prevent leaking into the caller's scope
  1452. unset(__cmake_contentName)
  1453. unset(__cmake_contentNameLower)
  1454. unset(__cmake_contentNameUpper)
  1455. endmacro()