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