Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Modules / FetchContent.cmake
1 # Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2 # file Copyright.txt or https://cmake.org/licensing for details.
3
4 #[=======================================================================[.rst:
5 FetchContent
6 ------------------
7
8 .. versionadded:: 3.11
9
10 .. only:: html
11
12   .. contents::
13
14 .. note:: The :guide:`Using Dependencies Guide` provides a high-level
15   introduction to this general topic. It provides a broader overview of
16   where the ``FetchContent`` module fits into the bigger picture,
17   including its relationship to the :command:`find_package` command.
18   The guide is recommended pre-reading before moving on to the details below.
19
20 Overview
21 ^^^^^^^^
22
23 This module enables populating content at configure time via any method
24 supported by the :module:`ExternalProject` module.  Whereas
25 :command:`ExternalProject_Add` downloads at build time, the
26 ``FetchContent`` module makes content available immediately, allowing the
27 configure step to use the content in commands like :command:`add_subdirectory`,
28 :command:`include` or :command:`file` operations.
29
30 Content population details should be defined separately from the command that
31 performs the actual population.  This separation ensures that all the
32 dependency details are defined before anything might try to use them to
33 populate content.  This is particularly important in more complex project
34 hierarchies where dependencies may be shared between multiple projects.
35
36 The following shows a typical example of declaring content details for some
37 dependencies and then ensuring they are populated with a separate call:
38
39 .. code-block:: cmake
40
41   FetchContent_Declare(
42     googletest
43     GIT_REPOSITORY https://github.com/google/googletest.git
44     GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
45   )
46   FetchContent_Declare(
47     myCompanyIcons
48     URL      https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
49     URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
50   )
51
52   FetchContent_MakeAvailable(googletest myCompanyIcons)
53
54 The :command:`FetchContent_MakeAvailable` command ensures the named
55 dependencies have been populated, either by an earlier call or by populating
56 them itself.  When performing the population, it will also add them to the
57 main build, if possible, so that the main build can use the populated
58 projects' targets, etc.  See the command's documentation for how these steps
59 are performed.
60
61 When using a hierarchical project arrangement, projects at higher levels in
62 the hierarchy are able to override the declared details of content specified
63 anywhere lower in the project hierarchy.  The first details to be declared
64 for a given dependency take precedence, regardless of where in the project
65 hierarchy that occurs.  Similarly, the first call that tries to populate a
66 dependency "wins", with subsequent populations reusing the result of the
67 first instead of repeating the population again.
68 See the :ref:`Examples <fetch-content-examples>` which demonstrate
69 this scenario.
70
71 In some cases, the main project may need to have more precise control over
72 the population, or it may be required to explicitly define the population
73 steps in a way that cannot be captured by the declared details alone.
74 For such situations, the lower level :command:`FetchContent_GetProperties` and
75 :command:`FetchContent_Populate` commands can be used.  These lack the richer
76 features provided by :command:`FetchContent_MakeAvailable` though, so their
77 direct use should be considered a last resort.  The typical pattern of such
78 custom steps looks like this:
79
80 .. code-block:: cmake
81
82   # NOTE: Where possible, prefer to use FetchContent_MakeAvailable()
83   #       instead of custom logic like this
84
85   # Check if population has already been performed
86   FetchContent_GetProperties(depname)
87   if(NOT depname_POPULATED)
88     # Fetch the content using previously declared details
89     FetchContent_Populate(depname)
90
91     # Set custom variables, policies, etc.
92     # ...
93
94     # Bring the populated content into the build
95     add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
96   endif()
97
98 The ``FetchContent`` module also supports defining and populating
99 content in a single call, with no check for whether the content has been
100 populated elsewhere already.  This should not be done in projects, but may
101 be appropriate for populating content in CMake's script mode.
102 See :command:`FetchContent_Populate` for details.
103
104 Commands
105 ^^^^^^^^
106
107 .. command:: FetchContent_Declare
108
109   .. code-block:: cmake
110
111     FetchContent_Declare(
112       <name>
113       <contentOptions>...
114       [SYSTEM]
115       [OVERRIDE_FIND_PACKAGE |
116        FIND_PACKAGE_ARGS args...]
117     )
118
119   The ``FetchContent_Declare()`` function records the options that describe
120   how to populate the specified content.  If such details have already
121   been recorded earlier in this project (regardless of where in the project
122   hierarchy), this and all later calls for the same content ``<name>`` are
123   ignored.  This "first to record, wins" approach is what allows hierarchical
124   projects to have parent projects override content details of child projects.
125
126   The content ``<name>`` can be any string without spaces, but good practice
127   would be to use only letters, numbers and underscores.  The name will be
128   treated case-insensitively and it should be obvious for the content it
129   represents, often being the name of the child project or the value given
130   to its top level :command:`project` command (if it is a CMake project).
131   For well-known public projects, the name should generally be the official
132   name of the project.  Choosing an unusual name makes it unlikely that other
133   projects needing that same content will use the same name, leading to
134   the content being populated multiple times.
135
136   The ``<contentOptions>`` can be any of the download, update or patch options
137   that the :command:`ExternalProject_Add` command understands.  The configure,
138   build, install and test steps are explicitly disabled and therefore options
139   related to them will be ignored.  The ``SOURCE_SUBDIR`` option is an
140   exception, see :command:`FetchContent_MakeAvailable` for details on how that
141   affects behavior.
142
143   In most cases, ``<contentOptions>`` will just be a couple of options defining
144   the download method and method-specific details like a commit tag or archive
145   hash.  For example:
146
147   .. code-block:: cmake
148
149     FetchContent_Declare(
150       googletest
151       GIT_REPOSITORY https://github.com/google/googletest.git
152       GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
153     )
154
155     FetchContent_Declare(
156       myCompanyIcons
157       URL      https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
158       URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
159     )
160
161     FetchContent_Declare(
162       myCompanyCertificates
163       SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs
164       SVN_REVISION   -r12345
165     )
166
167   Where contents are being fetched from a remote location and you do not
168   control that server, it is advisable to use a hash for ``GIT_TAG`` rather
169   than a branch or tag name.  A commit hash is more secure and helps to
170   confirm that the downloaded contents are what you expected.
171
172   .. versionchanged:: 3.14
173     Commands for the download, update or patch steps can access the terminal.
174     This may be needed for things like password prompts or real-time display
175     of command progress.
176
177   .. versionadded:: 3.22
178     The :variable:`CMAKE_TLS_VERIFY`, :variable:`CMAKE_TLS_CAINFO`,
179     :variable:`CMAKE_NETRC` and :variable:`CMAKE_NETRC_FILE` variables now
180     provide the defaults for their corresponding content options, just like
181     they do for :command:`ExternalProject_Add`. Previously, these variables
182     were ignored by the ``FetchContent`` module.
183
184   .. versionadded:: 3.24
185
186     ``FIND_PACKAGE_ARGS``
187       This option is for scenarios where the
188       :command:`FetchContent_MakeAvailable` command may first try a call to
189       :command:`find_package` to satisfy the dependency for ``<name>``.
190       By default, such a call would be simply ``find_package(<name>)``, but
191       ``FIND_PACKAGE_ARGS`` can be used to provide additional arguments to be
192       appended after the ``<name>``.  ``FIND_PACKAGE_ARGS`` can also be given
193       with nothing after it, which indicates that :command:`find_package` can
194       still be called if :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` is
195       set to ``OPT_IN`` or is not set.
196
197       Everything after the ``FIND_PACKAGE_ARGS`` keyword is appended to the
198       :command:`find_package` call, so all other ``<contentOptions>`` must
199       come before the ``FIND_PACKAGE_ARGS`` keyword.  If the
200       :variable:`CMAKE_FIND_PACKAGE_TARGETS_GLOBAL` variable is set to true
201       at the time ``FetchContent_Declare()`` is called, a ``GLOBAL`` keyword
202       will be appended to the :command:`find_package` arguments if it was
203       not already specified.  It will also be appended if
204       ``FIND_PACKAGE_ARGS`` was not given, but
205       :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` was set to ``ALWAYS``.
206
207       ``OVERRIDE_FIND_PACKAGE`` cannot be used when ``FIND_PACKAGE_ARGS`` is
208       given.
209
210       :ref:`dependency_providers` discusses another way that
211       :command:`FetchContent_MakeAvailable` calls can be redirected.
212       ``FIND_PACKAGE_ARGS`` is intended for project control, whereas
213       dependency providers allow users to override project behavior.
214
215     ``OVERRIDE_FIND_PACKAGE``
216       When a ``FetchContent_Declare(<name> ...)`` call includes this option,
217       subsequent calls to ``find_package(<name> ...)`` will ensure that
218       ``FetchContent_MakeAvailable(<name>)`` has been called, then use the
219       config package files in the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR`
220       directory (which are usually created by ``FetchContent_MakeAvailable()``).
221       This effectively makes :command:`FetchContent_MakeAvailable` override
222       :command:`find_package` for the named dependency, allowing the former to
223       satisfy the package requirements of the latter.  ``FIND_PACKAGE_ARGS``
224       cannot be used when ``OVERRIDE_FIND_PACKAGE`` is given.
225
226       If a :ref:`dependency provider <dependency_providers>` has been set
227       and the project calls :command:`find_package` for the ``<name>``
228       dependency, ``OVERRIDE_FIND_PACKAGE`` will not prevent the provider
229       from seeing that call.  Dependency providers always have the opportunity
230       to intercept any direct call to :command:`find_package`, except if that
231       call contains the ``BYPASS_PROVIDER`` option.
232
233   .. versionadded:: 3.25
234
235     ``SYSTEM``
236       If the ``SYSTEM`` argument is provided, targets created by
237       the dependency will have their :prop_tgt:`SYSTEM` property
238       set to true when populated by :command:`FetchContent_MakeAvailable`.
239       The entries in their  :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES`
240       will be treated as ``SYSTEM`` include directories when
241       compiling consumers.
242
243 .. command:: FetchContent_MakeAvailable
244
245   .. versionadded:: 3.14
246
247   .. code-block:: cmake
248
249     FetchContent_MakeAvailable(<name1> [<name2>...])
250
251   This command ensures that each of the named dependencies are made available
252   to the project by the time it returns.  There must have been a call to
253   :command:`FetchContent_Declare` for each dependency, and the first such call
254   will control how that dependency will be made available, as described below.
255
256   If ``<lowercaseName>_SOURCE_DIR`` is not set:
257
258   * .. versionadded:: 3.24
259
260       If a :ref:`dependency provider <dependency_providers>` is set, call the
261       provider's command with ``FETCHCONTENT_MAKEAVAILABLE_SERIAL`` as the
262       first argument, followed by the arguments of the first call to
263       :command:`FetchContent_Declare` for ``<name>``.  If ``SOURCE_DIR`` or
264       ``BINARY_DIR`` were not part of the original declared arguments, they
265       will be added with their default values.
266       If :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` was set to ``NEVER``
267       when the details were declared, any ``FIND_PACKAGE_ARGS`` will be
268       omitted.  The ``OVERRIDE_FIND_PACKAGE`` keyword is also always omitted.
269       If the provider fulfilled the request, ``FetchContent_MakeAvailable()``
270       will consider that dependency handled, skip the remaining steps below
271       and move on to the next dependency in the list.
272
273   * .. versionadded:: 3.24
274
275       If permitted, :command:`find_package(<name> [<args>...]) <find_package>`
276       will be called, where ``<args>...`` may be provided by the
277       ``FIND_PACKAGE_ARGS`` option in :command:`FetchContent_Declare`.
278       The value of the :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable
279       at the time :command:`FetchContent_Declare` was called determines whether
280       ``FetchContent_MakeAvailable()`` can call :command:`find_package`.
281       If the :variable:`CMAKE_FIND_PACKAGE_TARGETS_GLOBAL` variable is set to
282       true when ``FetchContent_MakeAvailable()`` is called, it still affects
283       any imported targets created when that in turn calls
284       :command:`find_package`, even if that variable was false when the
285       corresponding details were declared.
286
287   If the dependency was not satisfied by a provider or a
288   :command:`find_package` call, ``FetchContent_MakeAvailable()`` then uses
289   the following logic to make the dependency available:
290
291   * If the dependency has already been populated earlier in this run, set
292     the ``<lowercaseName>_POPULATED``, ``<lowercaseName>_SOURCE_DIR`` and
293     ``<lowercaseName>_BINARY_DIR`` variables in the same way as a call to
294     :command:`FetchContent_GetProperties`, then skip the remaining steps
295     below and move on to the next dependency in the list.
296
297   * Call :command:`FetchContent_Populate` to populate the dependency using
298     the details recorded by an earlier call to :command:`FetchContent_Declare`.
299     Halt with a fatal error if no such details have been recorded.
300     :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>` can be used to override
301     the declared details and use content provided at the specified location
302     instead.
303
304   * .. versionadded:: 3.24
305
306       Ensure the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` directory
307       contains a ``<lowercaseName>-config.cmake`` and a
308       ``<lowercaseName>-config-version.cmake`` file (or equivalently
309       ``<name>Config.cmake`` and ``<name>ConfigVersion.cmake``).
310       The directory that the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR`
311       variable points to is cleared at the start of every CMake run.
312       If no config file exists when :command:`FetchContent_Populate` returns,
313       a minimal one will be written which :command:`includes <include>` any
314       ``<lowercaseName>-extra.cmake`` or ``<name>Extra.cmake`` file with the
315       ``OPTIONAL`` flag (so the files can be missing and won't generate a
316       warning).  Similarly, if no config version file exists, a very simple
317       one will be written which sets ``PACKAGE_VERSION_COMPATIBLE`` and
318       ``PACKAGE_VERSION_EXACT`` to true.  This ensures all future calls to
319       :command:`find_package()` for the dependency will use the redirected
320       config file, regardless of any version requirements.
321       CMake cannot automatically determine an arbitrary dependency's version,
322       so it cannot set ``PACKAGE_VERSION``.
323       When a dependency is pulled in via :command:`add_subdirectory` in the
324       next step, it may choose to overwrite the generated config version file
325       in :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` with one that also sets
326       ``PACKAGE_VERSION``.
327       The dependency may also write a ``<lowercaseName>-extra.cmake`` or
328       ``<name>Extra.cmake`` file to perform custom processing or define any
329       variables that their normal (installed) package config file would
330       otherwise usually define (many projects don't do any custom processing
331       or set any variables and therefore have no need to do this).
332       If required, the main project can write these files instead if the
333       dependency project doesn't do so.  This allows the main project to
334       add missing details from older dependencies that haven't or can't be
335       updated to support this functionality.
336       See `Integrating With find_package()`_ for examples.
337
338   * If the top directory of the populated content contains a ``CMakeLists.txt``
339     file, call :command:`add_subdirectory` to add it to the main build.
340     It is not an error for there to be no ``CMakeLists.txt`` file, which
341     allows the command to be used for dependencies that make downloaded
342     content available at a known location, but which do not need or support
343     being added directly to the build.
344
345     .. versionadded:: 3.18
346       The ``SOURCE_SUBDIR`` option can be given in the declared details to
347       look somewhere below the top directory instead (i.e. the same way that
348       ``SOURCE_SUBDIR`` is used by the :command:`ExternalProject_Add`
349       command).  The path provided with ``SOURCE_SUBDIR`` must be relative
350       and will be treated as relative to the top directory.  It can also
351       point to a directory that does not contain a ``CMakeLists.txt`` file
352       or even to a directory that doesn't exist.  This can be used to avoid
353       adding a project that contains a ``CMakeLists.txt`` file in its top
354       directory.
355
356   Projects should aim to declare the details of all dependencies they might
357   use before they call ``FetchContent_MakeAvailable()`` for any of them.
358   This ensures that if any of the dependencies are also sub-dependencies of
359   one or more of the others, the main project still controls the details
360   that will be used (because it will declare them first before the
361   dependencies get a chance to).  In the following code samples, assume that
362   the ``uses_other`` dependency also uses ``FetchContent`` to add the ``other``
363   dependency internally:
364
365   .. code-block:: cmake
366
367     # WRONG: Should declare all details first
368     FetchContent_Declare(uses_other ...)
369     FetchContent_MakeAvailable(uses_other)
370
371     FetchContent_Declare(other ...)    # Will be ignored, uses_other beat us to it
372     FetchContent_MakeAvailable(other)  # Would use details declared by uses_other
373
374   .. code-block:: cmake
375
376     # CORRECT: All details declared first, so they will take priority
377     FetchContent_Declare(uses_other ...)
378     FetchContent_Declare(other ...)
379     FetchContent_MakeAvailable(uses_other other)
380
381   Note that :variable:`CMAKE_VERIFY_INTERFACE_HEADER_SETS` is explicitly set
382   to false upon entry to ``FetchContent_MakeAvailable()``, and is restored to
383   its original value before the command returns.  Developers typically only
384   want to verify header sets from the main project, not those from any
385   dependencies.  This local manipulation of the
386   :variable:`CMAKE_VERIFY_INTERFACE_HEADER_SETS` variable provides that
387   intuitive behavior.  You can use variables like
388   :variable:`CMAKE_PROJECT_INCLUDE` or
389   :variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE` to turn verification back
390   on for all or some dependencies.  You can also set the
391   :prop_tgt:`VERIFY_INTERFACE_HEADER_SETS` property of individual targets.
392
393 .. command:: FetchContent_Populate
394
395   .. note::
396     Where possible, prefer to use :command:`FetchContent_MakeAvailable`
397     instead of implementing population manually with this command.
398
399   .. code-block:: cmake
400
401     FetchContent_Populate(<name>)
402
403   In most cases, the only argument given to ``FetchContent_Populate()`` is the
404   ``<name>``.  When used this way, the command assumes the content details have
405   been recorded by an earlier call to :command:`FetchContent_Declare`.  The
406   details are stored in a global property, so they are unaffected by things
407   like variable or directory scope.  Therefore, it doesn't matter where in the
408   project the details were previously declared, as long as they have been
409   declared before the call to ``FetchContent_Populate()``.  Those saved details
410   are then used to construct a call to :command:`ExternalProject_Add` in a
411   private sub-build to perform the content population immediately.  The
412   implementation of ``ExternalProject_Add()`` ensures that if the content has
413   already been populated in a previous CMake run, that content will be reused
414   rather than repopulating them again.  For the common case where population
415   involves downloading content, the cost of the download is only paid once.
416
417   An internal global property records when a particular content population
418   request has been processed.  If ``FetchContent_Populate()`` is called more
419   than once for the same content name within a configure run, the second call
420   will halt with an error.  Projects can and should check whether content
421   population has already been processed with the
422   :command:`FetchContent_GetProperties` command before calling
423   ``FetchContent_Populate()``.
424
425   ``FetchContent_Populate()`` will set three variables in the scope of the
426   caller:
427
428   ``<lowercaseName>_POPULATED``
429     This will always be set to ``TRUE`` by the call.
430
431   ``<lowercaseName>_SOURCE_DIR``
432     The location where the populated content can be found upon return.
433
434   ``<lowercaseName>_BINARY_DIR``
435     A directory intended for use as a corresponding build directory.
436
437   The main use case for the ``<lowercaseName>_SOURCE_DIR`` and
438   ``<lowercaseName>_BINARY_DIR`` variables is to call
439   :command:`add_subdirectory` immediately after population:
440
441   .. code-block:: cmake
442
443     FetchContent_Populate(FooBar)
444     add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
445
446   The values of the three variables can also be retrieved from anywhere in the
447   project hierarchy using the :command:`FetchContent_GetProperties` command.
448
449   The ``FetchContent_Populate()`` command also supports a syntax allowing the
450   content details to be specified directly rather than using any saved
451   details.  This is more low-level and use of this form is generally to be
452   avoided in favor of using saved content details as outlined above.
453   Nevertheless, in certain situations it can be useful to invoke the content
454   population as an isolated operation (typically as part of implementing some
455   other higher level feature or when using CMake in script mode):
456
457   .. code-block:: cmake
458
459     FetchContent_Populate(
460       <name>
461       [QUIET]
462       [SUBBUILD_DIR <subBuildDir>]
463       [SOURCE_DIR <srcDir>]
464       [BINARY_DIR <binDir>]
465       ...
466     )
467
468   This form has a number of key differences to that where only ``<name>`` is
469   provided:
470
471   - All required population details are assumed to have been provided directly
472     in the call to ``FetchContent_Populate()``. Any saved details for
473     ``<name>`` are ignored.
474   - No check is made for whether content for ``<name>`` has already been
475     populated.
476   - No global property is set to record that the population has occurred.
477   - No global properties record the source or binary directories used for the
478     populated content.
479   - The ``FETCHCONTENT_FULLY_DISCONNECTED`` and
480     ``FETCHCONTENT_UPDATES_DISCONNECTED`` cache variables are ignored.
481
482   The ``<lowercaseName>_SOURCE_DIR`` and ``<lowercaseName>_BINARY_DIR``
483   variables are still returned to the caller, but since these locations are
484   not stored as global properties when this form is used, they are only
485   available to the calling scope and below rather than the entire project
486   hierarchy.  No ``<lowercaseName>_POPULATED`` variable is set in the caller's
487   scope with this form.
488
489   The supported options for ``FetchContent_Populate()`` are the same as those
490   for :command:`FetchContent_Declare()`.  Those few options shown just
491   above are either specific to ``FetchContent_Populate()`` or their behavior is
492   slightly modified from how :command:`ExternalProject_Add` treats them:
493
494   ``QUIET``
495     The ``QUIET`` option can be given to hide the output associated with
496     populating the specified content.  If the population fails, the output will
497     be shown regardless of whether this option was given or not so that the
498     cause of the failure can be diagnosed.  The global ``FETCHCONTENT_QUIET``
499     cache variable has no effect on ``FetchContent_Populate()`` calls where the
500     content details are provided directly.
501
502   ``SUBBUILD_DIR``
503     The ``SUBBUILD_DIR`` argument can be provided to change the location of the
504     sub-build created to perform the population.  The default value is
505     ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild`` and it would be
506     unusual to need to override this default.  If a relative path is specified,
507     it will be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
508     This option should not be confused with the ``SOURCE_SUBDIR`` option which
509     only affects the :command:`FetchContent_MakeAvailable` command.
510
511   ``SOURCE_DIR``, ``BINARY_DIR``
512     The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments are supported by
513     :command:`ExternalProject_Add`, but different default values are used by
514     ``FetchContent_Populate()``.  ``SOURCE_DIR`` defaults to
515     ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src`` and ``BINARY_DIR``
516     defaults to ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build``.
517     If a relative path is specified, it will be interpreted as relative to
518     :variable:`CMAKE_CURRENT_BINARY_DIR`.
519
520   In addition to the above explicit options, any other unrecognized options are
521   passed through unmodified to :command:`ExternalProject_Add` to perform the
522   download, patch and update steps.  The following options are explicitly
523   prohibited (they are disabled by the ``FetchContent_Populate()`` command):
524
525   - ``CONFIGURE_COMMAND``
526   - ``BUILD_COMMAND``
527   - ``INSTALL_COMMAND``
528   - ``TEST_COMMAND``
529
530   If using ``FetchContent_Populate()`` within CMake's script mode, be aware
531   that the implementation sets up a sub-build which therefore requires a CMake
532   generator and build tool to be available. If these cannot be found by
533   default, then the :variable:`CMAKE_GENERATOR` and/or
534   :variable:`CMAKE_MAKE_PROGRAM` variables will need to be set appropriately
535   on the command line invoking the script.
536
537   .. versionadded:: 3.18
538     Added support for the ``DOWNLOAD_NO_EXTRACT`` option.
539
540 .. command:: FetchContent_GetProperties
541
542   When using saved content details, a call to
543   :command:`FetchContent_MakeAvailable` or :command:`FetchContent_Populate`
544   records information in global properties which can be queried at any time.
545   This information may include the source and binary directories associated with
546   the content and also whether or not the content population has been processed
547   during the current configure run.
548
549   .. code-block:: cmake
550
551     FetchContent_GetProperties(
552       <name>
553       [SOURCE_DIR <srcDirVar>]
554       [BINARY_DIR <binDirVar>]
555       [POPULATED <doneVar>]
556     )
557
558   The ``SOURCE_DIR``, ``BINARY_DIR`` and ``POPULATED`` options can be used to
559   specify which properties should be retrieved.  Each option accepts a value
560   which is the name of the variable in which to store that property.  Most of
561   the time though, only ``<name>`` is given, in which case the call will then
562   set the same variables as a call to
563   :command:`FetchContent_MakeAvailable(name) <FetchContent_MakeAvailable>` or
564   :command:`FetchContent_Populate(name) <FetchContent_Populate>`.
565   Note that the ``SOURCE_DIR`` and ``BINARY_DIR`` values can be empty if the
566   call is fulfilled by a :ref:`dependency provider <dependency_providers>`.
567
568   This command is rarely needed when using
569   :command:`FetchContent_MakeAvailable`.  It is more commonly used as part of
570   implementing the following pattern with :command:`FetchContent_Populate`,
571   which ensures that the relevant variables will always be defined regardless
572   of whether or not the population has been performed elsewhere in the project
573   already:
574
575   .. code-block:: cmake
576
577     # Check if population has already been performed
578     FetchContent_GetProperties(depname)
579     if(NOT depname_POPULATED)
580       # Fetch the content using previously declared details
581       FetchContent_Populate(depname)
582
583       # Set custom variables, policies, etc.
584       # ...
585
586       # Bring the populated content into the build
587       add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
588     endif()
589
590 .. command:: FetchContent_SetPopulated
591
592   .. versionadded:: 3.24
593
594   .. note::
595     This command should only be called by
596     :ref:`dependency providers <dependency_providers>`.  Calling it in any
597     other context is unsupported and future CMake versions may halt with a
598     fatal error in such cases.
599
600   .. code-block:: cmake
601
602     FetchContent_SetPopulated(
603       <name>
604       [SOURCE_DIR <srcDir>]
605       [BINARY_DIR <binDir>]
606     )
607
608   If a provider command fulfills a ``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
609   request, it must call this function before returning.  The ``SOURCE_DIR``
610   and ``BINARY_DIR`` arguments can be used to specify the values that
611   :command:`FetchContent_GetProperties` should return for its corresponding
612   arguments.  Only provide ``SOURCE_DIR`` and ``BINARY_DIR`` if they have
613   the same meaning as if they had been populated by the built-in
614   :command:`FetchContent_MakeAvailable` implementation.
615
616
617 Variables
618 ^^^^^^^^^
619
620 A number of cache variables can influence the behavior where details from a
621 :command:`FetchContent_Declare` call are used to populate content.
622
623 .. note::
624   All of these variables are intended for the developer to customize behavior.
625   They should not normally be set by the project.
626
627 .. variable:: FETCHCONTENT_BASE_DIR
628
629   In most cases, the saved details do not specify any options relating to the
630   directories to use for the internal sub-build, final source and build areas.
631   It is generally best to leave these decisions up to the ``FetchContent``
632   module to handle on the project's behalf.  The ``FETCHCONTENT_BASE_DIR``
633   cache variable controls the point under which all content population
634   directories are collected, but in most cases, developers would not need to
635   change this.  The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
636   developers change this value, they should aim to keep the path short and
637   just below the top level of the build tree to avoid running into path
638   length problems on Windows.
639
640 .. variable:: FETCHCONTENT_QUIET
641
642   The logging output during population can be quite verbose, making the
643   configure stage quite noisy.  This cache option (``ON`` by default) hides
644   all population output unless an error is encountered.  If experiencing
645   problems with hung downloads, temporarily switching this option off may
646   help diagnose which content population is causing the issue.
647
648 .. variable:: FETCHCONTENT_FULLY_DISCONNECTED
649
650   When this option is enabled, no attempt is made to download or update
651   any content.  It is assumed that all content has already been populated in
652   a previous run or the source directories have been pointed at existing
653   contents the developer has provided manually (using options described
654   further below).  When the developer knows that no changes have been made to
655   any content details, turning this option ``ON`` can significantly speed up
656   the configure stage.  It is ``OFF`` by default.
657
658 .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED
659
660   This is a less severe download/update control compared to
661   :variable:`FETCHCONTENT_FULLY_DISCONNECTED`.  Instead of bypassing all
662   download and update logic, ``FETCHCONTENT_UPDATES_DISCONNECTED`` only
663   disables the update stage.  Therefore, if content has not been downloaded
664   previously, it will still be downloaded when this option is enabled.
665   This can speed up the configure stage, but not as much as
666   :variable:`FETCHCONTENT_FULLY_DISCONNECTED`.  It is ``OFF`` by default.
667
668 .. variable:: FETCHCONTENT_TRY_FIND_PACKAGE_MODE
669
670   .. versionadded:: 3.24
671
672   This variable modifies the details that :command:`FetchContent_Declare`
673   records for a given dependency.  While it ultimately controls the behavior
674   of :command:`FetchContent_MakeAvailable`, it is the variable's value when
675   :command:`FetchContent_Declare` is called that gets used.  It makes no
676   difference what the variable is set to when
677   :command:`FetchContent_MakeAvailable` is called.  Since the variable should
678   only be set by the user and not by projects directly, it will typically have
679   the same value throughout anyway, so this distinction is not usually
680   noticeable.
681
682   ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` ultimately controls whether
683   :command:`FetchContent_MakeAvailable` is allowed to call
684   :command:`find_package` to satisfy a dependency.  The variable can be set
685   to one of the following values:
686
687   ``OPT_IN``
688     :command:`FetchContent_MakeAvailable` will only call
689     :command:`find_package` if the :command:`FetchContent_Declare` call
690     included a ``FIND_PACKAGE_ARGS`` keyword.  This is also the default
691     behavior if ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` is not set.
692
693   ``ALWAYS``
694     :command:`find_package` can be called by
695     :command:`FetchContent_MakeAvailable` regardless of whether the
696     :command:`FetchContent_Declare` call included a ``FIND_PACKAGE_ARGS``
697     keyword or not.  If no ``FIND_PACKAGE_ARGS`` keyword was given, the
698     behavior will be as though ``FIND_PACKAGE_ARGS`` had been provided,
699     with no additional arguments after it.
700
701   ``NEVER``
702     :command:`FetchContent_MakeAvailable` will not call
703     :command:`find_package`.  Any ``FIND_PACKAGE_ARGS`` given to the
704     :command:`FetchContent_Declare` call will be ignored.
705
706   As a special case, if the :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>`
707   variable has a non-empty value for a dependency, it is assumed that the
708   user is overriding all other methods of making that dependency available.
709   ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` will have no effect on that
710   dependency and :command:`FetchContent_MakeAvailable` will not try to call
711   :command:`find_package` for it.
712
713 In addition to the above, the following variables are also defined for each
714 content name:
715
716 .. variable:: FETCHCONTENT_SOURCE_DIR_<uppercaseName>
717
718   If this is set, no download or update steps are performed for the specified
719   content and the ``<lowercaseName>_SOURCE_DIR`` variable returned to the
720   caller is pointed at this location.  This gives developers a way to have a
721   separate checkout of the content that they can modify freely without
722   interference from the build.  The build simply uses that existing source,
723   but it still defines ``<lowercaseName>_BINARY_DIR`` to point inside its own
724   build area.  Developers are strongly encouraged to use this mechanism rather
725   than editing the sources populated in the default location, as changes to
726   sources in the default location can be lost when content population details
727   are changed by the project.
728
729 .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED_<uppercaseName>
730
731   This is the per-content equivalent of
732   :variable:`FETCHCONTENT_UPDATES_DISCONNECTED`.  If the global option or
733   this option is ``ON``, then updates will be disabled for the named content.
734   Disabling updates for individual content can be useful for content whose
735   details rarely change, while still leaving other frequently changing content
736   with updates enabled.
737
738 .. _`fetch-content-examples`:
739
740 Examples
741 ^^^^^^^^
742
743 Typical Case
744 """"""""""""
745
746 This first fairly straightforward example ensures that some popular testing
747 frameworks are available to the main build:
748
749 .. code-block:: cmake
750
751   include(FetchContent)
752   FetchContent_Declare(
753     googletest
754     GIT_REPOSITORY https://github.com/google/googletest.git
755     GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
756   )
757   FetchContent_Declare(
758     Catch2
759     GIT_REPOSITORY https://github.com/catchorg/Catch2.git
760     GIT_TAG        de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
761   )
762
763   # After the following call, the CMake targets defined by googletest and
764   # Catch2 will be available to the rest of the build
765   FetchContent_MakeAvailable(googletest Catch2)
766
767 .. _FetchContent-find_package-integration-examples:
768
769 Integrating With find_package()
770 """""""""""""""""""""""""""""""
771
772 For the previous example, if the user wanted to try to find ``googletest``
773 and ``Catch2`` via :command:`find_package` first before trying to download
774 and build them from source, they could set the
775 :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable to ``ALWAYS``.
776 This would also affect any other calls to :command:`FetchContent_Declare`
777 throughout the project, which might not be acceptable.  The behavior can be
778 enabled for just these two dependencies instead by adding ``FIND_PACKAGE_ARGS``
779 to the declared details and leaving
780 :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` unset, or set to ``OPT_IN``:
781
782 .. code-block:: cmake
783
784   include(FetchContent)
785   FetchContent_Declare(
786     googletest
787     GIT_REPOSITORY https://github.com/google/googletest.git
788     GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
789     FIND_PACKAGE_ARGS NAMES GTest
790   )
791   FetchContent_Declare(
792     Catch2
793     GIT_REPOSITORY https://github.com/catchorg/Catch2.git
794     GIT_TAG        de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
795     FIND_PACKAGE_ARGS
796   )
797
798   # This will try calling find_package() first for both dependencies
799   FetchContent_MakeAvailable(googletest Catch2)
800
801 For ``Catch2``, no additional arguments to :command:`find_package` are needed,
802 so no additional arguments are provided after the ``FIND_PACKAGE_ARGS``
803 keyword.  For ``googletest``, its package is more commonly called ``GTest``,
804 so arguments are added to support it being found by that name.
805
806 If the user wanted to disable :command:`FetchContent_MakeAvailable` from
807 calling :command:`find_package` for any dependency, even if it provided
808 ``FIND_PACKAGE_ARGS`` in its declared details, they could set
809 :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` to ``NEVER``.
810
811 If the project wanted to indicate that these two dependencies should be
812 downloaded and built from source and that :command:`find_package` calls
813 should be redirected to use the built dependencies, the
814 ``OVERRIDE_FIND_PACKAGE`` option should be used when declaring the content
815 details:
816
817 .. code-block:: cmake
818
819   include(FetchContent)
820   FetchContent_Declare(
821     googletest
822     GIT_REPOSITORY https://github.com/google/googletest.git
823     GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
824     OVERRIDE_FIND_PACKAGE
825   )
826   FetchContent_Declare(
827     Catch2
828     GIT_REPOSITORY https://github.com/catchorg/Catch2.git
829     GIT_TAG        de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
830     OVERRIDE_FIND_PACKAGE
831   )
832
833   # The following will automatically forward through to FetchContent_MakeAvailable()
834   find_package(googletest)
835   find_package(Catch2)
836
837 CMake provides a FindGTest module which defines some variables that older
838 projects may use instead of linking to the imported targets.  To support
839 those cases, we can provide an extra file.  In keeping with the
840 "first to define, wins" philosophy of ``FetchContent``, we only write out
841 that file if something else hasn't already done so.
842
843 .. code-block:: cmake
844
845   FetchContent_MakeAvailable(googletest)
846
847   if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake AND
848      NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestExtra.cmake)
849     file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake
850   [=[
851   if("${GTEST_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest)
852     set(GTEST_LIBRARIES GTest::gtest)
853   endif()
854   if("${GTEST_MAIN_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest_main)
855     set(GTEST_MAIN_LIBRARIES GTest::gtest_main)
856   endif()
857   if("${GTEST_BOTH_LIBRARIES}" STREQUAL "")
858     set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
859   endif()
860   ]=])
861   endif()
862
863 Projects will also likely be using ``find_package(GTest)`` rather than
864 ``find_package(googletest)``, but it is possible to make use of the
865 :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` area to pull in the latter as
866 a dependency of the former.  This is likely to be sufficient to satisfy
867 a typical ``find_package(GTest)`` call.
868
869 .. code-block:: cmake
870
871   FetchContent_MakeAvailable(googletest)
872
873   if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake AND
874      NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfig.cmake)
875     file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake
876   [=[
877   include(CMakeFindDependencyMacro)
878   find_dependency(googletest)
879   ]=])
880   endif()
881
882   if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake AND
883      NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfigVersion.cmake)
884     file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake
885   [=[
886   include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-config-version.cmake OPTIONAL)
887   if(NOT PACKAGE_VERSION_COMPATIBLE)
888     include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestConfigVersion.cmake OPTIONAL)
889   endif()
890   ]=])
891   endif()
892
893 Overriding Where To Find CMakeLists.txt
894 """""""""""""""""""""""""""""""""""""""
895
896 If the sub-project's ``CMakeLists.txt`` file is not at the top level of its
897 source tree, the ``SOURCE_SUBDIR`` option can be used to tell ``FetchContent``
898 where to find it.  The following example shows how to use that option, and
899 it also sets a variable which is meaningful to the subproject before pulling
900 it into the main build (set as an ``INTERNAL`` cache variable to avoid
901 problems with policy :policy:`CMP0077`):
902
903 .. code-block:: cmake
904
905   include(FetchContent)
906   FetchContent_Declare(
907     protobuf
908     GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
909     GIT_TAG        ae50d9b9902526efd6c7a1907d09739f959c6297 # v3.15.0
910     SOURCE_SUBDIR  cmake
911   )
912   set(protobuf_BUILD_TESTS OFF CACHE INTERNAL "")
913   FetchContent_MakeAvailable(protobuf)
914
915 Complex Dependency Hierarchies
916 """"""""""""""""""""""""""""""
917
918 In more complex project hierarchies, the dependency relationships can be more
919 complicated.  Consider a hierarchy where ``projA`` is the top level project and
920 it depends directly on projects ``projB`` and ``projC``.  Both ``projB`` and
921 ``projC`` can be built standalone and they also both depend on another project
922 ``projD``.  ``projB`` additionally depends on ``projE``.  This example assumes
923 that all five projects are available on a company git server.  The
924 ``CMakeLists.txt`` of each project might have sections like the following:
925
926 *projA*:
927
928 .. code-block:: cmake
929
930   include(FetchContent)
931   FetchContent_Declare(
932     projB
933     GIT_REPOSITORY git@mycompany.com:git/projB.git
934     GIT_TAG        4a89dc7e24ff212a7b5167bef7ab079d
935   )
936   FetchContent_Declare(
937     projC
938     GIT_REPOSITORY git@mycompany.com:git/projC.git
939     GIT_TAG        4ad4016bd1d8d5412d135cf8ceea1bb9
940   )
941   FetchContent_Declare(
942     projD
943     GIT_REPOSITORY git@mycompany.com:git/projD.git
944     GIT_TAG        origin/integrationBranch
945   )
946   FetchContent_Declare(
947     projE
948     GIT_REPOSITORY git@mycompany.com:git/projE.git
949     GIT_TAG        v2.3-rc1
950   )
951
952   # Order is important, see notes in the discussion further below
953   FetchContent_MakeAvailable(projD projB projC)
954
955 *projB*:
956
957 .. code-block:: cmake
958
959   include(FetchContent)
960   FetchContent_Declare(
961     projD
962     GIT_REPOSITORY git@mycompany.com:git/projD.git
963     GIT_TAG        20b415f9034bbd2a2e8216e9a5c9e632
964   )
965   FetchContent_Declare(
966     projE
967     GIT_REPOSITORY git@mycompany.com:git/projE.git
968     GIT_TAG        68e20f674a48be38d60e129f600faf7d
969   )
970
971   FetchContent_MakeAvailable(projD projE)
972
973 *projC*:
974
975 .. code-block:: cmake
976
977   include(FetchContent)
978   FetchContent_Declare(
979     projD
980     GIT_REPOSITORY git@mycompany.com:git/projD.git
981     GIT_TAG        7d9a17ad2c962aa13e2fbb8043fb6b8a
982   )
983
984   # This particular version of projD requires workarounds
985   FetchContent_GetProperties(projD)
986   if(NOT projd_POPULATED)
987     FetchContent_Populate(projD)
988
989     # Copy an additional/replacement file into the populated source
990     file(COPY someFile.c DESTINATION ${projd_SOURCE_DIR}/src)
991
992     add_subdirectory(${projd_SOURCE_DIR} ${projd_BINARY_DIR})
993   endif()
994
995 A few key points should be noted in the above:
996
997 - ``projB`` and ``projC`` define different content details for ``projD``,
998   but ``projA`` also defines a set of content details for ``projD``.
999   Because ``projA`` will define them first, the details from ``projB`` and
1000   ``projC`` will not be used.  The override details defined by ``projA``
1001   are not required to match either of those from ``projB`` or ``projC``, but
1002   it is up to the higher level project to ensure that the details it does
1003   define still make sense for the child projects.
1004 - In the ``projA`` call to :command:`FetchContent_MakeAvailable`, ``projD``
1005   is listed ahead of ``projB`` and ``projC`` to ensure that ``projA`` is in
1006   control of how ``projD`` is populated.
1007 - While ``projA`` defines content details for ``projE``, it does not need
1008   to explicitly call ``FetchContent_MakeAvailable(projE)`` or
1009   ``FetchContent_Populate(projD)`` itself.  Instead, it leaves that to the
1010   child ``projB``.  For higher level projects, it is often enough to just
1011   define the override content details and leave the actual population to the
1012   child projects.  This saves repeating the same thing at each level of the
1013   project hierarchy unnecessarily.
1014
1015 Populating Content Without Adding It To The Build
1016 """""""""""""""""""""""""""""""""""""""""""""""""
1017
1018 Projects don't always need to add the populated content to the build.
1019 Sometimes the project just wants to make the downloaded content available at
1020 a predictable location.  The next example ensures that a set of standard
1021 company toolchain files (and potentially even the toolchain binaries
1022 themselves) is available early enough to be used for that same build.
1023
1024 .. code-block:: cmake
1025
1026   cmake_minimum_required(VERSION 3.14)
1027
1028   include(FetchContent)
1029   FetchContent_Declare(
1030     mycom_toolchains
1031     URL  https://intranet.mycompany.com//toolchains_1.3.2.tar.gz
1032   )
1033   FetchContent_MakeAvailable(mycom_toolchains)
1034
1035   project(CrossCompileExample)
1036
1037 The project could be configured to use one of the downloaded toolchains like
1038 so:
1039
1040 .. code-block:: shell
1041
1042   cmake -DCMAKE_TOOLCHAIN_FILE=_deps/mycom_toolchains-src/toolchain_arm.cmake /path/to/src
1043
1044 When CMake processes the ``CMakeLists.txt`` file, it will download and unpack
1045 the tarball into ``_deps/mycompany_toolchains-src`` relative to the build
1046 directory.  The :variable:`CMAKE_TOOLCHAIN_FILE` variable is not used until
1047 the :command:`project` command is reached, at which point CMake looks for the
1048 named toolchain file relative to the build directory.  Because the tarball has
1049 already been downloaded and unpacked by then, the toolchain file will be in
1050 place, even the very first time that ``cmake`` is run in the build directory.
1051
1052 Populating Content In CMake Script Mode
1053 """""""""""""""""""""""""""""""""""""""
1054
1055 This last example demonstrates how one might download and unpack a
1056 firmware tarball using CMake's :manual:`script mode <cmake(1)>`.  The call to
1057 :command:`FetchContent_Populate` specifies all the content details and the
1058 unpacked firmware will be placed in a ``firmware`` directory below the
1059 current working directory.
1060
1061 *getFirmware.cmake*:
1062
1063 .. code-block:: cmake
1064
1065   # NOTE: Intended to be run in script mode with cmake -P
1066   include(FetchContent)
1067   FetchContent_Populate(
1068     firmware
1069     URL        https://mycompany.com/assets/firmware-1.23-arm.tar.gz
1070     URL_HASH   MD5=68247684da89b608d466253762b0ff11
1071     SOURCE_DIR firmware
1072   )
1073
1074 #]=======================================================================]
1075
1076 #=======================================================================
1077 # Recording and retrieving content details for later population
1078 #=======================================================================
1079
1080 # Internal use, projects must not call this directly. It is
1081 # intended for use by FetchContent_Declare() only.
1082 #
1083 # Sets a content-specific global property (not meant for use
1084 # outside of functions defined here in this file) which can later
1085 # be retrieved using __FetchContent_getSavedDetails() with just the
1086 # same content name. If there is already a value stored in the
1087 # property, it is left unchanged and this call has no effect.
1088 # This allows parent projects to define the content details,
1089 # overriding anything a child project may try to set (properties
1090 # are not cached between runs, so the first thing to set it in a
1091 # build will be in control).
1092 function(__FetchContent_declareDetails contentName)
1093
1094   string(TOLOWER ${contentName} contentNameLower)
1095   set(savedDetailsPropertyName "_FetchContent_${contentNameLower}_savedDetails")
1096   get_property(alreadyDefined GLOBAL PROPERTY ${savedDetailsPropertyName} DEFINED)
1097   if(alreadyDefined)
1098     return()
1099   endif()
1100
1101   if("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "ALWAYS")
1102     set(__tryFindPackage TRUE)
1103     set(__tryFindPackageAllowed TRUE)
1104   elseif("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "NEVER")
1105     set(__tryFindPackage FALSE)
1106     set(__tryFindPackageAllowed FALSE)
1107   elseif("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "OPT_IN" OR
1108          NOT DEFINED FETCHCONTENT_TRY_FIND_PACKAGE_MODE)
1109     set(__tryFindPackage FALSE)
1110     set(__tryFindPackageAllowed TRUE)
1111   else()
1112     message(FATAL_ERROR
1113       "Unsupported value for FETCHCONTENT_TRY_FIND_PACKAGE_MODE: "
1114       "${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}"
1115     )
1116   endif()
1117
1118   set(__cmdArgs)
1119   set(__findPackageArgs)
1120   set(__sawQuietKeyword NO)
1121   set(__sawGlobalKeyword NO)
1122   foreach(__item IN LISTS ARGN)
1123     if(DEFINED __findPackageArgs)
1124       # All remaining args are for find_package()
1125       string(APPEND __findPackageArgs " [==[${__item}]==]")
1126       if(__item STREQUAL "QUIET")
1127         set(__sawQuietKeyword YES)
1128       elseif(__item STREQUAL "GLOBAL")
1129         set(__sawGlobalKeyword YES)
1130       endif()
1131       continue()
1132     endif()
1133
1134     # Still processing non-find_package() args
1135     if(__item STREQUAL "FIND_PACKAGE_ARGS")
1136       if(__tryFindPackageAllowed)
1137         set(__tryFindPackage TRUE)
1138       endif()
1139       # All arguments after this keyword are for find_package(). Define the
1140       # variable but with an empty value initially. This allows us to check
1141       # at the start of the loop whether to store remaining items in this
1142       # variable or not. Note that there could be no more args, which is still
1143       # a valid case because we automatically provide ${contentName} as the
1144       # package name and there may not need to be any further arguments.
1145       set(__findPackageArgs "")
1146       continue()  # Don't store this item
1147     elseif(__item STREQUAL "OVERRIDE_FIND_PACKAGE")
1148       set(__tryFindPackageAllowed FALSE)
1149       # Define a separate dedicated property for find_package() to check
1150       # in its implementation. This will be a placeholder until FetchContent
1151       # actually does the population. After that, we will have created a
1152       # stand-in config file that find_package() will pick up instead.
1153       set(propertyName "_FetchContent_${contentNameLower}_override_find_package")
1154       define_property(GLOBAL PROPERTY ${propertyName})
1155       set_property(GLOBAL PROPERTY ${propertyName} TRUE)
1156     endif()
1157
1158     string(APPEND __cmdArgs " [==[${__item}]==]")
1159   endforeach()
1160
1161   define_property(GLOBAL PROPERTY ${savedDetailsPropertyName})
1162   cmake_language(EVAL CODE
1163     "set_property(GLOBAL PROPERTY ${savedDetailsPropertyName} ${__cmdArgs})"
1164   )
1165
1166   if(__tryFindPackage AND __tryFindPackageAllowed)
1167     set(propertyName "_FetchContent_${contentNameLower}_find_package_args")
1168     define_property(GLOBAL PROPERTY ${propertyName})
1169     if(NOT __sawQuietKeyword)
1170       list(INSERT __findPackageArgs 0 QUIET)
1171     endif()
1172     if(CMAKE_FIND_PACKAGE_TARGETS_GLOBAL AND NOT __sawGlobalKeyword)
1173       list(APPEND __findPackageArgs GLOBAL)
1174     endif()
1175     cmake_language(EVAL CODE
1176       "set_property(GLOBAL PROPERTY ${propertyName} ${__findPackageArgs})"
1177     )
1178   endif()
1179
1180 endfunction()
1181
1182
1183 # Internal use, projects must not call this directly. It is
1184 # intended for use by the FetchContent_Declare() function.
1185 #
1186 # Retrieves details saved for the specified content in an
1187 # earlier call to __FetchContent_declareDetails().
1188 function(__FetchContent_getSavedDetails contentName outVar)
1189
1190   string(TOLOWER ${contentName} contentNameLower)
1191   set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
1192   get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
1193   if(NOT alreadyDefined)
1194     message(FATAL_ERROR "No content details recorded for ${contentName}")
1195   endif()
1196   get_property(propertyValue GLOBAL PROPERTY ${propertyName})
1197   set(${outVar} "${propertyValue}" PARENT_SCOPE)
1198
1199 endfunction()
1200
1201
1202 # Saves population details of the content, sets defaults for the
1203 # SOURCE_DIR and BUILD_DIR.
1204 function(FetchContent_Declare contentName)
1205
1206   # Always check this even if we won't save these details.
1207   # This helps projects catch errors earlier.
1208   # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
1209   list(FIND ARGN OVERRIDE_FIND_PACKAGE index_OVERRIDE_FIND_PACKAGE)
1210   list(FIND ARGN FIND_PACKAGE_ARGS index_FIND_PACKAGE_ARGS)
1211   if(index_OVERRIDE_FIND_PACKAGE GREATER_EQUAL 0 AND
1212      index_FIND_PACKAGE_ARGS GREATER_EQUAL 0)
1213     message(FATAL_ERROR
1214       "Cannot specify both OVERRIDE_FIND_PACKAGE and FIND_PACKAGE_ARGS "
1215       "when declaring details for ${contentName}"
1216     )
1217   endif()
1218
1219   # Because we are only looking for a subset of the supported keywords, we
1220   # cannot check for multi-value arguments with this method. We will have to
1221   # handle the URL keyword differently.
1222   set(oneValueArgs
1223     SVN_REPOSITORY
1224     DOWNLOAD_NO_EXTRACT
1225     DOWNLOAD_EXTRACT_TIMESTAMP
1226     BINARY_DIR
1227     SOURCE_DIR
1228   )
1229
1230   cmake_parse_arguments(PARSE_ARGV 1 ARG "" "${oneValueArgs}" "")
1231
1232   string(TOLOWER ${contentName} contentNameLower)
1233
1234   if(NOT ARG_BINARY_DIR)
1235     set(ARG_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
1236   endif()
1237
1238   if(NOT ARG_SOURCE_DIR)
1239     set(ARG_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
1240   endif()
1241
1242   if(ARG_SVN_REPOSITORY)
1243     # Add a hash of the svn repository URL to the source dir. This works
1244     # around the problem where if the URL changes, the download would
1245     # fail because it tries to checkout/update rather than switch the
1246     # old URL to the new one. We limit the hash to the first 7 characters
1247     # so that the source path doesn't get overly long (which can be a
1248     # problem on windows due to path length limits).
1249     string(SHA1 urlSHA ${ARG_SVN_REPOSITORY})
1250     string(SUBSTRING ${urlSHA} 0 7 urlSHA)
1251     string(APPEND ARG_SOURCE_DIR "-${urlSHA}")
1252   endif()
1253
1254   # The ExternalProject_Add() call in the sub-build won't see the CMP0135
1255   # policy setting of our caller. Work out if that policy will be needed and
1256   # explicitly set the relevant option if not already provided. The condition
1257   # here is essentially an abbreviated version of the logic in
1258   # ExternalProject's _ep_add_download_command() function.
1259   if(NOT ARG_DOWNLOAD_NO_EXTRACT AND
1260      NOT DEFINED ARG_DOWNLOAD_EXTRACT_TIMESTAMP)
1261     list(FIND ARGN URL urlIndex)
1262     if(urlIndex GREATER_EQUAL 0)
1263       math(EXPR urlIndex "${urlIndex} + 1")
1264       list(LENGTH ARGN numArgs)
1265       if(urlIndex GREATER_EQUAL numArgs)
1266         message(FATAL_ERROR
1267           "URL keyword needs to be followed by at least one URL"
1268         )
1269       endif()
1270       # If we have multiple URLs, none of them are allowed to be local paths.
1271       # Therefore, we can test just the first URL, and if it is non-local, so
1272       # will be the others if there are more.
1273       list(GET ARGN ${urlIndex} firstUrl)
1274       if(NOT IS_DIRECTORY "${firstUrl}")
1275         cmake_policy(GET CMP0135 _FETCHCONTENT_CMP0135
1276           PARENT_SCOPE # undocumented, do not use outside of CMake
1277         )
1278         if(_FETCHCONTENT_CMP0135 STREQUAL "")
1279           message(AUTHOR_WARNING
1280             "The DOWNLOAD_EXTRACT_TIMESTAMP option was not given and policy "
1281             "CMP0135 is not set. The policy's OLD behavior will be used. "
1282             "When using a URL download, the timestamps of extracted files "
1283             "should preferably be that of the time of extraction, otherwise "
1284             "code that depends on the extracted contents might not be "
1285             "rebuilt if the URL changes. The OLD behavior preserves the "
1286             "timestamps from the archive instead, but this is usually not "
1287             "what you want. Update your project to the NEW behavior or "
1288             "specify the DOWNLOAD_EXTRACT_TIMESTAMP option with a value of "
1289             "true to avoid this robustness issue."
1290           )
1291           set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
1292         elseif(_FETCHCONTENT_CMP0135 STREQUAL "NEW")
1293           set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
1294         else()
1295           set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
1296         endif()
1297       endif()
1298     endif()
1299   endif()
1300
1301   # Add back in the keyword args we pulled out and potentially tweaked/added
1302   foreach(key IN LISTS oneValueArgs)
1303     if(DEFINED ARG_${key})
1304       list(PREPEND ARG_UNPARSED_ARGUMENTS ${key} "${ARG_${key}}")
1305     endif()
1306   endforeach()
1307
1308   set(__argsQuoted)
1309   foreach(__item IN LISTS ARG_UNPARSED_ARGUMENTS)
1310     string(APPEND __argsQuoted " [==[${__item}]==]")
1311   endforeach()
1312   cmake_language(EVAL CODE
1313     "__FetchContent_declareDetails(${contentNameLower} ${__argsQuoted})"
1314   )
1315
1316 endfunction()
1317
1318
1319 #=======================================================================
1320 # Set/get whether the specified content has been populated yet.
1321 # The setter also records the source and binary dirs used.
1322 #=======================================================================
1323
1324 # Semi-internal use. Projects must not call this directly. Dependency
1325 # providers must call it if they satisfy a request made with the
1326 # FETCHCONTENT_MAKEAVAILABLE_SERIAL method (that is the only permitted
1327 # place to call it outside of the FetchContent module).
1328 function(FetchContent_SetPopulated contentName)
1329
1330   cmake_parse_arguments(PARSE_ARGV 1 arg
1331     ""
1332     "SOURCE_DIR;BINARY_DIR"
1333     ""
1334   )
1335   if(NOT "${arg_UNPARSED_ARGUMENTS}" STREQUAL "")
1336     message(FATAL_ERROR "Unsupported arguments: ${arg_UNPARSED_ARGUMENTS}")
1337   endif()
1338
1339   string(TOLOWER ${contentName} contentNameLower)
1340   set(prefix "_FetchContent_${contentNameLower}")
1341
1342   set(propertyName "${prefix}_sourceDir")
1343   define_property(GLOBAL PROPERTY ${propertyName})
1344   if("${arg_SOURCE_DIR}" STREQUAL "")
1345     # Don't discard a previously provided SOURCE_DIR
1346     get_property(arg_SOURCE_DIR GLOBAL PROPERTY ${propertyName})
1347   endif()
1348   set_property(GLOBAL PROPERTY ${propertyName} "${arg_SOURCE_DIR}")
1349
1350   set(propertyName "${prefix}_binaryDir")
1351   define_property(GLOBAL PROPERTY ${propertyName})
1352   if("${arg_BINARY_DIR}" STREQUAL "")
1353     # Don't discard a previously provided BINARY_DIR
1354     get_property(arg_BINARY_DIR GLOBAL PROPERTY ${propertyName})
1355   endif()
1356   set_property(GLOBAL PROPERTY ${propertyName} "${arg_BINARY_DIR}")
1357
1358   set(propertyName "${prefix}_populated")
1359   define_property(GLOBAL PROPERTY ${propertyName})
1360   set_property(GLOBAL PROPERTY ${propertyName} TRUE)
1361
1362 endfunction()
1363
1364
1365 # Set variables in the calling scope for any of the retrievable
1366 # properties. If no specific properties are requested, variables
1367 # will be set for all retrievable properties.
1368 #
1369 # This function is intended to also be used by projects as the canonical
1370 # way to detect whether they should call FetchContent_Populate()
1371 # and pull the populated source into the build with add_subdirectory(),
1372 # if they are using the populated content in that way.
1373 function(FetchContent_GetProperties contentName)
1374
1375   string(TOLOWER ${contentName} contentNameLower)
1376
1377   set(options "")
1378   set(oneValueArgs SOURCE_DIR BINARY_DIR POPULATED)
1379   set(multiValueArgs "")
1380
1381   cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
1382
1383   if(NOT ARG_SOURCE_DIR AND
1384      NOT ARG_BINARY_DIR AND
1385      NOT ARG_POPULATED)
1386     # No specific properties requested, provide them all
1387     set(ARG_SOURCE_DIR ${contentNameLower}_SOURCE_DIR)
1388     set(ARG_BINARY_DIR ${contentNameLower}_BINARY_DIR)
1389     set(ARG_POPULATED  ${contentNameLower}_POPULATED)
1390   endif()
1391
1392   set(prefix "_FetchContent_${contentNameLower}")
1393
1394   if(ARG_SOURCE_DIR)
1395     set(propertyName "${prefix}_sourceDir")
1396     get_property(value GLOBAL PROPERTY ${propertyName})
1397     if(value)
1398       set(${ARG_SOURCE_DIR} ${value} PARENT_SCOPE)
1399     endif()
1400   endif()
1401
1402   if(ARG_BINARY_DIR)
1403     set(propertyName "${prefix}_binaryDir")
1404     get_property(value GLOBAL PROPERTY ${propertyName})
1405     if(value)
1406       set(${ARG_BINARY_DIR} ${value} PARENT_SCOPE)
1407     endif()
1408   endif()
1409
1410   if(ARG_POPULATED)
1411     set(propertyName "${prefix}_populated")
1412     get_property(value GLOBAL PROPERTY ${propertyName} DEFINED)
1413     set(${ARG_POPULATED} ${value} PARENT_SCOPE)
1414   endif()
1415
1416 endfunction()
1417
1418
1419 #=======================================================================
1420 # Performing the population
1421 #=======================================================================
1422
1423 # The value of contentName will always have been lowercased by the caller.
1424 # All other arguments are assumed to be options that are understood by
1425 # ExternalProject_Add(), except for QUIET and SUBBUILD_DIR.
1426 function(__FetchContent_directPopulate contentName)
1427
1428   set(options
1429       QUIET
1430   )
1431   set(oneValueArgs
1432       SUBBUILD_DIR
1433       SOURCE_DIR
1434       BINARY_DIR
1435       # We need special processing if DOWNLOAD_NO_EXTRACT is true
1436       DOWNLOAD_NO_EXTRACT
1437       # Prevent the following from being passed through
1438       CONFIGURE_COMMAND
1439       BUILD_COMMAND
1440       INSTALL_COMMAND
1441       TEST_COMMAND
1442       # We force these to be ON since we are always executing serially
1443       # and we want all steps to have access to the terminal in case they
1444       # need input from the command line (e.g. ask for a private key password)
1445       # or they want to provide timely progress. We silently absorb and
1446       # discard these if they are set by the caller.
1447       USES_TERMINAL_DOWNLOAD
1448       USES_TERMINAL_UPDATE
1449       USES_TERMINAL_PATCH
1450   )
1451   set(multiValueArgs "")
1452
1453   cmake_parse_arguments(PARSE_ARGV 1 ARG
1454     "${options}" "${oneValueArgs}" "${multiValueArgs}")
1455
1456   if(NOT ARG_SUBBUILD_DIR)
1457     message(FATAL_ERROR "Internal error: SUBBUILD_DIR not set")
1458   elseif(NOT IS_ABSOLUTE "${ARG_SUBBUILD_DIR}")
1459     set(ARG_SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SUBBUILD_DIR}")
1460   endif()
1461
1462   if(NOT ARG_SOURCE_DIR)
1463     message(FATAL_ERROR "Internal error: SOURCE_DIR not set")
1464   elseif(NOT IS_ABSOLUTE "${ARG_SOURCE_DIR}")
1465     set(ARG_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SOURCE_DIR}")
1466   endif()
1467
1468   if(NOT ARG_BINARY_DIR)
1469     message(FATAL_ERROR "Internal error: BINARY_DIR not set")
1470   elseif(NOT IS_ABSOLUTE "${ARG_BINARY_DIR}")
1471     set(ARG_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_BINARY_DIR}")
1472   endif()
1473
1474   # Ensure the caller can know where to find the source and build directories
1475   # with some convenient variables. Doing this here ensures the caller sees
1476   # the correct result in the case where the default values are overridden by
1477   # the content details set by the project.
1478   set(${contentName}_SOURCE_DIR "${ARG_SOURCE_DIR}" PARENT_SCOPE)
1479   set(${contentName}_BINARY_DIR "${ARG_BINARY_DIR}" PARENT_SCOPE)
1480
1481   # The unparsed arguments may contain spaces, so build up ARG_EXTRA
1482   # in such a way that it correctly substitutes into the generated
1483   # CMakeLists.txt file with each argument quoted.
1484   unset(ARG_EXTRA)
1485   foreach(arg IN LISTS ARG_UNPARSED_ARGUMENTS)
1486     set(ARG_EXTRA "${ARG_EXTRA} \"${arg}\"")
1487   endforeach()
1488
1489   if(ARG_DOWNLOAD_NO_EXTRACT)
1490     set(ARG_EXTRA "${ARG_EXTRA} DOWNLOAD_NO_EXTRACT YES")
1491     set(__FETCHCONTENT_COPY_FILE
1492 "
1493 ExternalProject_Get_Property(${contentName}-populate DOWNLOADED_FILE)
1494 get_filename_component(dlFileName \"\${DOWNLOADED_FILE}\" NAME)
1495
1496 ExternalProject_Add_Step(${contentName}-populate copyfile
1497   COMMAND    \"${CMAKE_COMMAND}\" -E copy_if_different
1498              \"<DOWNLOADED_FILE>\" \"${ARG_SOURCE_DIR}\"
1499   DEPENDEES  patch
1500   DEPENDERS  configure
1501   BYPRODUCTS \"${ARG_SOURCE_DIR}/\${dlFileName}\"
1502   COMMENT    \"Copying file to SOURCE_DIR\"
1503 )
1504 ")
1505   else()
1506     unset(__FETCHCONTENT_COPY_FILE)
1507   endif()
1508
1509   # Hide output if requested, but save it to a variable in case there's an
1510   # error so we can show the output upon failure. When not quiet, don't
1511   # capture the output to a variable because the user may want to see the
1512   # output as it happens (e.g. progress during long downloads). Combine both
1513   # stdout and stderr in the one capture variable so the output stays in order.
1514   if (ARG_QUIET)
1515     set(outputOptions
1516         OUTPUT_VARIABLE capturedOutput
1517         ERROR_VARIABLE  capturedOutput
1518     )
1519   else()
1520     set(capturedOutput)
1521     set(outputOptions)
1522     message(STATUS "Populating ${contentName}")
1523   endif()
1524
1525   if(CMAKE_GENERATOR)
1526     set(subCMakeOpts "-G${CMAKE_GENERATOR}")
1527     if(CMAKE_GENERATOR_PLATFORM)
1528       list(APPEND subCMakeOpts "-A${CMAKE_GENERATOR_PLATFORM}")
1529     endif()
1530     if(CMAKE_GENERATOR_TOOLSET)
1531       list(APPEND subCMakeOpts "-T${CMAKE_GENERATOR_TOOLSET}")
1532     endif()
1533
1534     if(CMAKE_MAKE_PROGRAM)
1535       list(APPEND subCMakeOpts "-DCMAKE_MAKE_PROGRAM:FILEPATH=${CMAKE_MAKE_PROGRAM}")
1536     endif()
1537
1538     # Override the sub-build's configuration types for multi-config generators.
1539     # This ensures we are not affected by any custom setting from the project
1540     # and can always request a known configuration further below.
1541     get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
1542     if(is_multi_config)
1543       list(APPEND subCMakeOpts "-DCMAKE_CONFIGURATION_TYPES:STRING=Debug")
1544     endif()
1545
1546   else()
1547     # Likely we've been invoked via CMake's script mode where no
1548     # generator is set (and hence CMAKE_MAKE_PROGRAM could not be
1549     # trusted even if provided). We will have to rely on being
1550     # able to find the default generator and build tool.
1551     unset(subCMakeOpts)
1552   endif()
1553
1554   set(__FETCHCONTENT_CACHED_INFO "")
1555   set(__passthrough_vars
1556     CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY
1557     CMAKE_TLS_VERIFY
1558     CMAKE_TLS_CAINFO
1559     CMAKE_NETRC
1560     CMAKE_NETRC_FILE
1561   )
1562   foreach(var IN LISTS __passthrough_vars)
1563     if(DEFINED ${var})
1564       # Embed directly in the generated CMakeLists.txt file to avoid making
1565       # the cmake command line excessively long. It also makes debugging and
1566       # testing easier.
1567       string(APPEND __FETCHCONTENT_CACHED_INFO "set(${var} [==[${${var}}]==])\n")
1568     endif()
1569   endforeach()
1570
1571   # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
1572   list(FIND ARG_UNPARSED_ARGUMENTS GIT_REPOSITORY indexResult)
1573   if(indexResult GREATER_EQUAL 0)
1574     find_package(Git QUIET)
1575     string(APPEND __FETCHCONTENT_CACHED_INFO "
1576 # Pass through things we've already detected in the main project to avoid
1577 # paying the cost of redetecting them again in ExternalProject_Add()
1578 set(GIT_EXECUTABLE [==[${GIT_EXECUTABLE}]==])
1579 set(GIT_VERSION_STRING [==[${GIT_VERSION_STRING}]==])
1580 set_property(GLOBAL PROPERTY _CMAKE_FindGit_GIT_EXECUTABLE_VERSION
1581   [==[${GIT_EXECUTABLE};${GIT_VERSION_STRING}]==]
1582 )
1583 ")
1584   endif()
1585
1586   # Create and build a separate CMake project to carry out the population.
1587   # If we've already previously done these steps, they will not cause
1588   # anything to be updated, so extra rebuilds of the project won't occur.
1589   # Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
1590   # has this set to something not findable on the PATH. We also ensured above
1591   # that the Debug config will be defined for multi-config generators.
1592   configure_file("${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent/CMakeLists.cmake.in"
1593                  "${ARG_SUBBUILD_DIR}/CMakeLists.txt")
1594   execute_process(
1595     COMMAND ${CMAKE_COMMAND} ${subCMakeOpts} .
1596     RESULT_VARIABLE result
1597     ${outputOptions}
1598     WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
1599   )
1600   if(result)
1601     if(capturedOutput)
1602       message("${capturedOutput}")
1603     endif()
1604     message(FATAL_ERROR "CMake step for ${contentName} failed: ${result}")
1605   endif()
1606   execute_process(
1607     COMMAND ${CMAKE_COMMAND} --build . --config Debug
1608     RESULT_VARIABLE result
1609     ${outputOptions}
1610     WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
1611   )
1612   if(result)
1613     if(capturedOutput)
1614       message("${capturedOutput}")
1615     endif()
1616     message(FATAL_ERROR "Build step for ${contentName} failed: ${result}")
1617   endif()
1618
1619 endfunction()
1620
1621
1622 option(FETCHCONTENT_FULLY_DISCONNECTED   "Disables all attempts to download or update content and assumes source dirs already exist")
1623 option(FETCHCONTENT_UPDATES_DISCONNECTED "Enables UPDATE_DISCONNECTED behavior for all content population")
1624 option(FETCHCONTENT_QUIET                "Enables QUIET option for all content population" ON)
1625 set(FETCHCONTENT_BASE_DIR "${CMAKE_BINARY_DIR}/_deps" CACHE PATH "Directory under which to collect all populated content")
1626
1627 # Populate the specified content using details stored from
1628 # an earlier call to FetchContent_Declare().
1629 function(FetchContent_Populate contentName)
1630
1631   if(NOT contentName)
1632     message(FATAL_ERROR "Empty contentName not allowed for FetchContent_Populate()")
1633   endif()
1634
1635   string(TOLOWER ${contentName} contentNameLower)
1636
1637   if(ARGN)
1638     # This is the direct population form with details fully specified
1639     # as part of the call, so we already have everything we need
1640     __FetchContent_directPopulate(
1641       ${contentNameLower}
1642       SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-subbuild"
1643       SOURCE_DIR   "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-src"
1644       BINARY_DIR   "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-build"
1645       ${ARGN}  # Could override any of the above ..._DIR variables
1646     )
1647
1648     # Pass source and binary dir variables back to the caller
1649     set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
1650     set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
1651
1652     # Don't set global properties, or record that we did this population, since
1653     # this was a direct call outside of the normal declared details form.
1654     # We only want to save values in the global properties for content that
1655     # honors the hierarchical details mechanism so that projects are not
1656     # robbed of the ability to override details set in nested projects.
1657     return()
1658   endif()
1659
1660   # No details provided, so assume they were saved from an earlier call
1661   # to FetchContent_Declare(). Do a check that we haven't already
1662   # populated this content before in case the caller forgot to check.
1663   FetchContent_GetProperties(${contentName})
1664   if(${contentNameLower}_POPULATED)
1665     if("${${contentNameLower}_SOURCE_DIR}" STREQUAL "")
1666       message(FATAL_ERROR
1667         "Content ${contentName} already populated by find_package() or a "
1668         "dependency provider"
1669       )
1670     else()
1671       message(FATAL_ERROR
1672         "Content ${contentName} already populated in ${${contentNameLower}_SOURCE_DIR}"
1673       )
1674     endif()
1675   endif()
1676
1677   __FetchContent_getSavedDetails(${contentName} contentDetails)
1678   if("${contentDetails}" STREQUAL "")
1679     message(FATAL_ERROR "No details have been set for content: ${contentName}")
1680   endif()
1681
1682   string(TOUPPER ${contentName} contentNameUpper)
1683   set(FETCHCONTENT_SOURCE_DIR_${contentNameUpper}
1684       "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}"
1685       CACHE PATH "When not empty, overrides where to find pre-populated content for ${contentName}")
1686
1687   if(FETCHCONTENT_SOURCE_DIR_${contentNameUpper})
1688     # The source directory has been explicitly provided in the cache,
1689     # so no population is required. The build directory may still be specified
1690     # by the declared details though.
1691
1692     if(NOT IS_ABSOLUTE "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1693       # Don't check this directory because we don't know what location it is
1694       # expected to be relative to. We can't make this a hard error for backward
1695       # compatibility reasons.
1696       message(WARNING "Relative source directory specified. This is not safe, "
1697         "as it depends on the calling directory scope.\n"
1698         "  FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1699     elseif(NOT EXISTS "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1700       message(FATAL_ERROR "Manually specified source directory is missing:\n"
1701         "  FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1702     endif()
1703
1704     set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1705
1706     cmake_parse_arguments(savedDetails "" "BINARY_DIR" "" ${contentDetails})
1707
1708     if(savedDetails_BINARY_DIR)
1709       set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
1710     else()
1711       set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
1712     endif()
1713
1714   elseif(FETCHCONTENT_FULLY_DISCONNECTED)
1715     # Bypass population and assume source is already there from a previous run.
1716     # Declared details may override the default source or build directories.
1717
1718     cmake_parse_arguments(savedDetails "" "SOURCE_DIR;BINARY_DIR" "" ${contentDetails})
1719
1720     if(savedDetails_SOURCE_DIR)
1721       set(${contentNameLower}_SOURCE_DIR ${savedDetails_SOURCE_DIR})
1722     else()
1723       set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
1724     endif()
1725
1726     if(savedDetails_BINARY_DIR)
1727       set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
1728     else()
1729       set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
1730     endif()
1731
1732   else()
1733     # Support both a global "disconnect all updates" and a per-content
1734     # update test (either one being set disables updates for this content).
1735     option(FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper}
1736            "Enables UPDATE_DISCONNECTED behavior just for population of ${contentName}")
1737     if(FETCHCONTENT_UPDATES_DISCONNECTED OR
1738        FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper})
1739       set(disconnectUpdates True)
1740     else()
1741       set(disconnectUpdates False)
1742     endif()
1743
1744     if(FETCHCONTENT_QUIET)
1745       set(quietFlag QUIET)
1746     else()
1747       unset(quietFlag)
1748     endif()
1749
1750     set(__detailsQuoted)
1751     foreach(__item IN LISTS contentDetails)
1752       if(NOT __item STREQUAL "OVERRIDE_FIND_PACKAGE")
1753         string(APPEND __detailsQuoted " [==[${__item}]==]")
1754       endif()
1755     endforeach()
1756     cmake_language(EVAL CODE "
1757       __FetchContent_directPopulate(
1758         ${contentNameLower}
1759         ${quietFlag}
1760         UPDATE_DISCONNECTED ${disconnectUpdates}
1761         SUBBUILD_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-subbuild\"
1762         SOURCE_DIR   \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src\"
1763         BINARY_DIR   \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build\"
1764         # Put the saved details last so they can override any of the
1765         # the options we set above (this can include SOURCE_DIR or
1766         # BUILD_DIR)
1767         ${__detailsQuoted}
1768       )"
1769     )
1770   endif()
1771
1772   FetchContent_SetPopulated(
1773     ${contentName}
1774     SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}"
1775     BINARY_DIR "${${contentNameLower}_BINARY_DIR}"
1776   )
1777
1778   # Pass variables back to the caller. The variables passed back here
1779   # must match what FetchContent_GetProperties() sets when it is called
1780   # with just the content name.
1781   set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
1782   set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
1783   set(${contentNameLower}_POPULATED  True PARENT_SCOPE)
1784
1785 endfunction()
1786
1787 function(__FetchContent_setupFindPackageRedirection contentName)
1788
1789   __FetchContent_getSavedDetails(${contentName} contentDetails)
1790
1791   string(TOLOWER ${contentName} contentNameLower)
1792   get_property(wantFindPackage GLOBAL PROPERTY
1793     _FetchContent_${contentNameLower}_find_package_args
1794     DEFINED
1795   )
1796
1797   # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
1798   list(FIND contentDetails OVERRIDE_FIND_PACKAGE indexResult)
1799   if(NOT wantFindPackage AND indexResult EQUAL -1)
1800     # No find_package() redirection allowed
1801     return()
1802   endif()
1803
1804   # We write out dep-config.cmake and dep-config-version.cmake file name
1805   # forms here because they are forced to lowercase. FetchContent
1806   # dependency names are case-insensitive, but find_package() config files
1807   # are only case-insensitive for the -config and -config-version forms,
1808   # not the Config and ConfigVersion forms.
1809   set(inFileDir ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent)
1810   set(configFilePrefix1 "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${contentName}Config")
1811   set(configFilePrefix2 "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${contentNameLower}-config")
1812   if(NOT EXISTS "${configFilePrefix1}.cmake" AND
1813     NOT EXISTS "${configFilePrefix2}.cmake")
1814     configure_file(${inFileDir}/package-config.cmake.in
1815       "${configFilePrefix2}.cmake" @ONLY
1816     )
1817   endif()
1818   if(NOT EXISTS "${configFilePrefix1}Version.cmake" AND
1819     NOT EXISTS "${configFilePrefix2}-version.cmake")
1820     configure_file(${inFileDir}/package-config-version.cmake.in
1821       "${configFilePrefix2}-version.cmake" @ONLY
1822     )
1823   endif()
1824
1825   # Now that we've created the redirected package config files, prevent
1826   # find_package() from delegating to FetchContent and let it find these
1827   # config files through its normal processing.
1828   set(propertyName "${prefix}_override_find_package")
1829   set(GLOBAL PROPERTY ${propertyName} FALSE)
1830   set(${contentName}_DIR "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}"
1831     CACHE INTERNAL "Redirected by FetchContent"
1832   )
1833
1834 endfunction()
1835
1836 # Arguments are assumed to be the names of dependencies that have been
1837 # declared previously and should be populated. It is not an error if
1838 # any of them have already been populated (they will just be skipped in
1839 # that case). The command is implemented as a macro so that the variables
1840 # defined by the FetchContent_GetProperties() and FetchContent_Populate()
1841 # calls will be available to the caller.
1842 macro(FetchContent_MakeAvailable)
1843
1844   # We must append an item, even if the variable is unset, so prefix its value.
1845   # We will strip that prefix when we pop the value at the end of the macro.
1846   list(APPEND __cmake_fcCurrentVarsStack
1847     "__fcprefix__${CMAKE_VERIFY_INTERFACE_HEADER_SETS}"
1848   )
1849   set(CMAKE_VERIFY_INTERFACE_HEADER_SETS FALSE)
1850
1851   get_property(__cmake_providerCommand GLOBAL PROPERTY
1852     __FETCHCONTENT_MAKEAVAILABLE_SERIAL_PROVIDER
1853   )
1854   foreach(__cmake_contentName IN ITEMS ${ARGV})
1855     string(TOLOWER ${__cmake_contentName} __cmake_contentNameLower)
1856
1857     # If user specified FETCHCONTENT_SOURCE_DIR_... for this dependency, that
1858     # overrides everything else and we shouldn't try to use find_package() or
1859     # a dependency provider.
1860     string(TOUPPER ${__cmake_contentName} __cmake_contentNameUpper)
1861     if("${FETCHCONTENT_SOURCE_DIR_${__cmake_contentNameUpper}}" STREQUAL "")
1862       # Dependency provider gets first opportunity, but prevent infinite
1863       # recursion if we are called again for the same thing
1864       if(NOT "${__cmake_providerCommand}" STREQUAL "" AND
1865         NOT DEFINED __cmake_fcProvider_${__cmake_contentNameLower})
1866         message(VERBOSE
1867           "Trying FETCHCONTENT_MAKEAVAILABLE_SERIAL dependency provider for "
1868           "${__cmake_contentName}"
1869         )
1870         # It's still valid if there are no saved details. The project may have
1871         # been written to assume a dependency provider is always set and will
1872         # provide dependencies without having any declared details for them.
1873         __FetchContent_getSavedDetails(${__cmake_contentName} __cmake_contentDetails)
1874         set(__cmake_providerArgs
1875           "FETCHCONTENT_MAKEAVAILABLE_SERIAL"
1876           "${__cmake_contentName}"
1877         )
1878         # Empty arguments must be preserved because of things like
1879         # GIT_SUBMODULES (see CMP0097)
1880         foreach(__cmake_item IN LISTS __cmake_contentDetails)
1881           string(APPEND __cmake_providerArgs " [==[${__cmake_item}]==]")
1882         endforeach()
1883
1884         # This property might be defined but empty. As long as it is defined,
1885         # find_package() can be called.
1886         get_property(__cmake_addfpargs GLOBAL PROPERTY
1887           _FetchContent_${contentNameLower}_find_package_args
1888           DEFINED
1889         )
1890         if(__cmake_addfpargs)
1891           get_property(__cmake_fpargs GLOBAL PROPERTY
1892             _FetchContent_${contentNameLower}_find_package_args
1893           )
1894           string(APPEND __cmake_providerArgs " FIND_PACKAGE_ARGS")
1895           foreach(__cmake_item IN LISTS __cmake_fpargs)
1896             string(APPEND __cmake_providerArgs " [==[${__cmake_item}]==]")
1897           endforeach()
1898         endif()
1899
1900         # Calling the provider could lead to FetchContent_MakeAvailable() being
1901         # called for a nested dependency. That nested call may occur in the
1902         # current variable scope. We have to save and restore the variables we
1903         # need preserved.
1904         list(APPEND __cmake_fcCurrentVarsStack
1905           ${__cmake_contentName}
1906           ${__cmake_contentNameLower}
1907         )
1908
1909         set(__cmake_fcProvider_${__cmake_contentNameLower} YES)
1910         cmake_language(EVAL CODE "${__cmake_providerCommand}(${__cmake_providerArgs})")
1911
1912         list(POP_BACK __cmake_fcCurrentVarsStack
1913           __cmake_contentNameLower
1914           __cmake_contentName
1915         )
1916
1917         unset(__cmake_fcProvider_${__cmake_contentNameLower})
1918         unset(__cmake_providerArgs)
1919         unset(__cmake_addfpargs)
1920         unset(__cmake_fpargs)
1921         unset(__cmake_item)
1922         unset(__cmake_contentDetails)
1923
1924         FetchContent_GetProperties(${__cmake_contentName})
1925         if(${__cmake_contentNameLower}_POPULATED)
1926           continue()
1927         endif()
1928       endif()
1929
1930       # Check if we've been asked to try find_package() first, even if we
1931       # have already populated this dependency. If we previously tried to
1932       # use find_package() for this and it succeeded, those things might
1933       # no longer be in scope, so we have to do it again.
1934       get_property(__cmake_haveFpArgs GLOBAL PROPERTY
1935         _FetchContent_${__cmake_contentNameLower}_find_package_args DEFINED
1936       )
1937       if(__cmake_haveFpArgs)
1938         unset(__cmake_haveFpArgs)
1939         message(VERBOSE "Trying find_package(${__cmake_contentName} ...) before FetchContent")
1940         get_property(__cmake_fpArgs GLOBAL PROPERTY
1941           _FetchContent_${__cmake_contentNameLower}_find_package_args
1942         )
1943
1944         # This call could lead to FetchContent_MakeAvailable() being called for
1945         # a nested dependency and it may occur in the current variable scope.
1946         # We have to save/restore the variables we need to preserve.
1947         list(APPEND __cmake_fcCurrentNameStack
1948           ${__cmake_contentName}
1949           ${__cmake_contentNameLower}
1950         )
1951         find_package(${__cmake_contentName} ${__cmake_fpArgs})
1952         list(POP_BACK __cmake_fcCurrentNameStack
1953           __cmake_contentNameLower
1954           __cmake_contentName
1955         )
1956         unset(__cmake_fpArgs)
1957
1958         if(${__cmake_contentName}_FOUND)
1959           FetchContent_SetPopulated(${__cmake_contentName})
1960           FetchContent_GetProperties(${__cmake_contentName})
1961           continue()
1962         endif()
1963       endif()
1964     else()
1965       unset(__cmake_haveFpArgs)
1966     endif()
1967
1968     FetchContent_GetProperties(${__cmake_contentName})
1969     if(NOT ${__cmake_contentNameLower}_POPULATED)
1970       FetchContent_Populate(${__cmake_contentName})
1971       __FetchContent_setupFindPackageRedirection(${__cmake_contentName})
1972
1973       # Only try to call add_subdirectory() if the populated content
1974       # can be treated that way. Protecting the call with the check
1975       # allows this function to be used for projects that just want
1976       # to ensure the content exists, such as to provide content at
1977       # a known location. We check the saved details for an optional
1978       # SOURCE_SUBDIR which can be used in the same way as its meaning
1979       # for ExternalProject. It won't matter if it was passed through
1980       # to the ExternalProject sub-build, since it would have been
1981       # ignored there.
1982       set(__cmake_srcdir "${${__cmake_contentNameLower}_SOURCE_DIR}")
1983       __FetchContent_getSavedDetails(${__cmake_contentName} __cmake_contentDetails)
1984       if("${__cmake_contentDetails}" STREQUAL "")
1985         message(FATAL_ERROR "No details have been set for content: ${__cmake_contentName}")
1986       endif()
1987       cmake_parse_arguments(__cmake_arg "SYSTEM" "SOURCE_SUBDIR" "" ${__cmake_contentDetails})
1988       if(NOT "${__cmake_arg_SOURCE_SUBDIR}" STREQUAL "")
1989         string(APPEND __cmake_srcdir "/${__cmake_arg_SOURCE_SUBDIR}")
1990       endif()
1991
1992       if(EXISTS ${__cmake_srcdir}/CMakeLists.txt)
1993         if (__cmake_arg_SYSTEM)
1994           add_subdirectory(${__cmake_srcdir} ${${__cmake_contentNameLower}_BINARY_DIR} SYSTEM)
1995         else()
1996           add_subdirectory(${__cmake_srcdir} ${${__cmake_contentNameLower}_BINARY_DIR})
1997         endif()
1998       endif()
1999
2000       unset(__cmake_srcdir)
2001       unset(__cmake_contentDetails)
2002       unset(__cmake_arg_SOURCE_SUBDIR)
2003     endif()
2004   endforeach()
2005
2006   # Prefix will be "__fcprefix__"
2007   list(POP_BACK __cmake_fcCurrentVarsStack __cmake_original_verify_setting)
2008   string(SUBSTRING "${__cmake_original_verify_setting}"
2009     12 -1 __cmake_original_verify_setting
2010   )
2011   set(CMAKE_VERIFY_INTERFACE_HEADER_SETS ${__cmake_original_verify_setting})
2012
2013   # clear local variables to prevent leaking into the caller's scope
2014   unset(__cmake_contentName)
2015   unset(__cmake_contentNameLower)
2016   unset(__cmake_contentNameUpper)
2017   unset(__cmake_providerCommand)
2018   unset(__cmake_original_verify_setting)
2019
2020 endmacro()