e49faae183e0bb9b09b4a1a6f4aa4986e323f776
[platform/upstream/cmake.git] / Modules / ExternalProject.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 include_guard(GLOBAL)
5
6 #[=======================================================================[.rst:
7 ExternalProject
8 ---------------
9
10 .. only:: html
11
12    .. contents::
13
14 Commands
15 ^^^^^^^^
16
17 External Project Definition
18 """""""""""""""""""""""""""
19
20 .. command:: ExternalProject_Add
21
22   The ``ExternalProject_Add()`` function creates a custom target to drive
23   download, update/patch, configure, build, install and test steps of an
24   external project:
25
26   .. code-block:: cmake
27
28     ExternalProject_Add(<name> [<option>...])
29
30   The individual steps within the process can be driven independently if
31   required (e.g. for CDash submission) and extra custom steps can be defined,
32   along with the ability to control the step dependencies. The directory
33   structure used for the management of the external project can also be
34   customized. The function supports a large number of options which can be used
35   to tailor the external project behavior.
36
37   **Directory Options:**
38     Most of the time, the default directory layout is sufficient. It is largely
39     an implementation detail that the main project usually doesn't need to
40     change. In some circumstances, however, control over the directory layout
41     can be useful or necessary. The directory options are potentially more
42     useful from the point of view that the main build can use the
43     :command:`ExternalProject_Get_Property` command to retrieve their values,
44     thereby allowing the main project to refer to build artifacts of the
45     external project.
46
47     ``PREFIX <dir>``
48       Root directory for the external project. Unless otherwise noted below,
49       all other directories associated with the external project will be
50       created under here.
51
52     ``TMP_DIR <dir>``
53       Directory in which to store temporary files.
54
55     ``STAMP_DIR <dir>``
56       Directory in which to store the timestamps of each step. Log files from
57       individual steps are also created in here unless overridden by LOG_DIR
58       (see *Logging Options* below).
59
60     ``LOG_DIR <dir>``
61       .. versionadded:: 3.14
62
63       Directory in which to store the logs of each step.
64
65     ``DOWNLOAD_DIR <dir>``
66       Directory in which to store downloaded files before unpacking them. This
67       directory is only used by the URL download method, all other download
68       methods use ``SOURCE_DIR`` directly instead.
69
70     ``SOURCE_DIR <dir>``
71       Source directory into which downloaded contents will be unpacked, or for
72       non-URL download methods, the directory in which the repository should be
73       checked out, cloned, etc. If no download method is specified, this must
74       point to an existing directory where the external project has already
75       been unpacked or cloned/checked out.
76
77       .. note::
78          If a download method is specified, any existing contents of the source
79          directory may be deleted. Only the URL download method checks whether
80          this directory is either missing or empty before initiating the
81          download, stopping with an error if it is not empty. All other
82          download methods silently discard any previous contents of the source
83          directory.
84
85     ``BINARY_DIR <dir>``
86       Specify the build directory location. This option is ignored if
87       ``BUILD_IN_SOURCE`` is enabled.
88
89     ``INSTALL_DIR <dir>``
90       Installation prefix to be placed in the ``<INSTALL_DIR>`` placeholder.
91       This does not actually configure the external project to install to
92       the given prefix. That must be done by passing appropriate arguments
93       to the external project configuration step, e.g. using ``<INSTALL_DIR>``.
94
95     If any of the above ``..._DIR`` options are not specified, their defaults
96     are computed as follows. If the ``PREFIX`` option is given or the
97     ``EP_PREFIX`` directory property is set, then an external project is built
98     and installed under the specified prefix::
99
100       TMP_DIR      = <prefix>/tmp
101       STAMP_DIR    = <prefix>/src/<name>-stamp
102       DOWNLOAD_DIR = <prefix>/src
103       SOURCE_DIR   = <prefix>/src/<name>
104       BINARY_DIR   = <prefix>/src/<name>-build
105       INSTALL_DIR  = <prefix>
106       LOG_DIR      = <STAMP_DIR>
107
108     Otherwise, if the ``EP_BASE`` directory property is set then components
109     of an external project are stored under the specified base::
110
111       TMP_DIR      = <base>/tmp/<name>
112       STAMP_DIR    = <base>/Stamp/<name>
113       DOWNLOAD_DIR = <base>/Download/<name>
114       SOURCE_DIR   = <base>/Source/<name>
115       BINARY_DIR   = <base>/Build/<name>
116       INSTALL_DIR  = <base>/Install/<name>
117       LOG_DIR      = <STAMP_DIR>
118
119     If no ``PREFIX``, ``EP_PREFIX``, or ``EP_BASE`` is specified, then the
120     default is to set ``PREFIX`` to ``<name>-prefix``. Relative paths are
121     interpreted with respect to :variable:`CMAKE_CURRENT_BINARY_DIR` at the
122     point where ``ExternalProject_Add()`` is called.
123
124   **Download Step Options:**
125     A download method can be omitted if the ``SOURCE_DIR`` option is used to
126     point to an existing non-empty directory. Otherwise, one of the download
127     methods below must be specified (multiple download methods should not be
128     given) or a custom ``DOWNLOAD_COMMAND`` provided.
129
130     ``DOWNLOAD_COMMAND <cmd>...``
131       Overrides the command used for the download step
132       (:manual:`generator expressions <cmake-generator-expressions(7)>` are
133       supported). If this option is specified, all other download options will
134       be ignored. Providing an empty string for ``<cmd>`` effectively disables
135       the download step.
136
137     *URL Download*
138       ``URL <url1> [<url2>...]``
139         List of paths and/or URL(s) of the external project's source. When more
140         than one URL is given, they are tried in turn until one succeeds. A URL
141         may be an ordinary path in the local file system (in which case it
142         must be the only URL provided) or any downloadable URL supported by the
143         :command:`file(DOWNLOAD)` command. A local filesystem path may refer to
144         either an existing directory or to an archive file, whereas a URL is
145         expected to point to a file which can be treated as an archive. When an
146         archive is used, it will be unpacked automatically unless the
147         ``DOWNLOAD_NO_EXTRACT`` option is set to prevent it. The archive type
148         is determined by inspecting the actual content rather than using logic
149         based on the file extension.
150
151         .. versionchanged:: 3.7
152           Multiple URLs are allowed.
153
154       ``URL_HASH <algo>=<hashValue>``
155         Hash of the archive file to be downloaded. The argument should be of
156         the form ``<algo>=<hashValue>`` where ``algo`` can be any of the hashing
157         algorithms supported by the :command:`file()` command. Specifying this
158         option is strongly recommended for URL downloads, as it ensures the
159         integrity of the downloaded content. It is also used as a check for a
160         previously downloaded file, allowing connection to the remote location
161         to be avoided altogether if the local directory already has a file from
162         an earlier download that matches the specified hash.
163
164       ``URL_MD5 <md5>``
165         Equivalent to ``URL_HASH MD5=<md5>``.
166
167       ``DOWNLOAD_NAME <fname>``
168         File name to use for the downloaded file. If not given, the end of the
169         URL is used to determine the file name. This option is rarely needed,
170         the default name is generally suitable and is not normally used outside
171         of code internal to the ``ExternalProject`` module.
172
173       ``DOWNLOAD_NO_EXTRACT <bool>``
174         .. versionadded:: 3.6
175
176         Allows the extraction part of the download step to be disabled by
177         passing a boolean true value for this option. If this option is not
178         given, the downloaded contents will be unpacked automatically if
179         required. If extraction has been disabled, the full path to the
180         downloaded file is available as ``<DOWNLOADED_FILE>`` in subsequent
181         steps or as the property ``DOWNLOADED_FILE`` with the
182         :command:`ExternalProject_Get_Property` command.
183
184       ``DOWNLOAD_NO_PROGRESS <bool>``
185         Can be used to disable logging the download progress. If this option is
186         not given, download progress messages will be logged.
187
188       ``TIMEOUT <seconds>``
189         Maximum time allowed for file download operations.
190
191       ``INACTIVITY_TIMEOUT <seconds>``
192         .. versionadded:: 3.19
193
194         Terminate the operation after a period of inactivity.
195
196       ``HTTP_USERNAME <username>``
197         .. versionadded:: 3.7
198
199         Username for the download operation if authentication is required.
200
201       ``HTTP_PASSWORD <password>``
202         .. versionadded:: 3.7
203
204         Password for the download operation if authentication is required.
205
206       ``HTTP_HEADER <header1> [<header2>...]``
207         .. versionadded:: 3.7
208
209         Provides an arbitrary list of HTTP headers for the download operation.
210         This can be useful for accessing content in systems like AWS, etc.
211
212       ``TLS_VERIFY <bool>``
213         Specifies whether certificate verification should be performed for
214         https URLs. If this option is not provided, the default behavior is
215         determined by the :variable:`CMAKE_TLS_VERIFY` variable (see
216         :command:`file(DOWNLOAD)`). If that is also not set, certificate
217         verification will not be performed. In situations where ``URL_HASH``
218         cannot be provided, this option can be an alternative verification
219         measure.
220
221         .. versionchanged:: 3.6
222           This option also applies to ``git clone`` invocations.
223
224       ``TLS_CAINFO <file>``
225         Specify a custom certificate authority file to use if ``TLS_VERIFY``
226         is enabled. If this option is not specified, the value of the
227         :variable:`CMAKE_TLS_CAINFO` variable will be used instead (see
228         :command:`file(DOWNLOAD)`)
229
230       ``NETRC <level>``
231         .. versionadded:: 3.11
232
233         Specify whether the ``.netrc`` file is to be used for operation.
234         If this option is not specified, the value of the :variable:`CMAKE_NETRC`
235         variable will be used instead (see :command:`file(DOWNLOAD)`)
236         Valid levels are:
237
238         ``IGNORED``
239           The ``.netrc`` file is ignored.
240           This is the default.
241         ``OPTIONAL``
242           The ``.netrc`` file is optional, and information in the URL
243           is preferred.  The file will be scanned to find which ever
244           information is not specified in the URL.
245         ``REQUIRED``
246           The ``.netrc`` file is required, and information in the URL
247           is ignored.
248
249       ``NETRC_FILE <file>``
250         .. versionadded:: 3.11
251
252         Specify an alternative ``.netrc`` file to the one in your home directory
253         if the ``NETRC`` level is ``OPTIONAL`` or ``REQUIRED``. If this option
254         is not specified, the value of the :variable:`CMAKE_NETRC_FILE` variable
255         will be used instead (see :command:`file(DOWNLOAD)`)
256
257       .. versionadded:: 3.1
258         Added support for `tbz2`, `.tar.xz`, `.txz`, and `.7z` extensions.
259
260     *Git*
261       NOTE: A git version of 1.6.5 or later is required if this download method
262       is used.
263
264       ``GIT_REPOSITORY <url>``
265         URL of the git repository. Any URL understood by the ``git`` command
266         may be used.
267
268       ``GIT_TAG <tag>``
269         Git branch name, tag or commit hash. Note that branch names and tags
270         should generally be specified as remote names (i.e. ``origin/myBranch``
271         rather than simply ``myBranch``). This ensures that if the remote end
272         has its tag moved or branch rebased or history rewritten, the local
273         clone will still be updated correctly. In general, however, specifying
274         a commit hash should be preferred for a number of reasons:
275
276         - If the local clone already has the commit corresponding to the hash,
277           no ``git fetch`` needs to be performed to check for changes each time
278           CMake is re-run. This can result in a significant speed up if many
279           external projects are being used.
280         - Using a specific git hash ensures that the main project's own history
281           is fully traceable to a specific point in the external project's
282           evolution. If a branch or tag name is used instead, then checking out
283           a specific commit of the main project doesn't necessarily pin the
284           whole build to a specific point in the life of the external project.
285           The lack of such deterministic behavior makes the main project lose
286           traceability and repeatability.
287
288         If ``GIT_SHALLOW`` is enabled then ``GIT_TAG`` works only with
289         branch names and tags.  A commit hash is not allowed.
290
291       ``GIT_REMOTE_NAME <name>``
292         The optional name of the remote. If this option is not specified, it
293         defaults to ``origin``.
294
295       ``GIT_SUBMODULES <module>...``
296         Specific git submodules that should also be updated. If this option is
297         not provided, all git submodules will be updated.
298
299         .. versionchanged:: 3.16
300           When :policy:`CMP0097` is set to ``NEW``, if this value is set
301           to an empty string then no submodules are initialized or updated.
302
303       ``GIT_SUBMODULES_RECURSE <bool>``
304         .. versionadded:: 3.17
305
306         Specify whether git submodules (if any) should update recursively by
307         passing the ``--recursive`` flag to ``git submodule update``.
308         If not specified, the default is on.
309
310       ``GIT_SHALLOW <bool>``
311         .. versionadded:: 3.6
312
313         When this option is enabled, the ``git clone`` operation will be given
314         the ``--depth 1`` option. This performs a shallow clone, which avoids
315         downloading the whole history and instead retrieves just the commit
316         denoted by the ``GIT_TAG`` option.
317
318       ``GIT_PROGRESS <bool>``
319         .. versionadded:: 3.8
320
321         When enabled, this option instructs the ``git clone`` operation to
322         report its progress by passing it the ``--progress`` option. Without
323         this option, the clone step for large projects may appear to make the
324         build stall, since nothing will be logged until the clone operation
325         finishes. While this option can be used to provide progress to prevent
326         the appearance of the build having stalled, it may also make the build
327         overly noisy if lots of external projects are used.
328
329       ``GIT_CONFIG <option1> [<option2>...]``
330         .. versionadded:: 3.8
331
332         Specify a list of config options to pass to ``git clone``. Each option
333         listed will be transformed into its own ``--config <option>`` on the
334         ``git clone`` command line, with each option required to be in the
335         form ``key=value``.
336
337       ``GIT_REMOTE_UPDATE_STRATEGY <strategy>``
338         .. versionadded:: 3.18
339
340         When ``GIT_TAG`` refers to a remote branch, this option can be used to
341         specify how the update step behaves.  The ``<strategy>`` must be one of
342         the following:
343
344         ``CHECKOUT``
345           Ignore the local branch and always checkout the branch specified by
346           ``GIT_TAG``.
347
348         ``REBASE``
349           Try to rebase the current branch to the one specified by ``GIT_TAG``.
350           If there are local uncommitted changes, they will be stashed first
351           and popped again after rebasing.  If rebasing or popping stashed
352           changes fail, abort the rebase and halt with an error.
353           When ``GIT_REMOTE_UPDATE_STRATEGY`` is not present, this is the
354           default strategy unless the default has been overridden with
355           ``CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY`` (see below).
356
357         ``REBASE_CHECKOUT``
358           Same as ``REBASE`` except if the rebase fails, an annotated tag will
359           be created at the original ``HEAD`` position from before the rebase
360           and then checkout ``GIT_TAG`` just like the ``CHECKOUT`` strategy.
361           The message stored on the annotated tag will give information about
362           what was attempted and the tag name will include a timestamp so that
363           each failed run will add a new tag.  This strategy ensures no changes
364           will be lost, but updates should always succeed if ``GIT_TAG`` refers
365           to a valid ref unless there are uncommitted changes that cannot be
366           popped successfully.
367
368         The variable ``CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY`` can be set to
369         override the default strategy.  This variable should not be set by a
370         project, it is intended for the user to set.  It is primarily intended
371         for use in continuous integration scripts to ensure that when history
372         is rewritten on a remote branch, the build doesn't end up with unintended
373         changes or failed builds resulting from conflicts during rebase operations.
374
375     *Subversion*
376       ``SVN_REPOSITORY <url>``
377         URL of the Subversion repository.
378
379       ``SVN_REVISION -r<rev>``
380         Revision to checkout from the Subversion repository.
381
382       ``SVN_USERNAME <username>``
383         Username for the Subversion checkout and update.
384
385       ``SVN_PASSWORD <password>``
386         Password for the Subversion checkout and update.
387
388       ``SVN_TRUST_CERT <bool>``
389         Specifies whether to trust the Subversion server site certificate. If
390         enabled, the ``--trust-server-cert`` option is passed to the ``svn``
391         checkout and update commands.
392
393     *Mercurial*
394       ``HG_REPOSITORY <url>``
395         URL of the mercurial repository.
396
397       ``HG_TAG <tag>``
398         Mercurial branch name, tag or commit id.
399
400     *CVS*
401       ``CVS_REPOSITORY <cvsroot>``
402         CVSROOT of the CVS repository.
403
404       ``CVS_MODULE <mod>``
405         Module to checkout from the CVS repository.
406
407       ``CVS_TAG <tag>``
408         Tag to checkout from the CVS repository.
409
410   **Update/Patch Step Options:**
411     Whenever CMake is re-run, by default the external project's sources will be
412     updated if the download method supports updates (e.g. a git repository
413     would be checked if the ``GIT_TAG`` does not refer to a specific commit).
414
415     ``UPDATE_COMMAND <cmd>...``
416       Overrides the download method's update step with a custom command.
417       The command may use
418       :manual:`generator expressions <cmake-generator-expressions(7)>`.
419
420     ``UPDATE_DISCONNECTED <bool>``
421       .. versionadded:: 3.2
422
423       When enabled, this option causes the update step to be skipped. It does
424       not, however, prevent the download step. The update step can still be
425       added as a step target (see :command:`ExternalProject_Add_StepTargets`)
426       and called manually. This is useful if you want to allow developers to
427       build the project when disconnected from the network (the network may
428       still be needed for the download step though).
429
430       When this option is present, it is generally advisable to make the value
431       a cache variable under the developer's control rather than hard-coding
432       it. If this option is not present, the default value is taken from the
433       ``EP_UPDATE_DISCONNECTED`` directory property. If that is also not
434       defined, updates are performed as normal. The ``EP_UPDATE_DISCONNECTED``
435       directory property is intended as a convenience for controlling the
436       ``UPDATE_DISCONNECTED`` behavior for an entire section of a project's
437       directory hierarchy and may be a more convenient method of giving
438       developers control over whether or not to perform updates (assuming the
439       project also provides a cache variable or some other convenient method
440       for setting the directory property).
441
442       This may cause a step target to be created automatically for the
443       ``download`` step.  See policy :policy:`CMP0114`.
444
445     ``PATCH_COMMAND <cmd>...``
446       Specifies a custom command to patch the sources after an update. By
447       default, no patch command is defined. Note that it can be quite difficult
448       to define an appropriate patch command that performs robustly, especially
449       for download methods such as git where changing the ``GIT_TAG`` will not
450       discard changes from a previous patch, but the patch command will be
451       called again after updating to the new tag.
452
453   **Configure Step Options:**
454     The configure step is run after the download and update steps. By default,
455     the external project is assumed to be a CMake project, but this can be
456     overridden if required.
457
458     ``CONFIGURE_COMMAND <cmd>...``
459       The default configure command runs CMake with a few options based on
460       the main project.  The options added are typically only those needed to
461       use the same generator as the main project, but the ``CMAKE_GENERATOR``
462       option can be given to override this.  The project is responsible for
463       adding any toolchain details, flags or other settings it wants to
464       re-use from the main project or otherwise specify (see ``CMAKE_ARGS``,
465       ``CMAKE_CACHE_ARGS`` and ``CMAKE_CACHE_DEFAULT_ARGS`` below).
466
467       For non-CMake external projects, the ``CONFIGURE_COMMAND`` option must
468       be used to override the default configure command
469       (:manual:`generator expressions <cmake-generator-expressions(7)>` are
470       supported). For projects that require no configure step, specify this
471       option with an empty string as the command to execute.
472
473     ``CMAKE_COMMAND /.../cmake``
474       Specify an alternative cmake executable for the configure step (use an
475       absolute path). This is generally not recommended, since it is
476       usually desirable to use the same CMake version throughout the whole
477       build. This option is ignored if a custom configure command has been
478       specified with ``CONFIGURE_COMMAND``.
479
480     ``CMAKE_GENERATOR <gen>``
481       Override the CMake generator used for the configure step. Without this
482       option, the same generator as the main build will be used. This option is
483       ignored if a custom configure command has been specified with the
484       ``CONFIGURE_COMMAND`` option.
485
486     ``CMAKE_GENERATOR_PLATFORM <platform>``
487       .. versionadded:: 3.1
488
489       Pass a generator-specific platform name to the CMake command (see
490       :variable:`CMAKE_GENERATOR_PLATFORM`). It is an error to provide this
491       option without the ``CMAKE_GENERATOR`` option.
492
493     ``CMAKE_GENERATOR_TOOLSET <toolset>``
494       Pass a generator-specific toolset name to the CMake command (see
495       :variable:`CMAKE_GENERATOR_TOOLSET`). It is an error to provide this
496       option without the ``CMAKE_GENERATOR`` option.
497
498     ``CMAKE_GENERATOR_INSTANCE <instance>``
499       .. versionadded:: 3.11
500
501       Pass a generator-specific instance selection to the CMake command (see
502       :variable:`CMAKE_GENERATOR_INSTANCE`). It is an error to provide this
503       option without the ``CMAKE_GENERATOR`` option.
504
505     ``CMAKE_ARGS <arg>...``
506       The specified arguments are passed to the ``cmake`` command line. They
507       can be any argument the ``cmake`` command understands, not just cache
508       values defined by ``-D...`` arguments (see also
509       :manual:`CMake Options <cmake(1)>`).
510
511       .. versionadded:: 3.3
512         Arguments may use :manual:`generator expressions <cmake-generator-expressions(7)>`.
513
514     ``CMAKE_CACHE_ARGS <arg>...``
515       This is an alternate way of specifying cache variables where command line
516       length issues may become a problem. The arguments are expected to be in
517       the form ``-Dvar:STRING=value``, which are then transformed into
518       CMake :command:`set` commands with the ``FORCE`` option used. These
519       ``set()`` commands are written to a pre-load script which is then applied
520       using the :manual:`cmake -C <cmake(1)>` command line option.
521
522       .. versionadded:: 3.3
523         Arguments may use :manual:`generator expressions <cmake-generator-expressions(7)>`.
524
525     ``CMAKE_CACHE_DEFAULT_ARGS <arg>...``
526       .. versionadded:: 3.2
527
528       This is the same as the ``CMAKE_CACHE_ARGS`` option except the ``set()``
529       commands do not include the ``FORCE`` keyword. This means the values act
530       as initial defaults only and will not override any variables already set
531       from a previous run. Use this option with care, as it can lead to
532       different behavior depending on whether the build starts from a fresh
533       build directory or re-uses previous build contents.
534
535       .. versionadded:: 3.15
536         If the CMake generator is the ``Green Hills MULTI`` and not overridden then
537         the original project's settings for the GHS toolset and target system
538         customization cache variables are propagated into the external project.
539
540     ``SOURCE_SUBDIR <dir>``
541       .. versionadded:: 3.7
542
543       When no ``CONFIGURE_COMMAND`` option is specified, the configure step
544       assumes the external project has a ``CMakeLists.txt`` file at the top of
545       its source tree (i.e. in ``SOURCE_DIR``). The ``SOURCE_SUBDIR`` option
546       can be used to point to an alternative directory within the source tree
547       to use as the top of the CMake source tree instead. This must be a
548       relative path and it will be interpreted as being relative to
549       ``SOURCE_DIR``.
550
551       .. versionadded:: 3.14
552         When ``BUILD_IN_SOURCE`` option is enabled, the ``BUILD_COMMAND``
553         is used to point to an alternative directory within the source tree.
554
555     ``CONFIGURE_HANDLED_BY_BUILD <bool>``
556       .. versionadded:: 3.20
557
558       Enabling this option relaxes the dependencies of the configure step on
559       other external projects to order-only. This means the configure step will
560       be executed after its external project dependencies are built but it will
561       not be marked dirty when one of its external project dependencies is
562       rebuilt. This option can be enabled when the build step is smart enough
563       to figure out if the configure step needs to be rerun. CMake and Meson are
564       examples of build systems whose build step is smart enough to know if the
565       configure step needs to be rerun.
566
567   **Build Step Options:**
568     If the configure step assumed the external project uses CMake as its build
569     system, the build step will also. Otherwise, the build step will assume a
570     Makefile-based build and simply run ``make`` with no arguments as the
571     default build step. This can be overridden with custom build commands if
572     required.
573
574     If both the main project and the external project use make as their build
575     tool, the build step of the external project is invoked as a recursive
576     make using ``$(MAKE)``.  This will communicate some build tool settings
577     from the main project to the external project.  If either the main project
578     or external project is not using make, no build tool settings will be
579     passed to the external project other than those established by the
580     configure step (i.e. running ``ninja -v`` in the main project will not
581     pass ``-v`` to the external project's build step, even if it also uses
582     ``ninja`` as its build tool).
583
584     ``BUILD_COMMAND <cmd>...``
585       Overrides the default build command
586       (:manual:`generator expressions <cmake-generator-expressions(7)>` are
587       supported). If this option is not given, the default build command will
588       be chosen to integrate with the main build in the most appropriate way
589       (e.g. using recursive ``make`` for Makefile generators or
590       ``cmake --build`` if the project uses a CMake build). This option can be
591       specified with an empty string as the command to make the build step do
592       nothing.
593
594     ``BUILD_IN_SOURCE <bool>``
595       When this option is enabled, the build will be done directly within the
596       external project's source tree. This should generally be avoided, the use
597       of a separate build directory is usually preferred, but it can be useful
598       when the external project assumes an in-source build. The ``BINARY_DIR``
599       option should not be specified if building in-source.
600
601     ``BUILD_ALWAYS <bool>``
602       Enabling this option forces the build step to always be run. This can be
603       the easiest way to robustly ensure that the external project's own build
604       dependencies are evaluated rather than relying on the default
605       success timestamp-based method. This option is not normally needed unless
606       developers are expected to modify something the external project's build
607       depends on in a way that is not detectable via the step target
608       dependencies (e.g. ``SOURCE_DIR`` is used without a download method and
609       developers might modify the sources in ``SOURCE_DIR``).
610
611     ``BUILD_BYPRODUCTS <file>...``
612       .. versionadded:: 3.2
613
614       Specifies files that will be generated by the build command but which
615       might or might not have their modification time updated by subsequent
616       builds. These ultimately get passed through as ``BYPRODUCTS`` to the
617       build step's own underlying call to :command:`add_custom_command`.
618
619   **Install Step Options:**
620     If the configure step assumed the external project uses CMake as its build
621     system, the install step will also. Otherwise, the install step will assume
622     a Makefile-based build and simply run ``make install`` as the default build
623     step. This can be overridden with custom install commands if required.
624
625     ``INSTALL_COMMAND <cmd>...``
626       The external project's own install step is invoked as part of the main
627       project's *build*. It is done after the external project's build step
628       and may be before or after the external project's test step (see the
629       ``TEST_BEFORE_INSTALL`` option below). The external project's install
630       rules are not part of the main project's install rules, so if anything
631       from the external project should be installed as part of the main build,
632       these need to be specified in the main build as additional
633       :command:`install` commands. The default install step builds the
634       ``install`` target of the external project, but this can be overridden
635       with a custom command using this option
636       (:manual:`generator expressions <cmake-generator-expressions(7)>` are
637       supported). Passing an empty string as the ``<cmd>`` makes the install
638       step do nothing.
639
640   **Test Step Options:**
641     The test step is only defined if at least one of the following ``TEST_...``
642     options are provided.
643
644     ``TEST_COMMAND <cmd>...``
645       Overrides the default test command
646       (:manual:`generator expressions <cmake-generator-expressions(7)>` are
647       supported). If this option is not given, the default behavior of the test
648       step is to build the external project's own ``test`` target. This option
649       can be specified with ``<cmd>`` as an empty string, which allows the test
650       step to still be defined, but it will do nothing. Do not specify any of
651       the other ``TEST_...`` options if providing an empty string as the test
652       command, but prefer to omit all ``TEST_...`` options altogether if the
653       test step target is not needed.
654
655     ``TEST_BEFORE_INSTALL <bool>``
656       When this option is enabled, the test step will be executed before the
657       install step. The default behavior is for the test step to run after the
658       install step.
659
660     ``TEST_AFTER_INSTALL <bool>``
661       This option is mainly useful as a way to indicate that the test step is
662       desired but all default behavior is sufficient. Specifying this option
663       with a boolean true value ensures the test step is defined and that it
664       comes after the install step. If both ``TEST_BEFORE_INSTALL`` and
665       ``TEST_AFTER_INSTALL`` are enabled, the latter is silently ignored.
666
667     ``TEST_EXCLUDE_FROM_MAIN <bool>``
668       .. versionadded:: 3.2
669
670       If enabled, the main build's default ALL target will not depend on the
671       test step. This can be a useful way of ensuring the test step is defined
672       but only gets invoked when manually requested.
673       This may cause a step target to be created automatically for either
674       the ``install`` or ``build`` step.  See policy :policy:`CMP0114`.
675
676   **Output Logging Options:**
677     Each of the following ``LOG_...`` options can be used to wrap the relevant
678     step in a script to capture its output to files. The log files will be
679     created in ``LOG_DIR`` if supplied or otherwise the ``STAMP_DIR``
680     directory with step-specific file names.
681
682     ``LOG_DOWNLOAD <bool>``
683       When enabled, the output of the download step is logged to files.
684
685     ``LOG_UPDATE <bool>``
686       When enabled, the output of the update step is logged to files.
687
688     ``LOG_PATCH <bool>``
689       .. versionadded:: 3.14
690
691       When enabled, the output of the patch step is logged to files.
692
693     ``LOG_CONFIGURE <bool>``
694       When enabled, the output of the configure step is logged to files.
695
696     ``LOG_BUILD <bool>``
697       When enabled, the output of the build step is logged to files.
698
699     ``LOG_INSTALL <bool>``
700       When enabled, the output of the install step is logged to files.
701
702     ``LOG_TEST <bool>``
703       When enabled, the output of the test step is logged to files.
704
705     ``LOG_MERGED_STDOUTERR <bool>``
706       .. versionadded:: 3.14
707
708       When enabled, stdout and stderr will be merged for any step whose
709       output is being logged to files.
710
711     ``LOG_OUTPUT_ON_FAILURE <bool>``
712       .. versionadded:: 3.14
713
714       This option only has an effect if at least one of the other ``LOG_<step>``
715       options is enabled.  If an error occurs for a step which has logging to
716       file enabled, that step's output will be printed to the console if
717       ``LOG_OUTPUT_ON_FAILURE`` is set to true.  For cases where a large amount
718       of output is recorded, just the end of that output may be printed to the
719       console.
720
721   **Terminal Access Options:**
722     .. versionadded:: 3.4
723
724     Steps can be given direct access to the terminal in some cases. Giving a
725     step access to the terminal may allow it to receive terminal input if
726     required, such as for authentication details not provided by other options.
727     With the :generator:`Ninja` generator, these options place the steps in the
728     ``console`` :prop_gbl:`job pool <JOB_POOLS>`. Each step can be given access
729     to the terminal individually via the following options:
730
731     ``USES_TERMINAL_DOWNLOAD <bool>``
732       Give the download step access to the terminal.
733
734     ``USES_TERMINAL_UPDATE <bool>``
735       Give the update step access to the terminal.
736
737     ``USES_TERMINAL_CONFIGURE <bool>``
738       Give the configure step access to the terminal.
739
740     ``USES_TERMINAL_BUILD <bool>``
741       Give the build step access to the terminal.
742
743     ``USES_TERMINAL_INSTALL <bool>``
744       Give the install step access to the terminal.
745
746     ``USES_TERMINAL_TEST <bool>``
747       Give the test step access to the terminal.
748
749   **Target Options:**
750     ``DEPENDS <targets>...``
751       Specify other targets on which the external project depends. The other
752       targets will be brought up to date before any of the external project's
753       steps are executed. Because the external project uses additional custom
754       targets internally for each step, the ``DEPENDS`` option is the most
755       convenient way to ensure all of those steps depend on the other targets.
756       Simply doing
757       :command:`add_dependencies(\<name\> \<targets\>) <add_dependencies>` will
758       not make any of the steps dependent on ``<targets>``.
759
760     ``EXCLUDE_FROM_ALL <bool>``
761       When enabled, this option excludes the external project from the default
762       ALL target of the main build.
763
764     ``STEP_TARGETS <step-target>...``
765       Generate custom targets for the specified steps. This is required if the
766       steps need to be triggered manually or if they need to be used as
767       dependencies of other targets. If this option is not specified, the
768       default value is taken from the ``EP_STEP_TARGETS`` directory property.
769       See :command:`ExternalProject_Add_StepTargets` below for further
770       discussion of the effects of this option.
771
772     ``INDEPENDENT_STEP_TARGETS <step-target>...``
773       .. deprecated:: 3.19
774         This is allowed only if policy :policy:`CMP0114` is not set to ``NEW``.
775
776       Generates custom targets for the specified steps and prevent these targets
777       from having the usual dependencies applied to them. If this option is not
778       specified, the default value is taken from the
779       ``EP_INDEPENDENT_STEP_TARGETS`` directory property. This option is mostly
780       useful for allowing individual steps to be driven independently, such as
781       for a CDash setup where each step should be initiated and reported
782       individually rather than as one whole build. See
783       :command:`ExternalProject_Add_StepTargets` below for further discussion
784       of the effects of this option.
785
786   **Miscellaneous Options:**
787     ``LIST_SEPARATOR <sep>``
788       For any of the various ``..._COMMAND`` options, replace ``;`` with
789       ``<sep>`` in the specified command lines. This can be useful where list
790       variables may be given in commands where they should end up as
791       space-separated arguments (``<sep>`` would be a single space character
792       string in this case).
793
794     ``COMMAND <cmd>...``
795       Any of the other ``..._COMMAND`` options can have additional commands
796       appended to them by following them with as many ``COMMAND ...`` options
797       as needed
798       (:manual:`generator expressions <cmake-generator-expressions(7)>` are
799       supported). For example:
800
801       .. code-block:: cmake
802
803         ExternalProject_Add(example
804           ... # Download options, etc.
805           BUILD_COMMAND ${CMAKE_COMMAND} -E echo "Starting $<CONFIG> build"
806           COMMAND       ${CMAKE_COMMAND} --build <BINARY_DIR> --config $<CONFIG>
807           COMMAND       ${CMAKE_COMMAND} -E echo "$<CONFIG> build complete"
808         )
809
810   It should also be noted that each build step is created via a call to
811   :command:`ExternalProject_Add_Step`. See that command's documentation for the
812   automatic substitutions that are supported for some options.
813
814 Obtaining Project Properties
815 """"""""""""""""""""""""""""
816
817 .. command:: ExternalProject_Get_Property
818
819   The ``ExternalProject_Get_Property()`` function retrieves external project
820   target properties:
821
822   .. code-block:: cmake
823
824     ExternalProject_Get_Property(<name> <prop1> [<prop2>...])
825
826   The function stores property values in variables of the same name. Property
827   names correspond to the keyword argument names of ``ExternalProject_Add()``.
828   For example, the source directory might be retrieved like so:
829
830   .. code-block:: cmake
831
832     ExternalProject_Get_property(myExtProj SOURCE_DIR)
833     message("Source dir of myExtProj = ${SOURCE_DIR}")
834
835 Explicit Step Management
836 """"""""""""""""""""""""
837
838 The ``ExternalProject_Add()`` function on its own is often sufficient for
839 incorporating an external project into the main build. Certain scenarios
840 require additional work to implement desired behavior, such as adding in a
841 custom step or making steps available as manually triggerable targets. The
842 ``ExternalProject_Add_Step()``, ``ExternalProject_Add_StepTargets()`` and
843 ``ExternalProject_Add_StepDependencies`` functions provide the lower level
844 control needed to implement such step-level capabilities.
845
846 .. command:: ExternalProject_Add_Step
847
848   The ``ExternalProject_Add_Step()`` function specifies an additional custom
849   step for an external project defined by an earlier call to
850   :command:`ExternalProject_Add`:
851
852   .. code-block:: cmake
853
854     ExternalProject_Add_Step(<name> <step> [<option>...])
855
856   ``<name>`` is the same as the name passed to the original call to
857   :command:`ExternalProject_Add`. The specified ``<step>`` must not be one of
858   the pre-defined steps (``mkdir``, ``download``, ``update``,
859   ``patch``, ``configure``, ``build``, ``install`` or ``test``). The supported
860   options are:
861
862   ``COMMAND <cmd>...``
863     The command line to be executed by this custom step
864     (:manual:`generator expressions <cmake-generator-expressions(7)>` are
865     supported). This option can be repeated multiple times to specify multiple
866     commands to be executed in order.
867
868   ``COMMENT "<text>..."``
869     Text to be printed when the custom step executes.
870
871   ``DEPENDEES <step>...``
872     Other steps (custom or pre-defined) on which this step depends.
873
874   ``DEPENDERS <step>...``
875     Other steps (custom or pre-defined) that depend on this new custom step.
876
877   ``DEPENDS <file>...``
878     Files on which this custom step depends.
879
880   ``INDEPENDENT <bool>``
881     .. versionadded:: 3.19
882
883     Specifies whether this step is independent of the external dependencies
884     specified by the :command:`ExternalProject_Add`'s ``DEPENDS`` option.
885     The default is ``FALSE``.  Steps marked as independent may depend only
886     on other steps marked independent.  See policy :policy:`CMP0114`.
887
888     Note that this use of the term "independent" refers only to independence
889     from external targets specified by the ``DEPENDS`` option and is
890     orthogonal to a step's dependencies on other steps.
891
892     If a step target is created for an independent step by the
893     :command:`ExternalProject_Add` ``STEP_TARGETS`` option or by the
894     :command:`ExternalProject_Add_StepTargets` function, it will not depend
895     on the external targets, but may depend on targets for other steps.
896
897   ``BYPRODUCTS <file>...``
898     .. versionadded:: 3.2
899
900     Files that will be generated by this custom step but which might or might
901     not have their modification time updated by subsequent builds. This list of
902     files will ultimately be passed through as the ``BYPRODUCTS`` option to the
903     :command:`add_custom_command` used to implement the custom step internally.
904
905   ``ALWAYS <bool>``
906     When enabled, this option specifies that the custom step should always be
907     run (i.e. that it is always considered out of date).
908
909   ``EXCLUDE_FROM_MAIN <bool>``
910     When enabled, this option specifies that the external project's main target
911     does not depend on the custom step.
912     This may cause step targets to be created automatically for the steps on
913     which this step depends.  See policy :policy:`CMP0114`.
914
915   ``WORKING_DIRECTORY <dir>``
916     Specifies the working directory to set before running the custom step's
917     command. If this option is not specified, the directory will be the value
918     of the :variable:`CMAKE_CURRENT_BINARY_DIR` at the point where
919     ``ExternalProject_Add_Step()`` was called.
920
921   ``LOG <bool>``
922     If set, this causes the output from the custom step to be captured to files
923     in the external project's ``LOG_DIR`` if supplied or ``STAMP_DIR``.
924
925   ``USES_TERMINAL <bool>``
926     If enabled, this gives the custom step direct access to the terminal if
927     possible.
928
929   The command line, comment, working directory and byproducts of every
930   standard and custom step are processed to replace the tokens
931   ``<SOURCE_DIR>``, ``<SOURCE_SUBDIR>``, ``<BINARY_DIR>``, ``<INSTALL_DIR>``
932   ``<TMP_DIR>``, ``<DOWNLOAD_DIR>`` and ``<DOWNLOADED_FILE>`` with their
933   corresponding property values defined in the original call to
934   :command:`ExternalProject_Add`.
935
936   .. versionadded:: 3.3
937     Token replacement is extended to byproducts.
938
939   .. versionadded:: 3.11
940     The ``<DOWNLOAD_DIR>`` substitution token.
941
942 .. command:: ExternalProject_Add_StepTargets
943
944   The ``ExternalProject_Add_StepTargets()`` function generates targets for the
945   steps listed. The name of each created target will be of the form
946   ``<name>-<step>``:
947
948   .. code-block:: cmake
949
950     ExternalProject_Add_StepTargets(<name> <step1> [<step2>...])
951
952   Creating a target for a step allows it to be used as a dependency of another
953   target or to be triggered manually. Having targets for specific steps also
954   allows them to be driven independently of each other by specifying targets on
955   build command lines. For example, you may be submitting to a sub-project
956   based dashboard where you want to drive the configure portion of the build,
957   then submit to the dashboard, followed by the build portion, followed
958   by tests. If you invoke a custom target that depends on a step halfway
959   through the step dependency chain, then all the previous steps will also run
960   to ensure everything is up to date.
961
962   Internally, :command:`ExternalProject_Add` calls
963   :command:`ExternalProject_Add_Step` to create each step. If any
964   ``STEP_TARGETS`` were specified, then ``ExternalProject_Add_StepTargets()``
965   will also be called after :command:`ExternalProject_Add_Step`.  Even if a
966   step is not mentioned in the ``STEP_TARGETS`` option,
967   ``ExternalProject_Add_StepTargets()`` can still be called later to manually
968   define a target for the step.
969
970   The ``STEP_TARGETS`` option for :command:`ExternalProject_Add` is generally
971   the easiest way to ensure targets are created for specific steps of interest.
972   For custom steps, ``ExternalProject_Add_StepTargets()`` must be called
973   explicitly if a target should also be created for that custom step.
974   An alternative to these two options is to populate the ``EP_STEP_TARGETS``
975   directory property.  It acts as a default for the step target options and
976   can save having to repeatedly specify the same set of step targets when
977   multiple external projects are being defined.
978
979   .. versionadded:: 3.19
980     If :policy:`CMP0114` is set to ``NEW``, step targets are fully responsible
981     for holding the custom commands implementing their steps.  The primary target
982     created by ``ExternalProject_Add`` depends on the step targets, and the
983     step targets depend on each other.  The target-level dependencies match
984     the file-level dependencies used by the custom commands for each step.
985     The targets for steps created with :command:`ExternalProject_Add_Step`'s
986     ``INDEPENDENT`` option do not depend on the external targets specified
987     by :command:`ExternalProject_Add`'s ``DEPENDS`` option.  The predefined
988     steps ``mkdir``, ``download``, ``update``, and ``patch`` are independent.
989
990   If :policy:`CMP0114` is not ``NEW``, the following deprecated behavior
991   is available:
992
993   * A deprecated ``NO_DEPENDS`` option may be specified immediately after the
994     ``<name>`` and before the first step.
995     If the ``NO_DEPENDS`` option is specified, the step target will not depend on
996     the dependencies of the external project (i.e. on any dependencies of the
997     ``<name>`` custom target created by :command:`ExternalProject_Add`). This is
998     usually safe for the ``download``, ``update`` and ``patch`` steps, since they
999     do not typically require that the dependencies are updated and built. Using
1000     ``NO_DEPENDS`` for any of the other pre-defined steps, however, may break
1001     parallel builds. Only use ``NO_DEPENDS`` where it is certain that the named
1002     steps genuinely do not have dependencies. For custom steps, consider whether
1003     or not the custom commands require the dependencies to be configured, built
1004     and installed.
1005
1006   * The ``INDEPENDENT_STEP_TARGETS`` option for :command:`ExternalProject_Add`,
1007     or the ``EP_INDEPENDENT_STEP_TARGETS`` directory property, tells the
1008     function to call ``ExternalProject_Add_StepTargets()`` internally
1009     using the ``NO_DEPENDS`` option for the specified steps.
1010
1011 .. command:: ExternalProject_Add_StepDependencies
1012
1013   .. versionadded:: 3.2
1014
1015   The ``ExternalProject_Add_StepDependencies()`` function can be used to add
1016   dependencies to a step. The dependencies added must be targets CMake already
1017   knows about (these can be ordinary executable or library targets, custom
1018   targets or even step targets of another external project):
1019
1020   .. code-block:: cmake
1021
1022     ExternalProject_Add_StepDependencies(<name> <step> <target1> [<target2>...])
1023
1024   This function takes care to set both target and file level dependencies and
1025   will ensure that parallel builds will not break. It should be used instead of
1026   :command:`add_dependencies` whenever adding a dependency for some of the step
1027   targets generated by the ``ExternalProject`` module.
1028
1029 Examples
1030 ^^^^^^^^
1031
1032 The following example shows how to download and build a hypothetical project
1033 called *FooBar* from github:
1034
1035 .. code-block:: cmake
1036
1037   include(ExternalProject)
1038   ExternalProject_Add(foobar
1039     GIT_REPOSITORY    git@github.com:FooCo/FooBar.git
1040     GIT_TAG           origin/release/1.2.3
1041   )
1042
1043 For the sake of the example, also define a second hypothetical external project
1044 called *SecretSauce*, which is downloaded from a web server. Two URLs are given
1045 to take advantage of a faster internal network if available, with a fallback to
1046 a slower external server. The project is a typical ``Makefile`` project with no
1047 configure step, so some of the default commands are overridden. The build is
1048 only required to build the *sauce* target:
1049
1050 .. code-block:: cmake
1051
1052   find_program(MAKE_EXE NAMES gmake nmake make)
1053   ExternalProject_Add(secretsauce
1054     URL               http://intranet.somecompany.com/artifacts/sauce-2.7.tgz
1055                       https://www.somecompany.com/downloads/sauce-2.7.zip
1056     URL_HASH          MD5=d41d8cd98f00b204e9800998ecf8427e
1057     CONFIGURE_COMMAND ""
1058     BUILD_COMMAND     ${MAKE_EXE} sauce
1059   )
1060
1061 Suppose the build step of ``secretsauce`` requires that ``foobar`` must already
1062 be built. This could be enforced like so:
1063
1064 .. code-block:: cmake
1065
1066   ExternalProject_Add_StepDependencies(secretsauce build foobar)
1067
1068 Another alternative would be to create a custom target for ``foobar``'s build
1069 step and make ``secretsauce`` depend on that rather than the whole ``foobar``
1070 project. This would mean ``foobar`` only needs to be built, it doesn't need to
1071 run its install or test steps before ``secretsauce`` can be built. The
1072 dependency can also be defined along with the ``secretsauce`` project:
1073
1074 .. code-block:: cmake
1075
1076   ExternalProject_Add_StepTargets(foobar build)
1077   ExternalProject_Add(secretsauce
1078     URL               http://intranet.somecompany.com/artifacts/sauce-2.7.tgz
1079                       https://www.somecompany.com/downloads/sauce-2.7.zip
1080     URL_HASH          MD5=d41d8cd98f00b204e9800998ecf8427e
1081     CONFIGURE_COMMAND ""
1082     BUILD_COMMAND     ${MAKE_EXE} sauce
1083     DEPENDS           foobar-build
1084   )
1085
1086 Instead of calling :command:`ExternalProject_Add_StepTargets`, the target could
1087 be defined along with the ``foobar`` project itself:
1088
1089 .. code-block:: cmake
1090
1091   ExternalProject_Add(foobar
1092     GIT_REPOSITORY git@github.com:FooCo/FooBar.git
1093     GIT_TAG        origin/release/1.2.3
1094     STEP_TARGETS   build
1095   )
1096
1097 If many external projects should have the same set of step targets, setting a
1098 directory property may be more convenient. The ``build`` step target could be
1099 created automatically by setting the ``EP_STEP_TARGETS`` directory property
1100 before creating the external projects with :command:`ExternalProject_Add`:
1101
1102 .. code-block:: cmake
1103
1104   set_property(DIRECTORY PROPERTY EP_STEP_TARGETS build)
1105
1106 Lastly, suppose that ``secretsauce`` provides a script called ``makedoc`` which
1107 can be used to generate its own documentation. Further suppose that the script
1108 expects the output directory to be provided as the only parameter and that it
1109 should be run from the ``secretsauce`` source directory. A custom step and a
1110 custom target to trigger the script can be defined like so:
1111
1112 .. code-block:: cmake
1113
1114   ExternalProject_Add_Step(secretsauce docs
1115     COMMAND           <SOURCE_DIR>/makedoc <BINARY_DIR>
1116     WORKING_DIRECTORY <SOURCE_DIR>
1117     COMMENT           "Building secretsauce docs"
1118     ALWAYS            TRUE
1119     EXCLUDE_FROM_MAIN TRUE
1120   )
1121   ExternalProject_Add_StepTargets(secretsauce docs)
1122
1123 The custom step could then be triggered from the main build like so::
1124
1125   cmake --build . --target secretsauce-docs
1126
1127 #]=======================================================================]
1128
1129 cmake_policy(PUSH)
1130 cmake_policy(SET CMP0054 NEW) # if() quoted variables not dereferenced
1131 cmake_policy(SET CMP0057 NEW) # if() supports IN_LIST
1132
1133 macro(_ep_get_hash_algos out_var)
1134   set(${out_var}
1135     MD5
1136     SHA1
1137     SHA224
1138     SHA256
1139     SHA384
1140     SHA512
1141     SHA3_224
1142     SHA3_256
1143     SHA3_384
1144     SHA3_512
1145   )
1146 endmacro()
1147
1148 macro(_ep_get_hash_regex out_var)
1149   _ep_get_hash_algos(${out_var})
1150   list(JOIN ${out_var} "|" ${out_var})
1151   set(${out_var} "^(${${out_var}})=([0-9A-Fa-f]+)$")
1152 endmacro()
1153
1154 function(_ep_parse_arguments f keywords name ns args)
1155   # Transfer the arguments to this function into target properties for the
1156   # new custom target we just added so that we can set up all the build steps
1157   # correctly based on target properties.
1158   #
1159   # Because some keywords can be repeated, we can't use cmake_parse_arguments().
1160   # Instead, we loop through ARGN and consider the namespace starting with an
1161   # upper-case letter followed by at least two more upper-case letters,
1162   # numbers or underscores to be keywords.
1163
1164   set(key)
1165
1166   foreach(arg IN LISTS args)
1167     set(is_value 1)
1168
1169     if(arg MATCHES "^[A-Z][A-Z0-9_][A-Z0-9_]+$" AND
1170         NOT (("x${arg}x" STREQUAL "x${key}x") AND ("x${key}x" STREQUAL "xCOMMANDx")) AND
1171         NOT arg MATCHES "^(TRUE|FALSE)$")
1172       if(arg IN_LIST keywords)
1173         set(is_value 0)
1174       endif()
1175     endif()
1176
1177     if(is_value)
1178       if(key)
1179         # Value
1180         if(NOT arg STREQUAL "")
1181           set_property(TARGET ${name} APPEND PROPERTY ${ns}${key} "${arg}")
1182         else()
1183           get_property(have_key TARGET ${name} PROPERTY ${ns}${key} SET)
1184           if(have_key)
1185             get_property(value TARGET ${name} PROPERTY ${ns}${key})
1186             set_property(TARGET ${name} PROPERTY ${ns}${key} "${value};${arg}")
1187           else()
1188             set_property(TARGET ${name} PROPERTY ${ns}${key} "${arg}")
1189           endif()
1190         endif()
1191       else()
1192         # Missing Keyword
1193         message(AUTHOR_WARNING "value '${arg}' with no previous keyword in ${f}")
1194       endif()
1195     else()
1196       set(key "${arg}")
1197     endif()
1198   endforeach()
1199 endfunction()
1200
1201
1202 define_property(DIRECTORY PROPERTY "EP_BASE" INHERITED
1203   BRIEF_DOCS "Base directory for External Project storage."
1204   FULL_DOCS
1205   "See documentation of the ExternalProject_Add() function in the "
1206   "ExternalProject module."
1207   )
1208
1209 define_property(DIRECTORY PROPERTY "EP_PREFIX" INHERITED
1210   BRIEF_DOCS "Top prefix for External Project storage."
1211   FULL_DOCS
1212   "See documentation of the ExternalProject_Add() function in the "
1213   "ExternalProject module."
1214   )
1215
1216 define_property(DIRECTORY PROPERTY "EP_STEP_TARGETS" INHERITED
1217   BRIEF_DOCS
1218   "List of ExternalProject steps that automatically get corresponding targets"
1219   FULL_DOCS
1220   "These targets will be dependent on the main target dependencies. "
1221   "See documentation of the ExternalProject_Add_StepTargets() function in the "
1222   "ExternalProject module."
1223   )
1224
1225 define_property(DIRECTORY PROPERTY "EP_INDEPENDENT_STEP_TARGETS" INHERITED
1226   BRIEF_DOCS
1227   "List of ExternalProject steps that automatically get corresponding targets"
1228   FULL_DOCS
1229   "These targets will not be dependent on the main target dependencies. "
1230   "See documentation of the ExternalProject_Add_StepTargets() function in the "
1231   "ExternalProject module."
1232   )
1233
1234 define_property(DIRECTORY PROPERTY "EP_UPDATE_DISCONNECTED" INHERITED
1235   BRIEF_DOCS "Never update automatically from the remote repo."
1236   FULL_DOCS
1237   "See documentation of the ExternalProject_Add() function in the "
1238   "ExternalProject module."
1239   )
1240
1241 function(_ep_write_gitclone_script script_filename source_dir git_EXECUTABLE git_repository git_tag git_remote_name init_submodules git_submodules_recurse git_submodules git_shallow git_progress git_config src_name work_dir gitclone_infofile gitclone_stampfile tls_verify)
1242   if(NOT GIT_VERSION_STRING VERSION_LESS 1.8.5)
1243     # Use `git checkout <tree-ish> --` to avoid ambiguity with a local path.
1244     set(git_checkout_explicit-- "--")
1245   else()
1246     # Use `git checkout <branch>` even though this risks ambiguity with a
1247     # local path.  Unfortunately we cannot use `git checkout <tree-ish> --`
1248     # because that will not search for remote branch names, a common use case.
1249     set(git_checkout_explicit-- "")
1250   endif()
1251   if("${git_tag}" STREQUAL "")
1252     message(FATAL_ERROR "Tag for git checkout should not be empty.")
1253   endif()
1254
1255   if(GIT_VERSION_STRING VERSION_LESS 2.20 OR 2.21 VERSION_LESS_EQUAL GIT_VERSION_STRING)
1256     set(git_clone_options "--no-checkout")
1257   else()
1258     set(git_clone_options)
1259   endif()
1260   if(git_shallow)
1261     if(NOT GIT_VERSION_STRING VERSION_LESS 1.7.10)
1262       list(APPEND git_clone_options "--depth 1 --no-single-branch")
1263     else()
1264       list(APPEND git_clone_options "--depth 1")
1265     endif()
1266   endif()
1267   if(git_progress)
1268     list(APPEND git_clone_options --progress)
1269   endif()
1270   foreach(config IN LISTS git_config)
1271     list(APPEND git_clone_options --config \"${config}\")
1272   endforeach()
1273   if(NOT ${git_remote_name} STREQUAL "origin")
1274     list(APPEND git_clone_options --origin \"${git_remote_name}\")
1275   endif()
1276
1277   string (REPLACE ";" " " git_clone_options "${git_clone_options}")
1278
1279   set(git_options)
1280   # disable cert checking if explicitly told not to do it
1281   if(NOT "x${tls_verify}" STREQUAL "x" AND NOT tls_verify)
1282     set(git_options
1283       -c http.sslVerify=false)
1284   endif()
1285   string (REPLACE ";" " " git_options "${git_options}")
1286
1287   file(WRITE ${script_filename}
1288 "
1289 if(NOT \"${gitclone_infofile}\" IS_NEWER_THAN \"${gitclone_stampfile}\")
1290   message(STATUS \"Avoiding repeated git clone, stamp file is up to date: '${gitclone_stampfile}'\")
1291   return()
1292 endif()
1293
1294 execute_process(
1295   COMMAND \${CMAKE_COMMAND} -E rm -rf \"${source_dir}\"
1296   RESULT_VARIABLE error_code
1297   )
1298 if(error_code)
1299   message(FATAL_ERROR \"Failed to remove directory: '${source_dir}'\")
1300 endif()
1301
1302 # try the clone 3 times in case there is an odd git clone issue
1303 set(error_code 1)
1304 set(number_of_tries 0)
1305 while(error_code AND number_of_tries LESS 3)
1306   execute_process(
1307     COMMAND \"${git_EXECUTABLE}\" ${git_options} clone ${git_clone_options} \"${git_repository}\" \"${src_name}\"
1308     WORKING_DIRECTORY \"${work_dir}\"
1309     RESULT_VARIABLE error_code
1310     )
1311   math(EXPR number_of_tries \"\${number_of_tries} + 1\")
1312 endwhile()
1313 if(number_of_tries GREATER 1)
1314   message(STATUS \"Had to git clone more than once:
1315           \${number_of_tries} times.\")
1316 endif()
1317 if(error_code)
1318   message(FATAL_ERROR \"Failed to clone repository: '${git_repository}'\")
1319 endif()
1320
1321 execute_process(
1322   COMMAND \"${git_EXECUTABLE}\" ${git_options} checkout ${git_tag} ${git_checkout_explicit--}
1323   WORKING_DIRECTORY \"${work_dir}/${src_name}\"
1324   RESULT_VARIABLE error_code
1325   )
1326 if(error_code)
1327   message(FATAL_ERROR \"Failed to checkout tag: '${git_tag}'\")
1328 endif()
1329
1330 set(init_submodules ${init_submodules})
1331 if(init_submodules)
1332   execute_process(
1333     COMMAND \"${git_EXECUTABLE}\" ${git_options} submodule update ${git_submodules_recurse} --init ${git_submodules}
1334     WORKING_DIRECTORY \"${work_dir}/${src_name}\"
1335     RESULT_VARIABLE error_code
1336     )
1337 endif()
1338 if(error_code)
1339   message(FATAL_ERROR \"Failed to update submodules in: '${work_dir}/${src_name}'\")
1340 endif()
1341
1342 # Complete success, update the script-last-run stamp file:
1343 #
1344 execute_process(
1345   COMMAND \${CMAKE_COMMAND} -E copy
1346     \"${gitclone_infofile}\"
1347     \"${gitclone_stampfile}\"
1348   RESULT_VARIABLE error_code
1349   )
1350 if(error_code)
1351   message(FATAL_ERROR \"Failed to copy script-last-run stamp file: '${gitclone_stampfile}'\")
1352 endif()
1353
1354 "
1355 )
1356
1357 endfunction()
1358
1359 function(_ep_write_hgclone_script script_filename source_dir hg_EXECUTABLE hg_repository hg_tag src_name work_dir hgclone_infofile hgclone_stampfile)
1360   if("${hg_tag}" STREQUAL "")
1361     message(FATAL_ERROR "Tag for hg checkout should not be empty.")
1362   endif()
1363   file(WRITE ${script_filename}
1364 "
1365 if(NOT \"${hgclone_infofile}\" IS_NEWER_THAN \"${hgclone_stampfile}\")
1366   message(STATUS \"Avoiding repeated hg clone, stamp file is up to date: '${hgclone_stampfile}'\")
1367   return()
1368 endif()
1369
1370 execute_process(
1371   COMMAND \${CMAKE_COMMAND} -E rm -rf \"${source_dir}\"
1372   RESULT_VARIABLE error_code
1373   )
1374 if(error_code)
1375   message(FATAL_ERROR \"Failed to remove directory: '${source_dir}'\")
1376 endif()
1377
1378 execute_process(
1379   COMMAND \"${hg_EXECUTABLE}\" clone -U \"${hg_repository}\" \"${src_name}\"
1380   WORKING_DIRECTORY \"${work_dir}\"
1381   RESULT_VARIABLE error_code
1382   )
1383 if(error_code)
1384   message(FATAL_ERROR \"Failed to clone repository: '${hg_repository}'\")
1385 endif()
1386
1387 execute_process(
1388   COMMAND \"${hg_EXECUTABLE}\" update ${hg_tag}
1389   WORKING_DIRECTORY \"${work_dir}/${src_name}\"
1390   RESULT_VARIABLE error_code
1391   )
1392 if(error_code)
1393   message(FATAL_ERROR \"Failed to checkout tag: '${hg_tag}'\")
1394 endif()
1395
1396 # Complete success, update the script-last-run stamp file:
1397 #
1398 execute_process(
1399   COMMAND \${CMAKE_COMMAND} -E copy
1400     \"${hgclone_infofile}\"
1401     \"${hgclone_stampfile}\"
1402   RESULT_VARIABLE error_code
1403   )
1404 if(error_code)
1405   message(FATAL_ERROR \"Failed to copy script-last-run stamp file: '${hgclone_stampfile}'\")
1406 endif()
1407
1408 "
1409 )
1410
1411 endfunction()
1412
1413
1414 function(_ep_write_gitupdate_script script_filename git_EXECUTABLE git_tag git_remote_name init_submodules git_submodules_recurse git_submodules git_repository work_dir git_update_strategy)
1415   if("${git_tag}" STREQUAL "")
1416     message(FATAL_ERROR "Tag for git checkout should not be empty.")
1417   endif()
1418   set(git_stash_save_options --quiet)
1419   if(GIT_VERSION_STRING VERSION_GREATER_EQUAL 1.7.7)
1420     # This avoids stashing files covered by .gitignore
1421     list(APPEND git_stash_save_options --include-untracked)
1422   elseif(GIT_VERSION_STRING VERSION_GREATER_EQUAL 1.7.6)
1423     # Untracked files, but also ignored files, so potentially slower
1424     list(APPEND git_stash_save_options --all)
1425   endif()
1426
1427   configure_file(
1428       "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/ExternalProject-gitupdate.cmake.in"
1429       "${script_filename}"
1430       @ONLY
1431   )
1432 endfunction()
1433
1434 function(_ep_write_downloadfile_script script_filename REMOTE LOCAL timeout inactivity_timeout no_progress hash tls_verify tls_cainfo userpwd http_headers netrc netrc_file)
1435   if(timeout)
1436     set(TIMEOUT_ARGS TIMEOUT ${timeout})
1437     set(TIMEOUT_MSG "${timeout} seconds")
1438   else()
1439     set(TIMEOUT_ARGS "# no TIMEOUT")
1440     set(TIMEOUT_MSG "none")
1441   endif()
1442   if(inactivity_timeout)
1443     set(INACTIVITY_TIMEOUT_ARGS INACTIVITY_TIMEOUT ${inactivity_timeout})
1444     set(INACTIVITY_TIMEOUT_MSG "${inactivity_timeout} seconds")
1445   else()
1446     set(INACTIVITY_TIMEOUT_ARGS "# no INACTIVITY_TIMEOUT")
1447     set(INACTIVITY_TIMEOUT_MSG "none")
1448   endif()
1449
1450
1451   if(no_progress)
1452     set(SHOW_PROGRESS "")
1453   else()
1454     set(SHOW_PROGRESS "SHOW_PROGRESS")
1455   endif()
1456
1457   _ep_get_hash_regex(_ep_hash_regex)
1458   if("${hash}" MATCHES "${_ep_hash_regex}")
1459     set(ALGO "${CMAKE_MATCH_1}")
1460     string(TOLOWER "${CMAKE_MATCH_2}" EXPECT_VALUE)
1461   else()
1462     set(ALGO "")
1463     set(EXPECT_VALUE "")
1464   endif()
1465
1466   set(TLS_VERIFY_CODE "")
1467   set(TLS_CAINFO_CODE "")
1468   set(NETRC_CODE "")
1469   set(NETRC_FILE_CODE "")
1470
1471   # check for curl globals in the project
1472   if(DEFINED CMAKE_TLS_VERIFY)
1473     set(TLS_VERIFY_CODE "set(CMAKE_TLS_VERIFY ${CMAKE_TLS_VERIFY})")
1474   endif()
1475   if(DEFINED CMAKE_TLS_CAINFO)
1476     set(TLS_CAINFO_CODE "set(CMAKE_TLS_CAINFO \"${CMAKE_TLS_CAINFO}\")")
1477   endif()
1478   if(DEFINED CMAKE_NETRC)
1479     set(NETRC_CODE "set(CMAKE_NETRC \"${CMAKE_NETRC}\")")
1480   endif()
1481   if(DEFINED CMAKE_NETRC_FILE)
1482     set(NETRC_FILE_CODE "set(CMAKE_NETRC_FILE \"${CMAKE_NETRC_FILE}\")")
1483   endif()
1484
1485   # now check for curl locals so that the local values
1486   # will override the globals
1487
1488   # check for tls_verify argument
1489   string(LENGTH "${tls_verify}" tls_verify_len)
1490   if(tls_verify_len GREATER 0)
1491     set(TLS_VERIFY_CODE "set(CMAKE_TLS_VERIFY ${tls_verify})")
1492   endif()
1493   # check for tls_cainfo argument
1494   string(LENGTH "${tls_cainfo}" tls_cainfo_len)
1495   if(tls_cainfo_len GREATER 0)
1496     set(TLS_CAINFO_CODE "set(CMAKE_TLS_CAINFO \"${tls_cainfo}\")")
1497   endif()
1498   # check for netrc argument
1499   string(LENGTH "${netrc}" netrc_len)
1500   if(netrc_len GREATER 0)
1501     set(NETRC_CODE "set(CMAKE_NETRC \"${netrc}\")")
1502   endif()
1503   # check for netrc_file argument
1504   string(LENGTH "${netrc_file}" netrc_file_len)
1505   if(netrc_file_len GREATER 0)
1506     set(NETRC_FILE_CODE "set(CMAKE_NETRC_FILE \"${netrc_file}\")")
1507   endif()
1508
1509   if(userpwd STREQUAL ":")
1510     set(USERPWD_ARGS)
1511   else()
1512     set(USERPWD_ARGS USERPWD "${userpwd}")
1513   endif()
1514
1515   set(HTTP_HEADERS_ARGS "")
1516   if(NOT http_headers STREQUAL "")
1517     foreach(header ${http_headers})
1518       set(
1519           HTTP_HEADERS_ARGS
1520           "HTTPHEADER \"${header}\"\n        ${HTTP_HEADERS_ARGS}"
1521       )
1522     endforeach()
1523   endif()
1524
1525   # Used variables:
1526   # * TLS_VERIFY_CODE
1527   # * TLS_CAINFO_CODE
1528   # * ALGO
1529   # * EXPECT_VALUE
1530   # * REMOTE
1531   # * LOCAL
1532   # * SHOW_PROGRESS
1533   # * TIMEOUT_ARGS
1534   # * TIMEOUT_MSG
1535   # * USERPWD_ARGS
1536   # * HTTP_HEADERS_ARGS
1537   configure_file(
1538       "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/ExternalProject-download.cmake.in"
1539       "${script_filename}"
1540       @ONLY
1541   )
1542 endfunction()
1543
1544 function(_ep_write_verifyfile_script script_filename LOCAL hash)
1545   _ep_get_hash_regex(_ep_hash_regex)
1546   if("${hash}" MATCHES "${_ep_hash_regex}")
1547     set(ALGO "${CMAKE_MATCH_1}")
1548     string(TOLOWER "${CMAKE_MATCH_2}" EXPECT_VALUE)
1549   else()
1550     set(ALGO "")
1551     set(EXPECT_VALUE "")
1552   endif()
1553
1554   # Used variables:
1555   # * ALGO
1556   # * EXPECT_VALUE
1557   # * LOCAL
1558   configure_file(
1559       "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/ExternalProject-verify.cmake.in"
1560       "${script_filename}"
1561       @ONLY
1562   )
1563 endfunction()
1564
1565
1566 function(_ep_write_extractfile_script script_filename name filename directory)
1567   set(args "")
1568
1569   if(filename MATCHES "(\\.|=)(7z|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip)$")
1570     set(args xfz)
1571   endif()
1572
1573   if(filename MATCHES "(\\.|=)tar$")
1574     set(args xf)
1575   endif()
1576
1577   if(args STREQUAL "")
1578     message(SEND_ERROR "error: do not know how to extract '${filename}' -- known types are .7z, .tar, .tar.bz2, .tar.gz, .tar.xz, .tbz2, .tgz, .txz and .zip")
1579     return()
1580   endif()
1581
1582   file(WRITE ${script_filename}
1583 "# Make file names absolute:
1584 #
1585 get_filename_component(filename \"${filename}\" ABSOLUTE)
1586 get_filename_component(directory \"${directory}\" ABSOLUTE)
1587
1588 message(STATUS \"extracting...
1589      src='\${filename}'
1590      dst='\${directory}'\")
1591
1592 if(NOT EXISTS \"\${filename}\")
1593   message(FATAL_ERROR \"error: file to extract does not exist: '\${filename}'\")
1594 endif()
1595
1596 # Prepare a space for extracting:
1597 #
1598 set(i 1234)
1599 while(EXISTS \"\${directory}/../ex-${name}\${i}\")
1600   math(EXPR i \"\${i} + 1\")
1601 endwhile()
1602 set(ut_dir \"\${directory}/../ex-${name}\${i}\")
1603 file(MAKE_DIRECTORY \"\${ut_dir}\")
1604
1605 # Extract it:
1606 #
1607 message(STATUS \"extracting... [tar ${args}]\")
1608 execute_process(COMMAND \${CMAKE_COMMAND} -E tar ${args} \${filename}
1609   WORKING_DIRECTORY \${ut_dir}
1610   RESULT_VARIABLE rv)
1611
1612 if(NOT rv EQUAL 0)
1613   message(STATUS \"extracting... [error clean up]\")
1614   file(REMOVE_RECURSE \"\${ut_dir}\")
1615   message(FATAL_ERROR \"error: extract of '\${filename}' failed\")
1616 endif()
1617
1618 # Analyze what came out of the tar file:
1619 #
1620 message(STATUS \"extracting... [analysis]\")
1621 file(GLOB contents \"\${ut_dir}/*\")
1622 list(REMOVE_ITEM contents \"\${ut_dir}/.DS_Store\")
1623 list(LENGTH contents n)
1624 if(NOT n EQUAL 1 OR NOT IS_DIRECTORY \"\${contents}\")
1625   set(contents \"\${ut_dir}\")
1626 endif()
1627
1628 # Move \"the one\" directory to the final directory:
1629 #
1630 message(STATUS \"extracting... [rename]\")
1631 file(REMOVE_RECURSE \${directory})
1632 get_filename_component(contents \${contents} ABSOLUTE)
1633 file(RENAME \${contents} \${directory})
1634
1635 # Clean up:
1636 #
1637 message(STATUS \"extracting... [clean up]\")
1638 file(REMOVE_RECURSE \"\${ut_dir}\")
1639
1640 message(STATUS \"extracting... done\")
1641 "
1642 )
1643
1644 endfunction()
1645
1646
1647 function(_ep_set_directories name)
1648   get_property(prefix TARGET ${name} PROPERTY _EP_PREFIX)
1649   if(NOT prefix)
1650     get_property(prefix DIRECTORY PROPERTY EP_PREFIX)
1651     if(NOT prefix)
1652       get_property(base DIRECTORY PROPERTY EP_BASE)
1653       if(NOT base)
1654         set(prefix "${name}-prefix")
1655       endif()
1656     endif()
1657   endif()
1658   if(prefix)
1659     set(tmp_default "${prefix}/tmp")
1660     set(download_default "${prefix}/src")
1661     set(source_default "${prefix}/src/${name}")
1662     set(binary_default "${prefix}/src/${name}-build")
1663     set(stamp_default "${prefix}/src/${name}-stamp")
1664     set(install_default "${prefix}")
1665   else()
1666     set(tmp_default "${base}/tmp/${name}")
1667     set(download_default "${base}/Download/${name}")
1668     set(source_default "${base}/Source/${name}")
1669     set(binary_default "${base}/Build/${name}")
1670     set(stamp_default "${base}/Stamp/${name}")
1671     set(install_default "${base}/Install/${name}")
1672   endif()
1673   get_property(build_in_source TARGET ${name} PROPERTY _EP_BUILD_IN_SOURCE)
1674   if(build_in_source)
1675     get_property(have_binary_dir TARGET ${name} PROPERTY _EP_BINARY_DIR SET)
1676     if(have_binary_dir)
1677       message(FATAL_ERROR
1678         "External project ${name} has both BINARY_DIR and BUILD_IN_SOURCE!")
1679     endif()
1680   endif()
1681   set(top "${CMAKE_CURRENT_BINARY_DIR}")
1682
1683   # Apply defaults and convert to absolute paths.
1684   set(places stamp download source binary install tmp)
1685   foreach(var ${places})
1686     string(TOUPPER "${var}" VAR)
1687     get_property(${var}_dir TARGET ${name} PROPERTY _EP_${VAR}_DIR)
1688     if(NOT ${var}_dir)
1689       set(${var}_dir "${${var}_default}")
1690     endif()
1691     if(NOT IS_ABSOLUTE "${${var}_dir}")
1692       get_filename_component(${var}_dir "${top}/${${var}_dir}" ABSOLUTE)
1693     endif()
1694     set_property(TARGET ${name} PROPERTY _EP_${VAR}_DIR "${${var}_dir}")
1695   endforeach()
1696
1697   # Special case for default log directory based on stamp directory.
1698   get_property(log_dir TARGET ${name} PROPERTY _EP_LOG_DIR)
1699   if(NOT log_dir)
1700     get_property(log_dir TARGET ${name} PROPERTY _EP_STAMP_DIR)
1701   endif()
1702   if(NOT IS_ABSOLUTE "${log_dir}")
1703     get_filename_component(log_dir "${top}/${log_dir}" ABSOLUTE)
1704   endif()
1705   set_property(TARGET ${name} PROPERTY _EP_LOG_DIR "${log_dir}")
1706
1707   get_property(source_subdir TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR)
1708   if(NOT source_subdir)
1709     set_property(TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR "")
1710   elseif(IS_ABSOLUTE "${source_subdir}")
1711     message(FATAL_ERROR
1712       "External project ${name} has non-relative SOURCE_SUBDIR!")
1713   else()
1714     # Prefix with a slash so that when appended to the source directory, it
1715     # behaves as expected.
1716     set_property(TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR "/${source_subdir}")
1717   endif()
1718   if(build_in_source)
1719     get_property(source_dir TARGET ${name} PROPERTY _EP_SOURCE_DIR)
1720     if(source_subdir)
1721       set_property(TARGET ${name} PROPERTY _EP_BINARY_DIR "${source_dir}/${source_subdir}")
1722     else()
1723       set_property(TARGET ${name} PROPERTY _EP_BINARY_DIR "${source_dir}")
1724     endif()
1725   endif()
1726
1727   # Make the directories at CMake configure time *and* add a custom command
1728   # to make them at build time. They need to exist at makefile generation
1729   # time for Borland make and wmake so that CMake may generate makefiles
1730   # with "cd C:\short\paths\with\no\spaces" commands in them.
1731   #
1732   # Additionally, the add_custom_command is still used in case somebody
1733   # removes one of the necessary directories and tries to rebuild without
1734   # re-running cmake.
1735   foreach(var ${places})
1736     string(TOUPPER "${var}" VAR)
1737     get_property(dir TARGET ${name} PROPERTY _EP_${VAR}_DIR)
1738     file(MAKE_DIRECTORY "${dir}")
1739     if(NOT EXISTS "${dir}")
1740       message(FATAL_ERROR "dir '${dir}' does not exist after file(MAKE_DIRECTORY)")
1741     endif()
1742   endforeach()
1743 endfunction()
1744
1745
1746 # IMPORTANT: this MUST be a macro and not a function because of the
1747 # in-place replacements that occur in each ${var}
1748 #
1749 macro(_ep_replace_location_tags target_name)
1750   set(vars ${ARGN})
1751   foreach(var ${vars})
1752     if(${var})
1753       foreach(dir SOURCE_DIR SOURCE_SUBDIR BINARY_DIR INSTALL_DIR TMP_DIR DOWNLOAD_DIR DOWNLOADED_FILE LOG_DIR)
1754         get_property(val TARGET ${target_name} PROPERTY _EP_${dir})
1755         string(REPLACE "<${dir}>" "${val}" ${var} "${${var}}")
1756       endforeach()
1757     endif()
1758   endforeach()
1759 endmacro()
1760
1761
1762 function(_ep_command_line_to_initial_cache var args force)
1763   set(script_initial_cache "")
1764   set(regex "^([^:]+):([^=]+)=(.*)$")
1765   set(setArg "")
1766   set(forceArg "")
1767   if(force)
1768     set(forceArg "FORCE")
1769   endif()
1770   foreach(line ${args})
1771     if("${line}" MATCHES "^-D(.*)")
1772       set(line "${CMAKE_MATCH_1}")
1773       if(NOT "${setArg}" STREQUAL "")
1774         # This is required to build up lists in variables, or complete an entry
1775         string(APPEND setArg "${accumulator}\" CACHE ${type} \"Initial cache\" ${forceArg})")
1776         string(APPEND script_initial_cache "\n${setArg}")
1777         set(accumulator "")
1778         set(setArg "")
1779       endif()
1780       if("${line}" MATCHES "${regex}")
1781         set(name "${CMAKE_MATCH_1}")
1782         set(type "${CMAKE_MATCH_2}")
1783         set(value "${CMAKE_MATCH_3}")
1784         set(setArg "set(${name} \"${value}")
1785       else()
1786         message(WARNING "Line '${line}' does not match regex. Ignoring.")
1787       endif()
1788     else()
1789       # Assume this is a list to append to the last var
1790       string(APPEND accumulator ";${line}")
1791     endif()
1792   endforeach()
1793   # Catch the final line of the args
1794   if(NOT "${setArg}" STREQUAL "")
1795     string(APPEND setArg "${accumulator}\" CACHE ${type} \"Initial cache\" ${forceArg})")
1796     string(APPEND script_initial_cache "\n${setArg}")
1797   endif()
1798   set(${var} ${script_initial_cache} PARENT_SCOPE)
1799 endfunction()
1800
1801
1802 function(_ep_write_initial_cache target_name script_filename script_initial_cache)
1803   # Write out values into an initial cache, that will be passed to CMake with -C
1804   # Replace location tags.
1805   _ep_replace_location_tags(${target_name} script_initial_cache)
1806   _ep_replace_location_tags(${target_name} script_filename)
1807   # Replace list separators.
1808   get_property(sep TARGET ${target_name} PROPERTY _EP_LIST_SEPARATOR)
1809   if(sep AND script_initial_cache)
1810     string(REPLACE "${sep}" ";" script_initial_cache "${script_initial_cache}")
1811   endif()
1812   # Write out the initial cache file to the location specified.
1813   file(GENERATE OUTPUT "${script_filename}" CONTENT "${script_initial_cache}")
1814 endfunction()
1815
1816
1817 function(ExternalProject_Get_Property name)
1818   foreach(var ${ARGN})
1819     string(TOUPPER "${var}" VAR)
1820     get_property(is_set TARGET ${name} PROPERTY _EP_${VAR} SET)
1821     if(NOT is_set)
1822       message(FATAL_ERROR "External project \"${name}\" has no ${var}")
1823     endif()
1824     get_property(${var} TARGET ${name} PROPERTY _EP_${VAR})
1825     set(${var} "${${var}}" PARENT_SCOPE)
1826   endforeach()
1827 endfunction()
1828
1829
1830 function(_ep_get_configure_command_id name cfg_cmd_id_var)
1831   get_target_property(cmd ${name} _EP_CONFIGURE_COMMAND)
1832
1833   if(cmd STREQUAL "")
1834     # Explicit empty string means no configure step for this project
1835     set(${cfg_cmd_id_var} "none" PARENT_SCOPE)
1836   else()
1837     if(NOT cmd)
1838       # Default is "use cmake":
1839       set(${cfg_cmd_id_var} "cmake" PARENT_SCOPE)
1840     else()
1841       # Otherwise we have to analyze the value:
1842       if(cmd MATCHES "^[^;]*/configure")
1843         set(${cfg_cmd_id_var} "configure" PARENT_SCOPE)
1844       elseif(cmd MATCHES "^[^;]*/cmake" AND NOT cmd MATCHES ";-[PE];")
1845         set(${cfg_cmd_id_var} "cmake" PARENT_SCOPE)
1846       elseif(cmd MATCHES "config")
1847         set(${cfg_cmd_id_var} "configure" PARENT_SCOPE)
1848       else()
1849         set(${cfg_cmd_id_var} "unknown:${cmd}" PARENT_SCOPE)
1850       endif()
1851     endif()
1852   endif()
1853 endfunction()
1854
1855
1856 function(_ep_get_build_command name step cmd_var)
1857   set(cmd "")
1858   set(args)
1859   _ep_get_configure_command_id(${name} cfg_cmd_id)
1860   if(cfg_cmd_id STREQUAL "cmake")
1861     # CMake project.  Select build command based on generator.
1862     get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR)
1863     if("${CMAKE_GENERATOR}" MATCHES "Make" AND
1864        ("${cmake_generator}" MATCHES "Make" OR NOT cmake_generator))
1865       # The project uses the same Makefile generator.  Use recursive make.
1866       set(cmd "$(MAKE)")
1867       if(step STREQUAL "INSTALL")
1868         set(args install)
1869       endif()
1870       if("x${step}x" STREQUAL "xTESTx")
1871         set(args test)
1872       endif()
1873     else()
1874       # Drive the project with "cmake --build".
1875       get_target_property(cmake_command ${name} _EP_CMAKE_COMMAND)
1876       if(cmake_command)
1877         set(cmd "${cmake_command}")
1878       else()
1879         set(cmd "${CMAKE_COMMAND}")
1880       endif()
1881       set(args --build ".")
1882       get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
1883       if(_isMultiConfig)
1884         if (CMAKE_CFG_INTDIR AND
1885             NOT CMAKE_CFG_INTDIR STREQUAL "." AND
1886             NOT CMAKE_CFG_INTDIR MATCHES "\\$")
1887           # CMake 3.4 and below used the CMAKE_CFG_INTDIR placeholder value
1888           # provided by multi-configuration generators.  Some projects were
1889           # taking advantage of that undocumented implementation detail to
1890           # specify a specific configuration here.  They should use
1891           # BUILD_COMMAND to change the default command instead, but for
1892           # compatibility honor the value.
1893           set(config ${CMAKE_CFG_INTDIR})
1894           message(AUTHOR_WARNING "CMAKE_CFG_INTDIR should not be set by project code.\n"
1895             "To get a non-default build command, use the BUILD_COMMAND option.")
1896         else()
1897           set(config $<CONFIG>)
1898         endif()
1899         list(APPEND args --config ${config})
1900       endif()
1901       if(step STREQUAL "INSTALL")
1902         list(APPEND args --target install)
1903       endif()
1904       # But for "TEST" drive the project with corresponding "ctest".
1905       if("x${step}x" STREQUAL "xTESTx")
1906         string(REGEX REPLACE "^(.*/)cmake([^/]*)$" "\\1ctest\\2" cmd "${cmd}")
1907         set(args "")
1908         if(_isMultiConfig)
1909           list(APPEND args -C ${config})
1910         endif()
1911       endif()
1912     endif()
1913   else()
1914     # Non-CMake project.  Guess "make" and "make install" and "make test".
1915     if("${CMAKE_GENERATOR}" MATCHES "Makefiles")
1916       # Try to get the parallel arguments
1917       set(cmd "$(MAKE)")
1918     else()
1919       set(cmd "make")
1920     endif()
1921     if(step STREQUAL "INSTALL")
1922       set(args install)
1923     endif()
1924     if("x${step}x" STREQUAL "xTESTx")
1925       set(args test)
1926     endif()
1927   endif()
1928
1929   # Use user-specified arguments instead of default arguments, if any.
1930   get_property(have_args TARGET ${name} PROPERTY _EP_${step}_ARGS SET)
1931   if(have_args)
1932     get_target_property(args ${name} _EP_${step}_ARGS)
1933   endif()
1934
1935   if(NOT "${args}" STREQUAL "")
1936     # args could have empty items, so we must quote it to prevent them
1937     # from being silently removed
1938     list(APPEND cmd "${args}")
1939   endif()
1940   set(${cmd_var} "${cmd}" PARENT_SCOPE)
1941 endfunction()
1942
1943 function(_ep_write_log_script name step cmd_var)
1944   ExternalProject_Get_Property(${name} log_dir)
1945   ExternalProject_Get_Property(${name} stamp_dir)
1946   set(command "${${cmd_var}}")
1947
1948   set(make "")
1949   set(code_cygpath_make "")
1950   if(command MATCHES "^\\$\\(MAKE\\)")
1951     # GNU make recognizes the string "$(MAKE)" as recursive make, so
1952     # ensure that it appears directly in the makefile.
1953     string(REGEX REPLACE "^\\$\\(MAKE\\)" "\${make}" command "${command}")
1954     set(make "-Dmake=$(MAKE)")
1955
1956     if(WIN32 AND NOT CYGWIN)
1957       set(code_cygpath_make "
1958 if(\${make} MATCHES \"^/\")
1959   execute_process(
1960     COMMAND cygpath -w \${make}
1961     OUTPUT_VARIABLE cygpath_make
1962     ERROR_VARIABLE cygpath_make
1963     RESULT_VARIABLE cygpath_error
1964     OUTPUT_STRIP_TRAILING_WHITESPACE
1965   )
1966   if(NOT cygpath_error)
1967     set(make \${cygpath_make})
1968   endif()
1969 endif()
1970 ")
1971     endif()
1972   endif()
1973
1974   set(config "")
1975   if("${CMAKE_CFG_INTDIR}" MATCHES "^\\$")
1976     string(REPLACE "${CMAKE_CFG_INTDIR}" "\${config}" command "${command}")
1977     set(config "-Dconfig=${CMAKE_CFG_INTDIR}")
1978   endif()
1979
1980   # Wrap multiple 'COMMAND' lines up into a second-level wrapper
1981   # script so all output can be sent to one log file.
1982   if(command MATCHES "(^|;)COMMAND;")
1983     set(code_execute_process "
1984 ${code_cygpath_make}
1985 execute_process(COMMAND \${command} RESULT_VARIABLE result)
1986 if(result)
1987   set(msg \"Command failed (\${result}):\\n\")
1988   foreach(arg IN LISTS command)
1989     set(msg \"\${msg} '\${arg}'\")
1990   endforeach()
1991   message(FATAL_ERROR \"\${msg}\")
1992 endif()
1993 ")
1994     set(code "")
1995     set(cmd "")
1996     set(sep "")
1997     foreach(arg IN LISTS command)
1998       if("x${arg}" STREQUAL "xCOMMAND")
1999         if(NOT "x${cmd}" STREQUAL "x")
2000           string(APPEND code "set(command \"${cmd}\")${code_execute_process}")
2001         endif()
2002         set(cmd "")
2003         set(sep "")
2004       else()
2005         string(APPEND cmd "${sep}${arg}")
2006         set(sep ";")
2007       endif()
2008     endforeach()
2009     string(APPEND code "set(command \"${cmd}\")${code_execute_process}")
2010     file(GENERATE OUTPUT "${stamp_dir}/${name}-${step}-$<CONFIG>-impl.cmake" CONTENT "${code}")
2011     set(command ${CMAKE_COMMAND} "-Dmake=\${make}" "-Dconfig=\${config}" -P ${stamp_dir}/${name}-${step}-$<CONFIG>-impl.cmake)
2012   endif()
2013
2014   # Wrap the command in a script to log output to files.
2015   set(script ${stamp_dir}/${name}-${step}-$<CONFIG>.cmake)
2016   set(logbase ${log_dir}/${name}-${step})
2017   get_property(log_merged TARGET ${name} PROPERTY _EP_LOG_MERGED_STDOUTERR)
2018   get_property(log_output_on_failure TARGET ${name} PROPERTY _EP_LOG_OUTPUT_ON_FAILURE)
2019   if (log_merged)
2020     set(stdout_log "${logbase}.log")
2021     set(stderr_log "${logbase}.log")
2022   else()
2023     set(stdout_log "${logbase}-out.log")
2024     set(stderr_log "${logbase}-err.log")
2025   endif()
2026   set(code "
2027 cmake_minimum_required(VERSION 3.15)
2028 ${code_cygpath_make}
2029 set(command \"${command}\")
2030 set(log_merged \"${log_merged}\")
2031 set(log_output_on_failure \"${log_output_on_failure}\")
2032 set(stdout_log \"${stdout_log}\")
2033 set(stderr_log \"${stderr_log}\")
2034 execute_process(
2035   COMMAND \${command}
2036   RESULT_VARIABLE result
2037   OUTPUT_FILE \"\${stdout_log}\"
2038   ERROR_FILE \"\${stderr_log}\"
2039   )
2040 macro(read_up_to_max_size log_file output_var)
2041   file(SIZE \${log_file} determined_size)
2042   set(max_size 10240)
2043   if (determined_size GREATER max_size)
2044     math(EXPR seek_position \"\${determined_size} - \${max_size}\")
2045     file(READ \${log_file} \${output_var} OFFSET \${seek_position})
2046     set(\${output_var} \"...skipping to end...\\n\${\${output_var}}\")
2047   else()
2048     file(READ \${log_file} \${output_var})
2049   endif()
2050 endmacro()
2051 if(result)
2052   set(msg \"Command failed: \${result}\\n\")
2053   foreach(arg IN LISTS command)
2054     set(msg \"\${msg} '\${arg}'\")
2055   endforeach()
2056   if (\${log_merged})
2057     set(msg \"\${msg}\\nSee also\\n  \${stderr_log}\")
2058   else()
2059     set(msg \"\${msg}\\nSee also\\n  ${logbase}-*.log\")
2060   endif()
2061   if (\${log_output_on_failure})
2062     message(SEND_ERROR \"\${msg}\")
2063     if (\${log_merged})
2064       read_up_to_max_size(\"\${stderr_log}\" error_log_contents)
2065       message(STATUS \"Log output is:\\n\${error_log_contents}\")
2066     else()
2067       read_up_to_max_size(\"\${stdout_log}\" out_log_contents)
2068       read_up_to_max_size(\"\${stderr_log}\" err_log_contents)
2069       message(STATUS \"stdout output is:\\n\${out_log_contents}\")
2070       message(STATUS \"stderr output is:\\n\${err_log_contents}\")
2071     endif()
2072     message(FATAL_ERROR \"Stopping after outputting logs.\")
2073   else()
2074     message(FATAL_ERROR \"\${msg}\")
2075   endif()
2076 else()
2077   if(NOT \"${CMAKE_GENERATOR}\" MATCHES \"Ninja\")
2078     set(msg \"${name} ${step} command succeeded.  See also ${logbase}-*.log\")
2079     message(STATUS \"\${msg}\")
2080   endif()
2081 endif()
2082 ")
2083   file(GENERATE OUTPUT "${script}" CONTENT "${code}")
2084   set(command ${CMAKE_COMMAND} ${make} ${config} -P ${script})
2085   set(${cmd_var} "${command}" PARENT_SCOPE)
2086 endfunction()
2087
2088 # This module used to use "/${CMAKE_CFG_INTDIR}" directly and produced
2089 # makefiles with "/./" in paths for custom command dependencies. Which
2090 # resulted in problems with parallel make -j invocations.
2091 #
2092 # This function was added so that the suffix (search below for ${cfgdir}) is
2093 # only set to "/${CMAKE_CFG_INTDIR}" when ${CMAKE_CFG_INTDIR} is not going to
2094 # be "." (multi-configuration build systems like Visual Studio and Xcode...)
2095 #
2096 function(_ep_get_configuration_subdir_suffix suffix_var)
2097   set(suffix "")
2098   get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
2099   if(_isMultiConfig)
2100     set(suffix "/${CMAKE_CFG_INTDIR}")
2101   endif()
2102   set(${suffix_var} "${suffix}" PARENT_SCOPE)
2103 endfunction()
2104
2105
2106 function(_ep_get_step_stampfile name step stampfile_var)
2107   ExternalProject_Get_Property(${name} stamp_dir)
2108
2109   _ep_get_configuration_subdir_suffix(cfgdir)
2110   set(stampfile "${stamp_dir}${cfgdir}/${name}-${step}")
2111
2112   set(${stampfile_var} "${stampfile}" PARENT_SCOPE)
2113 endfunction()
2114
2115
2116 function(_ep_get_complete_stampfile name stampfile_var)
2117   set(cmf_dir ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles)
2118   _ep_get_configuration_subdir_suffix(cfgdir)
2119   set(stampfile "${cmf_dir}${cfgdir}/${name}-complete")
2120
2121   set(${stampfile_var} ${stampfile} PARENT_SCOPE)
2122 endfunction()
2123
2124
2125 function(_ep_step_add_target name step no_deps)
2126   if(TARGET ${name}-${step})
2127     return()
2128   endif()
2129   get_property(cmp0114 TARGET ${name} PROPERTY _EP_CMP0114)
2130   _ep_get_step_stampfile(${name} ${step} stamp_file)
2131   cmake_policy(PUSH)
2132   if(cmp0114 STREQUAL "NEW")
2133     # To implement CMP0114 NEW behavior with Makefile generators,
2134     # we need CMP0113 NEW behavior.
2135     cmake_policy(SET CMP0113 NEW)
2136   endif()
2137   add_custom_target(${name}-${step}
2138     DEPENDS ${stamp_file})
2139   cmake_policy(POP)
2140   set_property(TARGET ${name}-${step} PROPERTY _EP_IS_EXTERNAL_PROJECT_STEP 1)
2141   set_property(TARGET ${name}-${step} PROPERTY LABELS ${name})
2142   set_property(TARGET ${name}-${step} PROPERTY FOLDER "ExternalProjectTargets/${name}")
2143
2144   if(cmp0114 STREQUAL "NEW")
2145     # Add target-level dependencies for the step.
2146     get_property(exclude_from_main TARGET ${name} PROPERTY _EP_${step}_EXCLUDE_FROM_MAIN)
2147     if(NOT exclude_from_main)
2148       add_dependencies(${name} ${name}-${step})
2149     endif()
2150     _ep_step_add_target_dependencies(${name} ${step} ${step})
2151     _ep_step_add_target_dependents(${name} ${step} ${step})
2152
2153     get_property(independent TARGET ${name} PROPERTY _EP_${step}_INDEPENDENT)
2154   else()
2155     if(no_deps AND "${step}" MATCHES "^(configure|build|install|test)$")
2156       message(AUTHOR_WARNING "Using NO_DEPENDS for \"${step}\" step  might break parallel builds")
2157     endif()
2158     set(independent ${no_deps})
2159   endif()
2160
2161   # Depend on other external projects (target-level).
2162   if(NOT independent)
2163     get_property(deps TARGET ${name} PROPERTY _EP_DEPENDS)
2164     foreach(arg IN LISTS deps)
2165       add_dependencies(${name}-${step} ${arg})
2166     endforeach()
2167   endif()
2168 endfunction()
2169
2170
2171 function(_ep_step_add_target_dependencies name step node)
2172   get_property(dependees TARGET ${name} PROPERTY _EP_${node}_INTERNAL_DEPENDEES)
2173   list(REMOVE_DUPLICATES dependees)
2174   foreach(dependee IN LISTS dependees)
2175     get_property(exclude_from_main TARGET ${name} PROPERTY _EP_${step}_EXCLUDE_FROM_MAIN)
2176     get_property(dependee_dependers TARGET ${name} PROPERTY _EP_${dependee}_INTERNAL_DEPENDERS)
2177     if(exclude_from_main OR dependee_dependers MATCHES ";")
2178       # The step on which our step target depends itself has
2179       # dependents in multiple targes.  It needs a step target too
2180       # so that there is a unique place for its custom command.
2181       _ep_step_add_target("${name}" "${dependee}" "FALSE")
2182     endif()
2183
2184     if(TARGET ${name}-${dependee})
2185       add_dependencies(${name}-${step} ${name}-${dependee})
2186     else()
2187       _ep_step_add_target_dependencies(${name} ${step} ${dependee})
2188     endif()
2189   endforeach()
2190 endfunction()
2191
2192
2193 function(_ep_step_add_target_dependents name step node)
2194   get_property(dependers TARGET ${name} PROPERTY _EP_${node}_INTERNAL_DEPENDERS)
2195   list(REMOVE_DUPLICATES dependers)
2196   foreach(depender IN LISTS dependers)
2197     if(TARGET ${name}-${depender})
2198       add_dependencies(${name}-${depender} ${name}-${step})
2199     else()
2200       _ep_step_add_target_dependents(${name} ${step} ${depender})
2201     endif()
2202   endforeach()
2203 endfunction()
2204
2205
2206 function(ExternalProject_Add_StepTargets name)
2207   get_property(cmp0114 TARGET ${name} PROPERTY _EP_CMP0114)
2208   set(steps ${ARGN})
2209   if(ARGC GREATER 1 AND "${ARGV1}" STREQUAL "NO_DEPENDS")
2210     set(no_deps 1)
2211     list(REMOVE_AT steps 0)
2212   else()
2213     set(no_deps 0)
2214   endif()
2215   if(cmp0114 STREQUAL "NEW")
2216     if(no_deps)
2217       message(FATAL_ERROR
2218         "The 'NO_DEPENDS' option is no longer allowed.  "
2219         "It has been superseded by the per-step 'INDEPENDENT' option.  "
2220         "See policy CMP0114."
2221         )
2222     endif()
2223   elseif(cmp0114 STREQUAL "")
2224     cmake_policy(GET_WARNING CMP0114 _cmp0114_warning)
2225     string(APPEND _cmp0114_warning "\n"
2226       "ExternalProject target '${name}' would depend on the targets for "
2227       "step(s) '${steps}' under policy CMP0114, but this is being left out "
2228       "for compatibility since the policy is not set."
2229       )
2230     if(no_deps)
2231       string(APPEND _cmp0114_warning
2232         "  Also, the NO_DEPENDS option is deprecated in favor of policy CMP0114."
2233         )
2234     endif()
2235     message(AUTHOR_WARNING "${_cmp0114_warning}")
2236   endif()
2237   foreach(step ${steps})
2238     _ep_step_add_target("${name}" "${step}" "${no_deps}")
2239   endforeach()
2240 endfunction()
2241
2242
2243 function(ExternalProject_Add_Step name step)
2244   get_property(cmp0114 TARGET ${name} PROPERTY _EP_CMP0114)
2245   _ep_get_complete_stampfile(${name} complete_stamp_file)
2246   _ep_get_step_stampfile(${name} ${step} stamp_file)
2247
2248   set(keywords
2249     COMMAND
2250     COMMENT
2251     DEPENDEES
2252     DEPENDERS
2253     DEPENDS
2254     INDEPENDENT
2255     BYPRODUCTS
2256     ALWAYS
2257     EXCLUDE_FROM_MAIN
2258     WORKING_DIRECTORY
2259     LOG
2260     USES_TERMINAL
2261   )
2262   _ep_parse_arguments(ExternalProject_Add_Step "${keywords}"
2263                       ${name} _EP_${step}_ "${ARGN}")
2264
2265   get_property(independent TARGET ${name} PROPERTY _EP_${step}_INDEPENDENT)
2266   if(independent STREQUAL "")
2267     set(independent FALSE)
2268     set_property(TARGET ${name} PROPERTY _EP_${step}_INDEPENDENT "${independent}")
2269   endif()
2270
2271   get_property(exclude_from_main TARGET ${name} PROPERTY _EP_${step}_EXCLUDE_FROM_MAIN)
2272   if(NOT exclude_from_main)
2273     add_custom_command(APPEND
2274       OUTPUT ${complete_stamp_file}
2275       DEPENDS ${stamp_file}
2276       )
2277   endif()
2278
2279   # Steps depending on this step.
2280   get_property(dependers TARGET ${name} PROPERTY _EP_${step}_DEPENDERS)
2281   set_property(TARGET ${name} APPEND PROPERTY _EP_${step}_INTERNAL_DEPENDERS ${dependers})
2282   foreach(depender IN LISTS dependers)
2283     set_property(TARGET ${name} APPEND PROPERTY _EP_${depender}_INTERNAL_DEPENDEES ${step})
2284     _ep_get_step_stampfile(${name} ${depender} depender_stamp_file)
2285     add_custom_command(APPEND
2286       OUTPUT ${depender_stamp_file}
2287       DEPENDS ${stamp_file}
2288       )
2289     if(cmp0114 STREQUAL "NEW" AND NOT independent)
2290       get_property(dep_independent TARGET ${name} PROPERTY _EP_${depender}_INDEPENDENT)
2291       if(dep_independent)
2292         message(FATAL_ERROR "ExternalProject '${name}' step '${depender}' is marked INDEPENDENT "
2293           "but depends on step '${step}' that is not marked INDEPENDENT.")
2294       endif()
2295     endif()
2296   endforeach()
2297
2298   # Dependencies on files.
2299   get_property(depends TARGET ${name} PROPERTY _EP_${step}_DEPENDS)
2300
2301   # Byproducts of the step.
2302   get_property(byproducts TARGET ${name} PROPERTY _EP_${step}_BYPRODUCTS)
2303
2304   # Dependencies on steps.
2305   get_property(dependees TARGET ${name} PROPERTY _EP_${step}_DEPENDEES)
2306   set_property(TARGET ${name} APPEND PROPERTY _EP_${step}_INTERNAL_DEPENDEES ${dependees})
2307   foreach(dependee IN LISTS dependees)
2308     set_property(TARGET ${name} APPEND PROPERTY _EP_${dependee}_INTERNAL_DEPENDERS ${step})
2309     _ep_get_step_stampfile(${name} ${dependee} dependee_stamp_file)
2310     list(APPEND depends ${dependee_stamp_file})
2311     if(cmp0114 STREQUAL "NEW" AND independent)
2312       get_property(dep_independent TARGET ${name} PROPERTY _EP_${dependee}_INDEPENDENT)
2313       if(NOT dep_independent)
2314         message(FATAL_ERROR "ExternalProject '${name}' step '${step}' is marked INDEPENDENT "
2315           "but depends on step '${dependee}' that is not marked INDEPENDENT.")
2316       endif()
2317     endif()
2318   endforeach()
2319
2320   # The command to run.
2321   get_property(command TARGET ${name} PROPERTY _EP_${step}_COMMAND)
2322   if(command)
2323     set(comment "Performing ${step} step for '${name}'")
2324   else()
2325     set(comment "No ${step} step for '${name}'")
2326   endif()
2327   get_property(work_dir TARGET ${name} PROPERTY _EP_${step}_WORKING_DIRECTORY)
2328
2329   # Replace list separators.
2330   get_property(sep TARGET ${name} PROPERTY _EP_LIST_SEPARATOR)
2331   if(sep AND command)
2332     string(REPLACE "${sep}" "\\;" command "${command}")
2333   endif()
2334
2335   # Replace location tags.
2336   _ep_replace_location_tags(${name} comment command work_dir byproducts)
2337
2338   # Custom comment?
2339   get_property(comment_set TARGET ${name} PROPERTY _EP_${step}_COMMENT SET)
2340   if(comment_set)
2341     get_property(comment TARGET ${name} PROPERTY _EP_${step}_COMMENT)
2342   endif()
2343
2344   # Uses terminal?
2345   get_property(uses_terminal TARGET ${name} PROPERTY _EP_${step}_USES_TERMINAL)
2346   if(uses_terminal)
2347     set(uses_terminal USES_TERMINAL)
2348   else()
2349     set(uses_terminal "")
2350   endif()
2351
2352   # Run every time?
2353   get_property(always TARGET ${name} PROPERTY _EP_${step}_ALWAYS)
2354   if(always)
2355     set_property(SOURCE ${stamp_file} PROPERTY SYMBOLIC 1)
2356     set(touch)
2357     # Remove any existing stamp in case the option changed in an existing tree.
2358     get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
2359     if(_isMultiConfig)
2360       foreach(cfg ${CMAKE_CONFIGURATION_TYPES})
2361         string(REPLACE "/${CMAKE_CFG_INTDIR}" "/${cfg}" stamp_file_config "${stamp_file}")
2362         file(REMOVE ${stamp_file_config})
2363       endforeach()
2364     else()
2365       file(REMOVE ${stamp_file})
2366     endif()
2367   else()
2368     set(touch ${CMAKE_COMMAND} -E touch ${stamp_file})
2369   endif()
2370
2371   # Wrap with log script?
2372   get_property(log TARGET ${name} PROPERTY _EP_${step}_LOG)
2373   if(command AND log)
2374     _ep_write_log_script(${name} ${step} command)
2375   endif()
2376
2377   if("${command}" STREQUAL "")
2378     # Some generators (i.e. Xcode) will not generate a file level target
2379     # if no command is set, and therefore the dependencies on this
2380     # target will be broken.
2381     # The empty command is replaced by an echo command here in order to
2382     # avoid this issue.
2383     set(command ${CMAKE_COMMAND} -E echo_append)
2384   endif()
2385
2386   set(__cmdQuoted)
2387   foreach(__item IN LISTS command)
2388     string(APPEND __cmdQuoted " [==[${__item}]==]")
2389   endforeach()
2390   cmake_language(EVAL CODE "
2391     add_custom_command(
2392       OUTPUT \${stamp_file}
2393       BYPRODUCTS \${byproducts}
2394       COMMENT \${comment}
2395       COMMAND ${__cmdQuoted}
2396       COMMAND \${touch}
2397       DEPENDS \${depends}
2398       WORKING_DIRECTORY \${work_dir}
2399       VERBATIM
2400       ${uses_terminal}
2401     )"
2402   )
2403   set_property(TARGET ${name} APPEND PROPERTY _EP_STEPS ${step})
2404
2405   # Add custom "step target"?
2406   get_property(step_targets TARGET ${name} PROPERTY _EP_STEP_TARGETS)
2407   if(NOT step_targets)
2408     get_property(step_targets DIRECTORY PROPERTY EP_STEP_TARGETS)
2409   endif()
2410   foreach(st ${step_targets})
2411     if("${st}" STREQUAL "${step}")
2412       _ep_step_add_target("${name}" "${step}" "FALSE")
2413       break()
2414     endif()
2415   endforeach()
2416
2417   get_property(independent_step_targets TARGET ${name} PROPERTY _EP_INDEPENDENT_STEP_TARGETS)
2418   if(NOT independent_step_targets)
2419     get_property(independent_step_targets DIRECTORY PROPERTY EP_INDEPENDENT_STEP_TARGETS)
2420   endif()
2421   if(cmp0114 STREQUAL "NEW")
2422     if(independent_step_targets)
2423       message(FATAL_ERROR
2424         "ExternalProject '${name}' option 'INDEPENDENT_STEP_TARGETS' is set to\n"
2425         "  ${independent_step_targets}\n"
2426         "but the option is no longer allowed.  "
2427         "It has been superseded by the per-step 'INDEPENDENT' option.  "
2428         "See policy CMP0114."
2429         )
2430     endif()
2431   else()
2432     if(independent_step_targets AND cmp0114 STREQUAL "")
2433       get_property(warned TARGET ${name} PROPERTY _EP_CMP0114_WARNED_INDEPENDENT_STEP_TARGETS)
2434       if(NOT warned)
2435         set_property(TARGET ${name} PROPERTY _EP_CMP0114_WARNED_INDEPENDENT_STEP_TARGETS 1)
2436         cmake_policy(GET_WARNING CMP0114 _cmp0114_warning)
2437         string(APPEND _cmp0114_warning "\n"
2438           "ExternalProject '${name}' option INDEPENDENT_STEP_TARGETS is set to\n"
2439           "  ${independent_step_targets}\n"
2440           "but the option is deprecated in favor of policy CMP0114."
2441           )
2442         message(AUTHOR_WARNING "${_cmp0114_warning}")
2443       endif()
2444     endif()
2445     foreach(st ${independent_step_targets})
2446       if("${st}" STREQUAL "${step}")
2447         _ep_step_add_target("${name}" "${step}" "TRUE")
2448         break()
2449       endif()
2450     endforeach()
2451   endif()
2452 endfunction()
2453
2454
2455 function(ExternalProject_Add_StepDependencies name step)
2456   set(dependencies ${ARGN})
2457
2458   # Sanity checks on "name" and "step".
2459   if(NOT TARGET ${name})
2460     message(FATAL_ERROR "Cannot find target \"${name}\". Perhaps it has not yet been created using ExternalProject_Add.")
2461   endif()
2462
2463   get_property(type TARGET ${name} PROPERTY TYPE)
2464   if(NOT type STREQUAL "UTILITY")
2465     message(FATAL_ERROR "Target \"${name}\" was not generated by ExternalProject_Add.")
2466   endif()
2467
2468   get_property(is_ep TARGET ${name} PROPERTY _EP_IS_EXTERNAL_PROJECT)
2469   if(NOT is_ep)
2470     message(FATAL_ERROR "Target \"${name}\" was not generated by ExternalProject_Add.")
2471   endif()
2472
2473   get_property(steps TARGET ${name} PROPERTY _EP_STEPS)
2474   list(FIND steps ${step} is_step)
2475   if(is_step LESS 0)
2476     message(FATAL_ERROR "External project \"${name}\" does not have a step \"${step}\".")
2477   endif()
2478
2479   if(TARGET ${name}-${step})
2480     get_property(type TARGET ${name}-${step} PROPERTY TYPE)
2481     if(NOT type STREQUAL "UTILITY")
2482       message(FATAL_ERROR "Target \"${name}-${step}\" was not generated by ExternalProject_Add_StepTargets.")
2483     endif()
2484     get_property(is_ep_step TARGET ${name}-${step} PROPERTY _EP_IS_EXTERNAL_PROJECT_STEP)
2485     if(NOT is_ep_step)
2486       message(FATAL_ERROR "Target \"${name}-${step}\" was not generated by ExternalProject_Add_StepTargets.")
2487     endif()
2488   endif()
2489
2490   # Always add file-level dependency, but add target-level dependency
2491   # only if the target exists for that step.
2492   _ep_get_step_stampfile(${name} ${step} stamp_file)
2493   foreach(dep ${dependencies})
2494     add_custom_command(APPEND
2495       OUTPUT ${stamp_file}
2496       DEPENDS ${dep})
2497     if(TARGET ${name}-${step})
2498       foreach(dep ${dependencies})
2499         add_dependencies(${name}-${step} ${dep})
2500       endforeach()
2501     endif()
2502   endforeach()
2503
2504 endfunction()
2505
2506
2507 function(_ep_add_mkdir_command name)
2508   ExternalProject_Get_Property(${name}
2509     source_dir binary_dir install_dir stamp_dir download_dir tmp_dir log_dir)
2510
2511   _ep_get_configuration_subdir_suffix(cfgdir)
2512
2513   ExternalProject_Add_Step(${name} mkdir
2514     INDEPENDENT TRUE
2515     COMMENT "Creating directories for '${name}'"
2516     COMMAND ${CMAKE_COMMAND} -E make_directory ${source_dir}
2517     COMMAND ${CMAKE_COMMAND} -E make_directory ${binary_dir}
2518     COMMAND ${CMAKE_COMMAND} -E make_directory ${install_dir}
2519     COMMAND ${CMAKE_COMMAND} -E make_directory ${tmp_dir}
2520     COMMAND ${CMAKE_COMMAND} -E make_directory ${stamp_dir}${cfgdir}
2521     COMMAND ${CMAKE_COMMAND} -E make_directory ${download_dir}
2522     COMMAND ${CMAKE_COMMAND} -E make_directory ${log_dir}
2523     )
2524 endfunction()
2525
2526
2527 function(_ep_is_dir_empty dir empty_var)
2528   file(GLOB gr "${dir}/*")
2529   if("${gr}" STREQUAL "")
2530     set(${empty_var} 1 PARENT_SCOPE)
2531   else()
2532     set(${empty_var} 0 PARENT_SCOPE)
2533   endif()
2534 endfunction()
2535
2536 function(_ep_get_git_submodules_recurse git_submodules_recurse)
2537   # Checks for GIT_SUBMODULES_RECURSE property
2538   # Default is ON, which sets git_submodules_recurse output variable to "--recursive"
2539   # Otherwise, the output variable is set to an empty value ""
2540   get_property(git_submodules_recurse_set TARGET ${name} PROPERTY _EP_GIT_SUBMODULES_RECURSE SET)
2541   if(NOT git_submodules_recurse_set)
2542     set(recurseFlag "--recursive")
2543   else()
2544     get_property(git_submodules_recurse_value TARGET ${name} PROPERTY _EP_GIT_SUBMODULES_RECURSE)
2545     if(git_submodules_recurse_value)
2546       set(recurseFlag "--recursive")
2547     else()
2548       set(recurseFlag "")
2549     endif()
2550   endif()
2551   set(${git_submodules_recurse} "${recurseFlag}" PARENT_SCOPE)
2552
2553   # The git submodule update '--recursive' flag requires git >= v1.6.5
2554   if(recurseFlag AND GIT_VERSION_STRING VERSION_LESS 1.6.5)
2555     message(FATAL_ERROR "error: git version 1.6.5 or later required for --recursive flag with 'git submodule ...': GIT_VERSION_STRING='${GIT_VERSION_STRING}'")
2556   endif()
2557 endfunction()
2558
2559
2560 function(_ep_add_download_command name)
2561   ExternalProject_Get_Property(${name} source_dir stamp_dir download_dir tmp_dir)
2562
2563   get_property(cmd_set TARGET ${name} PROPERTY _EP_DOWNLOAD_COMMAND SET)
2564   get_property(cmd TARGET ${name} PROPERTY _EP_DOWNLOAD_COMMAND)
2565   get_property(cvs_repository TARGET ${name} PROPERTY _EP_CVS_REPOSITORY)
2566   get_property(svn_repository TARGET ${name} PROPERTY _EP_SVN_REPOSITORY)
2567   get_property(git_repository TARGET ${name} PROPERTY _EP_GIT_REPOSITORY)
2568   get_property(hg_repository  TARGET ${name} PROPERTY _EP_HG_REPOSITORY )
2569   get_property(url TARGET ${name} PROPERTY _EP_URL)
2570   get_property(fname TARGET ${name} PROPERTY _EP_DOWNLOAD_NAME)
2571
2572   # TODO: Perhaps file:// should be copied to download dir before extraction.
2573   string(REGEX REPLACE "file://" "" url "${url}")
2574
2575   set(depends)
2576   set(comment)
2577   set(work_dir)
2578
2579   if(cmd_set)
2580     set(work_dir ${download_dir})
2581   elseif(cvs_repository)
2582     find_package(CVS QUIET)
2583     if(NOT CVS_EXECUTABLE)
2584       message(FATAL_ERROR "error: could not find cvs for checkout of ${name}")
2585     endif()
2586
2587     get_target_property(cvs_module ${name} _EP_CVS_MODULE)
2588     if(NOT cvs_module)
2589       message(FATAL_ERROR "error: no CVS_MODULE")
2590     endif()
2591
2592     get_property(cvs_tag TARGET ${name} PROPERTY _EP_CVS_TAG)
2593
2594     set(repository ${cvs_repository})
2595     set(module ${cvs_module})
2596     set(tag ${cvs_tag})
2597     configure_file(
2598       "${CMAKE_ROOT}/Modules/RepositoryInfo.txt.in"
2599       "${stamp_dir}/${name}-cvsinfo.txt"
2600       @ONLY
2601       )
2602
2603     get_filename_component(src_name "${source_dir}" NAME)
2604     get_filename_component(work_dir "${source_dir}" PATH)
2605     set(comment "Performing download step (CVS checkout) for '${name}'")
2606     set(cmd ${CVS_EXECUTABLE} -d ${cvs_repository} -q co ${cvs_tag} -d ${src_name} ${cvs_module})
2607     list(APPEND depends ${stamp_dir}/${name}-cvsinfo.txt)
2608   elseif(svn_repository)
2609     find_package(Subversion QUIET)
2610     if(NOT Subversion_SVN_EXECUTABLE)
2611       message(FATAL_ERROR "error: could not find svn for checkout of ${name}")
2612     endif()
2613
2614     get_property(svn_revision TARGET ${name} PROPERTY _EP_SVN_REVISION)
2615     get_property(svn_username TARGET ${name} PROPERTY _EP_SVN_USERNAME)
2616     get_property(svn_password TARGET ${name} PROPERTY _EP_SVN_PASSWORD)
2617     get_property(svn_trust_cert TARGET ${name} PROPERTY _EP_SVN_TRUST_CERT)
2618
2619     set(repository "${svn_repository} user=${svn_username} password=${svn_password}")
2620     set(module)
2621     set(tag ${svn_revision})
2622     configure_file(
2623       "${CMAKE_ROOT}/Modules/RepositoryInfo.txt.in"
2624       "${stamp_dir}/${name}-svninfo.txt"
2625       @ONLY
2626       )
2627
2628     get_filename_component(src_name "${source_dir}" NAME)
2629     get_filename_component(work_dir "${source_dir}" PATH)
2630     set(comment "Performing download step (SVN checkout) for '${name}'")
2631     set(svn_user_pw_args "")
2632     if(DEFINED svn_username)
2633       set(svn_user_pw_args ${svn_user_pw_args} "--username=${svn_username}")
2634     endif()
2635     if(DEFINED svn_password)
2636       set(svn_user_pw_args ${svn_user_pw_args} "--password=${svn_password}")
2637     endif()
2638     if(svn_trust_cert)
2639       set(svn_trust_cert_args --trust-server-cert)
2640     endif()
2641     set(cmd ${Subversion_SVN_EXECUTABLE} co ${svn_repository} ${svn_revision}
2642       --non-interactive ${svn_trust_cert_args} ${svn_user_pw_args} ${src_name})
2643     list(APPEND depends ${stamp_dir}/${name}-svninfo.txt)
2644   elseif(git_repository)
2645     # FetchContent gives us these directly, so don't try to recompute them
2646     if(NOT GIT_EXECUTABLE OR NOT GIT_VERSION_STRING)
2647       unset(CMAKE_MODULE_PATH) # Use CMake builtin find module
2648       find_package(Git QUIET)
2649       if(NOT GIT_EXECUTABLE)
2650         message(FATAL_ERROR "error: could not find git for clone of ${name}")
2651       endif()
2652     endif()
2653
2654     _ep_get_git_submodules_recurse(git_submodules_recurse)
2655
2656     get_property(git_tag TARGET ${name} PROPERTY _EP_GIT_TAG)
2657     if(NOT git_tag)
2658       set(git_tag "master")
2659     endif()
2660
2661     set(git_init_submodules TRUE)
2662     get_property(git_submodules_set TARGET ${name} PROPERTY _EP_GIT_SUBMODULES SET)
2663     if(git_submodules_set)
2664       get_property(git_submodules TARGET ${name} PROPERTY _EP_GIT_SUBMODULES)
2665       if(git_submodules  STREQUAL "" AND _EP_CMP0097 STREQUAL "NEW")
2666         set(git_init_submodules FALSE)
2667       endif()
2668     endif()
2669
2670     get_property(git_remote_name TARGET ${name} PROPERTY _EP_GIT_REMOTE_NAME)
2671     if(NOT git_remote_name)
2672       set(git_remote_name "origin")
2673     endif()
2674
2675     get_property(tls_verify TARGET ${name} PROPERTY _EP_TLS_VERIFY)
2676     if("x${tls_verify}" STREQUAL "x" AND DEFINED CMAKE_TLS_VERIFY)
2677       set(tls_verify "${CMAKE_TLS_VERIFY}")
2678     endif()
2679     get_property(git_shallow TARGET ${name} PROPERTY _EP_GIT_SHALLOW)
2680     get_property(git_progress TARGET ${name} PROPERTY _EP_GIT_PROGRESS)
2681     get_property(git_config TARGET ${name} PROPERTY _EP_GIT_CONFIG)
2682
2683     # If git supports it, make checkouts quiet when checking out a git hash.
2684     # This avoids the very noisy detached head message.
2685     if(GIT_VERSION_STRING VERSION_GREATER_EQUAL 1.7.7)
2686       list(PREPEND git_config advice.detachedHead=false)
2687     endif()
2688
2689     # For the download step, and the git clone operation, only the repository
2690     # should be recorded in a configured RepositoryInfo file. If the repo
2691     # changes, the clone script should be run again. But if only the tag
2692     # changes, avoid running the clone script again. Let the 'always' running
2693     # update step checkout the new tag.
2694     #
2695     set(repository ${git_repository})
2696     set(module)
2697     set(tag ${git_remote_name})
2698     configure_file(
2699       "${CMAKE_ROOT}/Modules/RepositoryInfo.txt.in"
2700       "${stamp_dir}/${name}-gitinfo.txt"
2701       @ONLY
2702       )
2703
2704     get_filename_component(src_name "${source_dir}" NAME)
2705     get_filename_component(work_dir "${source_dir}" PATH)
2706
2707     # Since git clone doesn't succeed if the non-empty source_dir exists,
2708     # create a cmake script to invoke as download command.
2709     # The script will delete the source directory and then call git clone.
2710     #
2711     _ep_write_gitclone_script(${tmp_dir}/${name}-gitclone.cmake ${source_dir}
2712       ${GIT_EXECUTABLE} ${git_repository} ${git_tag} ${git_remote_name} ${git_init_submodules} "${git_submodules_recurse}" "${git_submodules}" "${git_shallow}" "${git_progress}" "${git_config}" ${src_name} ${work_dir}
2713       ${stamp_dir}/${name}-gitinfo.txt ${stamp_dir}/${name}-gitclone-lastrun.txt "${tls_verify}"
2714       )
2715     set(comment "Performing download step (git clone) for '${name}'")
2716     set(cmd ${CMAKE_COMMAND} -P ${tmp_dir}/${name}-gitclone.cmake)
2717     list(APPEND depends ${stamp_dir}/${name}-gitinfo.txt)
2718   elseif(hg_repository)
2719     find_package(Hg QUIET)
2720     if(NOT HG_EXECUTABLE)
2721       message(FATAL_ERROR "error: could not find hg for clone of ${name}")
2722     endif()
2723
2724     get_property(hg_tag TARGET ${name} PROPERTY _EP_HG_TAG)
2725     if(NOT hg_tag)
2726       set(hg_tag "tip")
2727     endif()
2728
2729     # For the download step, and the hg clone operation, only the repository
2730     # should be recorded in a configured RepositoryInfo file. If the repo
2731     # changes, the clone script should be run again. But if only the tag
2732     # changes, avoid running the clone script again. Let the 'always' running
2733     # update step checkout the new tag.
2734     #
2735     set(repository ${hg_repository})
2736     set(module)
2737     set(tag)
2738     configure_file(
2739       "${CMAKE_ROOT}/Modules/RepositoryInfo.txt.in"
2740       "${stamp_dir}/${name}-hginfo.txt"
2741       @ONLY
2742       )
2743
2744     get_filename_component(src_name "${source_dir}" NAME)
2745     get_filename_component(work_dir "${source_dir}" PATH)
2746
2747     # Since hg clone doesn't succeed if the non-empty source_dir exists,
2748     # create a cmake script to invoke as download command.
2749     # The script will delete the source directory and then call hg clone.
2750     #
2751     _ep_write_hgclone_script(${tmp_dir}/${name}-hgclone.cmake ${source_dir}
2752       ${HG_EXECUTABLE} ${hg_repository} ${hg_tag} ${src_name} ${work_dir}
2753       ${stamp_dir}/${name}-hginfo.txt ${stamp_dir}/${name}-hgclone-lastrun.txt
2754       )
2755     set(comment "Performing download step (hg clone) for '${name}'")
2756     set(cmd ${CMAKE_COMMAND} -P ${tmp_dir}/${name}-hgclone.cmake)
2757     list(APPEND depends ${stamp_dir}/${name}-hginfo.txt)
2758   elseif(url)
2759     get_filename_component(work_dir "${source_dir}" PATH)
2760     get_property(hash TARGET ${name} PROPERTY _EP_URL_HASH)
2761     _ep_get_hash_regex(_ep_hash_regex)
2762     if(hash AND NOT "${hash}" MATCHES "${_ep_hash_regex}")
2763       _ep_get_hash_algos(_ep_hash_algos)
2764       list(JOIN _ep_hash_algos "|" _ep_hash_algos)
2765       message(FATAL_ERROR "URL_HASH is set to\n  ${hash}\n"
2766         "but must be ALGO=value where ALGO is\n  ${_ep_hash_algos}\n"
2767         "and value is a hex string.")
2768     endif()
2769     get_property(md5 TARGET ${name} PROPERTY _EP_URL_MD5)
2770     if(md5 AND NOT "MD5=${md5}" MATCHES "${_ep_hash_regex}")
2771       message(FATAL_ERROR "URL_MD5 is set to\n  ${md5}\nbut must be a hex string.")
2772     endif()
2773     if(md5 AND NOT hash)
2774       set(hash "MD5=${md5}")
2775     endif()
2776     set(repository "external project URL")
2777     set(module "${url}")
2778     set(tag "${hash}")
2779     configure_file(
2780       "${CMAKE_ROOT}/Modules/RepositoryInfo.txt.in"
2781       "${stamp_dir}/${name}-urlinfo.txt"
2782       @ONLY
2783       )
2784     list(APPEND depends ${stamp_dir}/${name}-urlinfo.txt)
2785
2786     list(LENGTH url url_list_length)
2787     if(NOT "${url_list_length}" STREQUAL "1")
2788       foreach(entry ${url})
2789         if(NOT "${entry}" MATCHES "^[a-z]+://")
2790           message(FATAL_ERROR "At least one entry of URL is a path (invalid in a list)")
2791         endif()
2792       endforeach()
2793       if("x${fname}" STREQUAL "x")
2794         list(GET url 0 fname)
2795       endif()
2796     endif()
2797
2798     if(IS_DIRECTORY "${url}")
2799       get_filename_component(abs_dir "${url}" ABSOLUTE)
2800       set(comment "Performing download step (DIR copy) for '${name}'")
2801       set(cmd   ${CMAKE_COMMAND} -E rm -rf ${source_dir}
2802         COMMAND ${CMAKE_COMMAND} -E copy_directory ${abs_dir} ${source_dir})
2803     else()
2804       get_property(no_extract TARGET "${name}" PROPERTY _EP_DOWNLOAD_NO_EXTRACT)
2805       if("${url}" MATCHES "^[a-z]+://")
2806         # TODO: Should download and extraction be different steps?
2807         if("x${fname}" STREQUAL "x")
2808           set(fname "${url}")
2809         endif()
2810         if("${fname}" MATCHES [[([^/\?#]+(\.|=)(7z|tar|tar\.bz2|tar\.gz|tar\.xz|tbz2|tgz|txz|zip))([/?#].*)?$]])
2811           set(fname "${CMAKE_MATCH_1}")
2812         elseif(no_extract)
2813           get_filename_component(fname "${fname}" NAME)
2814         else()
2815           # Fall back to a default file name.  The actual file name does not
2816           # matter because it is used only internally and our extraction tool
2817           # inspects the file content directly.  If it turns out the wrong URL
2818           # was given that will be revealed during the build which is an easier
2819           # place for users to diagnose than an error here anyway.
2820           set(fname "archive.tar")
2821         endif()
2822         string(REPLACE ";" "-" fname "${fname}")
2823         set(file ${download_dir}/${fname})
2824         get_property(timeout TARGET ${name} PROPERTY _EP_TIMEOUT)
2825         get_property(inactivity_timeout TARGET ${name} PROPERTY _EP_INACTIVITY_TIMEOUT)
2826         get_property(no_progress TARGET ${name} PROPERTY _EP_DOWNLOAD_NO_PROGRESS)
2827         get_property(tls_verify TARGET ${name} PROPERTY _EP_TLS_VERIFY)
2828         get_property(tls_cainfo TARGET ${name} PROPERTY _EP_TLS_CAINFO)
2829         get_property(netrc TARGET ${name} PROPERTY _EP_NETRC)
2830         get_property(netrc_file TARGET ${name} PROPERTY _EP_NETRC_FILE)
2831         get_property(http_username TARGET ${name} PROPERTY _EP_HTTP_USERNAME)
2832         get_property(http_password TARGET ${name} PROPERTY _EP_HTTP_PASSWORD)
2833         get_property(http_headers TARGET ${name} PROPERTY _EP_HTTP_HEADER)
2834         set(download_script "${stamp_dir}/download-${name}.cmake")
2835         _ep_write_downloadfile_script("${download_script}" "${url}" "${file}" "${timeout}" "${inactivity_timeout}" "${no_progress}" "${hash}" "${tls_verify}" "${tls_cainfo}" "${http_username}:${http_password}" "${http_headers}" "${netrc}" "${netrc_file}")
2836         set(cmd ${CMAKE_COMMAND} -P "${download_script}"
2837           COMMAND)
2838         if (no_extract)
2839           set(steps "download and verify")
2840         else ()
2841           set(steps "download, verify and extract")
2842         endif ()
2843         set(comment "Performing download step (${steps}) for '${name}'")
2844         file(WRITE "${stamp_dir}/verify-${name}.cmake" "") # already verified by 'download_script'
2845       else()
2846         set(file "${url}")
2847         if (no_extract)
2848           set(steps "verify")
2849         else ()
2850           set(steps "verify and extract")
2851         endif ()
2852         set(comment "Performing download step (${steps}) for '${name}'")
2853         _ep_write_verifyfile_script("${stamp_dir}/verify-${name}.cmake" "${file}" "${hash}")
2854       endif()
2855       list(APPEND cmd ${CMAKE_COMMAND} -P ${stamp_dir}/verify-${name}.cmake)
2856       if (NOT no_extract)
2857         _ep_write_extractfile_script("${stamp_dir}/extract-${name}.cmake" "${name}" "${file}" "${source_dir}")
2858         list(APPEND cmd COMMAND ${CMAKE_COMMAND} -P ${stamp_dir}/extract-${name}.cmake)
2859       else ()
2860         set_property(TARGET ${name} PROPERTY _EP_DOWNLOADED_FILE ${file})
2861       endif ()
2862     endif()
2863   else()
2864     _ep_is_dir_empty("${source_dir}" empty)
2865     if(${empty})
2866       message(SEND_ERROR
2867         "No download info given for '${name}' and its source directory:\n"
2868         " ${source_dir}\n"
2869         "is not an existing non-empty directory.  Please specify one of:\n"
2870         " * SOURCE_DIR with an existing non-empty directory\n"
2871         " * DOWNLOAD_COMMAND\n"
2872         " * URL\n"
2873         " * GIT_REPOSITORY\n"
2874         " * SVN_REPOSITORY\n"
2875         " * HG_REPOSITORY\n"
2876         " * CVS_REPOSITORY and CVS_MODULE"
2877         )
2878     endif()
2879   endif()
2880
2881   get_property(log TARGET ${name} PROPERTY _EP_LOG_DOWNLOAD)
2882   if(log)
2883     set(log LOG 1)
2884   else()
2885     set(log "")
2886   endif()
2887
2888   get_property(uses_terminal TARGET ${name} PROPERTY
2889     _EP_USES_TERMINAL_DOWNLOAD)
2890   if(uses_terminal)
2891     set(uses_terminal USES_TERMINAL 1)
2892   else()
2893     set(uses_terminal "")
2894   endif()
2895
2896   set(__cmdQuoted)
2897   foreach(__item IN LISTS cmd)
2898     string(APPEND __cmdQuoted " [==[${__item}]==]")
2899   endforeach()
2900   cmake_language(EVAL CODE "
2901     ExternalProject_Add_Step(\${name} download
2902       INDEPENDENT TRUE
2903       COMMENT \${comment}
2904       COMMAND ${__cmdQuoted}
2905       WORKING_DIRECTORY \${work_dir}
2906       DEPENDS \${depends}
2907       DEPENDEES mkdir
2908       ${log}
2909       ${uses_terminal}
2910       )"
2911   )
2912 endfunction()
2913
2914 function(_ep_get_update_disconnected var name)
2915   get_property(update_disconnected_set TARGET ${name} PROPERTY _EP_UPDATE_DISCONNECTED SET)
2916   if(update_disconnected_set)
2917     get_property(update_disconnected TARGET ${name} PROPERTY _EP_UPDATE_DISCONNECTED)
2918   else()
2919     get_property(update_disconnected DIRECTORY PROPERTY EP_UPDATE_DISCONNECTED)
2920   endif()
2921   set(${var} "${update_disconnected}" PARENT_SCOPE)
2922 endfunction()
2923
2924 function(_ep_add_update_command name)
2925   ExternalProject_Get_Property(${name} source_dir tmp_dir)
2926
2927   get_property(cmd_set TARGET ${name} PROPERTY _EP_UPDATE_COMMAND SET)
2928   get_property(cmd TARGET ${name} PROPERTY _EP_UPDATE_COMMAND)
2929   get_property(cvs_repository TARGET ${name} PROPERTY _EP_CVS_REPOSITORY)
2930   get_property(svn_repository TARGET ${name} PROPERTY _EP_SVN_REPOSITORY)
2931   get_property(git_repository TARGET ${name} PROPERTY _EP_GIT_REPOSITORY)
2932   get_property(hg_repository  TARGET ${name} PROPERTY _EP_HG_REPOSITORY )
2933
2934   _ep_get_update_disconnected(update_disconnected ${name})
2935
2936   set(work_dir)
2937   set(comment)
2938   set(always)
2939
2940   if(cmd_set)
2941     set(work_dir ${source_dir})
2942     if(NOT "x${cmd}" STREQUAL "x")
2943       set(always 1)
2944     endif()
2945   elseif(cvs_repository)
2946     if(NOT CVS_EXECUTABLE)
2947       message(FATAL_ERROR "error: could not find cvs for update of ${name}")
2948     endif()
2949     set(work_dir ${source_dir})
2950     set(comment "Performing update step (CVS update) for '${name}'")
2951     get_property(cvs_tag TARGET ${name} PROPERTY _EP_CVS_TAG)
2952     set(cmd ${CVS_EXECUTABLE} -d ${cvs_repository} -q up -dP ${cvs_tag})
2953     set(always 1)
2954   elseif(svn_repository)
2955     if(NOT Subversion_SVN_EXECUTABLE)
2956       message(FATAL_ERROR "error: could not find svn for update of ${name}")
2957     endif()
2958     set(work_dir ${source_dir})
2959     set(comment "Performing update step (SVN update) for '${name}'")
2960     get_property(svn_revision TARGET ${name} PROPERTY _EP_SVN_REVISION)
2961     get_property(svn_username TARGET ${name} PROPERTY _EP_SVN_USERNAME)
2962     get_property(svn_password TARGET ${name} PROPERTY _EP_SVN_PASSWORD)
2963     get_property(svn_trust_cert TARGET ${name} PROPERTY _EP_SVN_TRUST_CERT)
2964     set(svn_user_pw_args "")
2965     if(DEFINED svn_username)
2966       set(svn_user_pw_args ${svn_user_pw_args} "--username=${svn_username}")
2967     endif()
2968     if(DEFINED svn_password)
2969       set(svn_user_pw_args ${svn_user_pw_args} "--password=${svn_password}")
2970     endif()
2971     if(svn_trust_cert)
2972       set(svn_trust_cert_args --trust-server-cert)
2973     endif()
2974     set(cmd ${Subversion_SVN_EXECUTABLE} up ${svn_revision}
2975       --non-interactive ${svn_trust_cert_args} ${svn_user_pw_args})
2976     set(always 1)
2977   elseif(git_repository)
2978     # FetchContent gives us these directly, so don't try to recompute them
2979     if(NOT GIT_EXECUTABLE OR NOT GIT_VERSION_STRING)
2980       unset(CMAKE_MODULE_PATH) # Use CMake builtin find module
2981       find_package(Git QUIET)
2982       if(NOT GIT_EXECUTABLE)
2983         message(FATAL_ERROR "error: could not find git for fetch of ${name}")
2984       endif()
2985     endif()
2986     set(work_dir ${source_dir})
2987     set(comment "Performing update step for '${name}'")
2988     get_property(git_tag TARGET ${name} PROPERTY _EP_GIT_TAG)
2989     if(NOT git_tag)
2990       set(git_tag "master")
2991     endif()
2992     get_property(git_remote_name TARGET ${name} PROPERTY _EP_GIT_REMOTE_NAME)
2993     if(NOT git_remote_name)
2994       set(git_remote_name "origin")
2995     endif()
2996
2997     set(git_init_submodules TRUE)
2998     get_property(git_submodules_set TARGET ${name} PROPERTY _EP_GIT_SUBMODULES SET)
2999     if(git_submodules_set)
3000       get_property(git_submodules TARGET ${name} PROPERTY _EP_GIT_SUBMODULES)
3001       if(git_submodules  STREQUAL "" AND _EP_CMP0097 STREQUAL "NEW")
3002         set(git_init_submodules FALSE)
3003       endif()
3004     endif()
3005
3006     get_property(git_update_strategy TARGET ${name} PROPERTY _EP_GIT_REMOTE_UPDATE_STRATEGY)
3007     if(NOT git_update_strategy)
3008       set(git_update_strategy "${CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY}")
3009     endif()
3010     if(NOT git_update_strategy)
3011       set(git_update_strategy REBASE)
3012     endif()
3013     set(strategies CHECKOUT REBASE REBASE_CHECKOUT)
3014     if(NOT git_update_strategy IN_LIST strategies)
3015       message(FATAL_ERROR "'${git_update_strategy}' is not one of the supported strategies: ${strategies}")
3016     endif()
3017
3018     _ep_get_git_submodules_recurse(git_submodules_recurse)
3019
3020     _ep_write_gitupdate_script(${tmp_dir}/${name}-gitupdate.cmake
3021       ${GIT_EXECUTABLE} ${git_tag} ${git_remote_name} ${git_init_submodules} "${git_submodules_recurse}" "${git_submodules}" ${git_repository} ${work_dir} ${git_update_strategy}
3022       )
3023     set(cmd ${CMAKE_COMMAND} -P ${tmp_dir}/${name}-gitupdate.cmake)
3024     set(always 1)
3025   elseif(hg_repository)
3026     if(NOT HG_EXECUTABLE)
3027       message(FATAL_ERROR "error: could not find hg for pull of ${name}")
3028     endif()
3029     set(work_dir ${source_dir})
3030     set(comment "Performing update step (hg pull) for '${name}'")
3031     get_property(hg_tag TARGET ${name} PROPERTY _EP_HG_TAG)
3032     if(NOT hg_tag)
3033       set(hg_tag "tip")
3034     endif()
3035     if("${HG_VERSION_STRING}" STREQUAL "2.1")
3036       message(WARNING "Mercurial 2.1 does not distinguish an empty pull from a failed pull:
3037  http://mercurial.selenic.com/wiki/UpgradeNotes#A2.1.1:_revert_pull_return_code_change.2C_compile_issue_on_OS_X
3038  http://thread.gmane.org/gmane.comp.version-control.mercurial.devel/47656
3039 Update to Mercurial >= 2.1.1.
3040 ")
3041     endif()
3042     set(cmd ${HG_EXECUTABLE} pull
3043       COMMAND ${HG_EXECUTABLE} update ${hg_tag}
3044       )
3045     set(always 1)
3046   endif()
3047
3048   get_property(log TARGET ${name} PROPERTY _EP_LOG_UPDATE)
3049   if(log)
3050     set(log LOG 1)
3051   else()
3052     set(log "")
3053   endif()
3054
3055   get_property(uses_terminal TARGET ${name} PROPERTY
3056     _EP_USES_TERMINAL_UPDATE)
3057   if(uses_terminal)
3058     set(uses_terminal USES_TERMINAL 1)
3059   else()
3060     set(uses_terminal "")
3061   endif()
3062
3063   set(__cmdQuoted)
3064   foreach(__item IN LISTS cmd)
3065     string(APPEND __cmdQuoted " [==[${__item}]==]")
3066   endforeach()
3067   cmake_language(EVAL CODE "
3068     ExternalProject_Add_Step(${name} update
3069       INDEPENDENT TRUE
3070       COMMENT \${comment}
3071       COMMAND ${__cmdQuoted}
3072       ALWAYS \${always}
3073       EXCLUDE_FROM_MAIN \${update_disconnected}
3074       WORKING_DIRECTORY \${work_dir}
3075       DEPENDEES download
3076       ${log}
3077       ${uses_terminal}
3078       )"
3079   )
3080
3081 endfunction()
3082
3083
3084 function(_ep_add_patch_command name)
3085   ExternalProject_Get_Property(${name} source_dir)
3086
3087   get_property(cmd_set TARGET ${name} PROPERTY _EP_PATCH_COMMAND SET)
3088   get_property(cmd TARGET ${name} PROPERTY _EP_PATCH_COMMAND)
3089
3090   set(work_dir)
3091
3092   if(cmd_set)
3093     set(work_dir ${source_dir})
3094   endif()
3095
3096   get_property(log TARGET ${name} PROPERTY _EP_LOG_PATCH)
3097   if(log)
3098     set(log LOG 1)
3099   else()
3100     set(log "")
3101   endif()
3102
3103   _ep_get_update_disconnected(update_disconnected ${name})
3104   if(update_disconnected)
3105     set(patch_dep download)
3106   else()
3107     set(patch_dep update)
3108   endif()
3109
3110   set(__cmdQuoted)
3111   foreach(__item IN LISTS cmd)
3112     string(APPEND __cmdQuoted " [==[${__item}]==]")
3113   endforeach()
3114   cmake_language(EVAL CODE "
3115     ExternalProject_Add_Step(${name} patch
3116       INDEPENDENT TRUE
3117       COMMAND ${__cmdQuoted}
3118       WORKING_DIRECTORY \${work_dir}
3119       DEPENDEES \${patch_dep}
3120       ${log}
3121       )"
3122   )
3123 endfunction()
3124
3125 function(_ep_get_file_deps var name)
3126   set(file_deps)
3127
3128   get_property(deps TARGET ${name} PROPERTY _EP_DEPENDS)
3129   foreach(dep IN LISTS deps)
3130     get_property(dep_type TARGET ${dep} PROPERTY TYPE)
3131     if(dep_type STREQUAL "UTILITY")
3132       get_property(is_ep TARGET ${dep} PROPERTY _EP_IS_EXTERNAL_PROJECT)
3133       if(is_ep)
3134         _ep_get_step_stampfile(${dep} "done" done_stamp_file)
3135         list(APPEND file_deps ${done_stamp_file})
3136       endif()
3137     endif()
3138   endforeach()
3139
3140   set("${var}" "${file_deps}" PARENT_SCOPE)
3141 endfunction()
3142
3143 function(_ep_extract_configure_command var name)
3144   get_property(cmd_set TARGET ${name} PROPERTY _EP_CONFIGURE_COMMAND SET)
3145   if(cmd_set)
3146     get_property(cmd TARGET ${name} PROPERTY _EP_CONFIGURE_COMMAND)
3147   else()
3148     get_target_property(cmake_command ${name} _EP_CMAKE_COMMAND)
3149     if(cmake_command)
3150       set(cmd "${cmake_command}")
3151     else()
3152       set(cmd "${CMAKE_COMMAND}")
3153     endif()
3154
3155     get_property(cmake_args TARGET ${name} PROPERTY _EP_CMAKE_ARGS)
3156     list(APPEND cmd ${cmake_args})
3157
3158     # If there are any CMAKE_CACHE_ARGS or CMAKE_CACHE_DEFAULT_ARGS,
3159     # write an initial cache and use it
3160     get_property(cmake_cache_args TARGET ${name} PROPERTY _EP_CMAKE_CACHE_ARGS)
3161     get_property(cmake_cache_default_args TARGET ${name} PROPERTY _EP_CMAKE_CACHE_DEFAULT_ARGS)
3162
3163     set(has_cmake_cache_args 0)
3164     if(NOT "${cmake_cache_args}" STREQUAL "")
3165       set(has_cmake_cache_args 1)
3166     endif()
3167
3168     set(has_cmake_cache_default_args 0)
3169     if(NOT "${cmake_cache_default_args}" STREQUAL "")
3170       set(has_cmake_cache_default_args 1)
3171     endif()
3172
3173     get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR)
3174     get_target_property(cmake_generator_instance ${name} _EP_CMAKE_GENERATOR_INSTANCE)
3175     get_target_property(cmake_generator_platform ${name} _EP_CMAKE_GENERATOR_PLATFORM)
3176     get_target_property(cmake_generator_toolset ${name} _EP_CMAKE_GENERATOR_TOOLSET)
3177     if(cmake_generator)
3178       list(APPEND cmd "-G${cmake_generator}")
3179       if(cmake_generator_platform)
3180         list(APPEND cmd "-A${cmake_generator_platform}")
3181       endif()
3182       if(cmake_generator_toolset)
3183         list(APPEND cmd "-T${cmake_generator_toolset}")
3184       endif()
3185       if(cmake_generator_instance)
3186         list(APPEND cmd "-DCMAKE_GENERATOR_INSTANCE:INTERNAL=${cmake_generator_instance}")
3187       endif()
3188     else()
3189       if(CMAKE_EXTRA_GENERATOR)
3190         list(APPEND cmd "-G${CMAKE_EXTRA_GENERATOR} - ${CMAKE_GENERATOR}")
3191       else()
3192         list(APPEND cmd "-G${CMAKE_GENERATOR}")
3193         if("${CMAKE_GENERATOR}" MATCHES "Green Hills MULTI")
3194           set(has_cmake_cache_default_args 1)
3195           set(cmake_cache_default_args ${cmake_cache_default_args}
3196             "-DGHS_TARGET_PLATFORM:STRING=${GHS_TARGET_PLATFORM}"
3197             "-DGHS_PRIMARY_TARGET:STRING=${GHS_PRIMARY_TARGET}"
3198             "-DGHS_TOOLSET_ROOT:STRING=${GHS_TOOLSET_ROOT}"
3199             "-DGHS_OS_ROOT:STRING=${GHS_OS_ROOT}"
3200             "-DGHS_OS_DIR:STRING=${GHS_OS_DIR}"
3201             "-DGHS_BSP_NAME:STRING=${GHS_BSP_NAME}")
3202         endif()
3203       endif()
3204       if(cmake_generator_platform)
3205         message(FATAL_ERROR "Option CMAKE_GENERATOR_PLATFORM not allowed without CMAKE_GENERATOR.")
3206       endif()
3207       if(CMAKE_GENERATOR_PLATFORM)
3208         list(APPEND cmd "-A${CMAKE_GENERATOR_PLATFORM}")
3209       endif()
3210       if(cmake_generator_toolset)
3211         message(FATAL_ERROR "Option CMAKE_GENERATOR_TOOLSET not allowed without CMAKE_GENERATOR.")
3212       endif()
3213       if(CMAKE_GENERATOR_TOOLSET)
3214         list(APPEND cmd "-T${CMAKE_GENERATOR_TOOLSET}")
3215       endif()
3216       if(cmake_generator_instance)
3217         message(FATAL_ERROR "Option CMAKE_GENERATOR_INSTANCE not allowed without CMAKE_GENERATOR.")
3218       endif()
3219       if(CMAKE_GENERATOR_INSTANCE)
3220         list(APPEND cmd "-DCMAKE_GENERATOR_INSTANCE:INTERNAL=${CMAKE_GENERATOR_INSTANCE}")
3221       endif()
3222     endif()
3223
3224     if(has_cmake_cache_args OR has_cmake_cache_default_args)
3225       set(_ep_cache_args_script "<TMP_DIR>/${name}-cache-$<CONFIG>.cmake")
3226       if(has_cmake_cache_args)
3227         _ep_command_line_to_initial_cache(script_initial_cache_force "${cmake_cache_args}" 1)
3228       endif()
3229       if(has_cmake_cache_default_args)
3230         _ep_command_line_to_initial_cache(script_initial_cache_default "${cmake_cache_default_args}" 0)
3231       endif()
3232       _ep_write_initial_cache(${name} "${_ep_cache_args_script}" "${script_initial_cache_force}${script_initial_cache_default}")
3233       list(APPEND cmd "-C${_ep_cache_args_script}")
3234       _ep_replace_location_tags(${name} _ep_cache_args_script)
3235       set(_ep_cache_args_script
3236         "${_ep_cache_args_script}"
3237         PARENT_SCOPE)
3238     endif()
3239
3240     list(APPEND cmd "<SOURCE_DIR><SOURCE_SUBDIR>")
3241   endif()
3242
3243   set("${var}" "${cmd}" PARENT_SCOPE)
3244 endfunction()
3245
3246 # TODO: Make sure external projects use the proper compiler
3247 function(_ep_add_configure_command name)
3248   ExternalProject_Get_Property(${name} binary_dir tmp_dir)
3249
3250   set(file_deps)
3251   get_property(configure_handled_by_build TARGET ${name}
3252                PROPERTY _EP_CONFIGURE_HANDLED_BY_BUILD)
3253   if(NOT configure_handled_by_build)
3254     # Depend on other external projects (file-level)
3255     _ep_get_file_deps(file_deps ${name})
3256   endif()
3257
3258   _ep_extract_configure_command(cmd ${name})
3259
3260   # If anything about the configure command changes, (command itself, cmake
3261   # used, cmake args or cmake generator) then re-run the configure step.
3262   # Fixes issue https://gitlab.kitware.com/cmake/cmake/-/issues/10258
3263   #
3264   if(NOT EXISTS ${tmp_dir}/${name}-cfgcmd.txt.in)
3265     file(WRITE ${tmp_dir}/${name}-cfgcmd.txt.in "cmd='\@cmd\@'\n")
3266   endif()
3267   configure_file(${tmp_dir}/${name}-cfgcmd.txt.in ${tmp_dir}/${name}-cfgcmd.txt)
3268   list(APPEND file_deps ${tmp_dir}/${name}-cfgcmd.txt)
3269   list(APPEND file_deps ${_ep_cache_args_script})
3270
3271   get_property(log TARGET ${name} PROPERTY _EP_LOG_CONFIGURE)
3272   if(log)
3273     set(log LOG 1)
3274   else()
3275     set(log "")
3276   endif()
3277
3278   get_property(uses_terminal TARGET ${name} PROPERTY
3279     _EP_USES_TERMINAL_CONFIGURE)
3280   if(uses_terminal)
3281     set(uses_terminal USES_TERMINAL 1)
3282   else()
3283     set(uses_terminal "")
3284   endif()
3285
3286   set(__cmdQuoted)
3287   foreach(__item IN LISTS cmd)
3288     string(APPEND __cmdQuoted " [==[${__item}]==]")
3289   endforeach()
3290   cmake_language(EVAL CODE "
3291     ExternalProject_Add_Step(${name} configure
3292       INDEPENDENT FALSE
3293       COMMAND ${__cmdQuoted}
3294       WORKING_DIRECTORY \${binary_dir}
3295       DEPENDEES patch
3296       DEPENDS \${file_deps}
3297       ${log}
3298       ${uses_terminal}
3299       )"
3300   )
3301 endfunction()
3302
3303
3304 function(_ep_add_build_command name)
3305   ExternalProject_Get_Property(${name} binary_dir)
3306
3307   set(file_deps)
3308   get_property(configure_handled_by_build TARGET ${name}
3309                PROPERTY _EP_CONFIGURE_HANDLED_BY_BUILD)
3310   if(configure_handled_by_build)
3311     # Depend on other external projects (file-level)
3312     _ep_get_file_deps(file_deps ${name})
3313   endif()
3314
3315   get_property(cmd_set TARGET ${name} PROPERTY _EP_BUILD_COMMAND SET)
3316   if(cmd_set)
3317     get_property(cmd TARGET ${name} PROPERTY _EP_BUILD_COMMAND)
3318   else()
3319     _ep_get_build_command(${name} BUILD cmd)
3320   endif()
3321
3322   get_property(log TARGET ${name} PROPERTY _EP_LOG_BUILD)
3323   if(log)
3324     set(log LOG 1)
3325   else()
3326     set(log "")
3327   endif()
3328
3329   get_property(uses_terminal TARGET ${name} PROPERTY
3330     _EP_USES_TERMINAL_BUILD)
3331   if(uses_terminal)
3332     set(uses_terminal USES_TERMINAL 1)
3333   else()
3334     set(uses_terminal "")
3335   endif()
3336
3337   get_property(build_always TARGET ${name} PROPERTY _EP_BUILD_ALWAYS)
3338   if(build_always)
3339     set(always 1)
3340   else()
3341     set(always 0)
3342   endif()
3343
3344   get_property(build_byproducts TARGET ${name} PROPERTY _EP_BUILD_BYPRODUCTS)
3345
3346   set(__cmdQuoted)
3347   foreach(__item IN LISTS cmd)
3348     string(APPEND __cmdQuoted " [==[${__item}]==]")
3349   endforeach()
3350   cmake_language(EVAL CODE "
3351     ExternalProject_Add_Step(${name} build
3352       INDEPENDENT FALSE
3353       COMMAND ${__cmdQuoted}
3354       BYPRODUCTS \${build_byproducts}
3355       WORKING_DIRECTORY \${binary_dir}
3356       DEPENDEES configure
3357       DEPENDS \${file_deps}
3358       ALWAYS \${always}
3359       ${log}
3360       ${uses_terminal}
3361       )"
3362   )
3363 endfunction()
3364
3365
3366 function(_ep_add_install_command name)
3367   ExternalProject_Get_Property(${name} binary_dir)
3368
3369   get_property(cmd_set TARGET ${name} PROPERTY _EP_INSTALL_COMMAND SET)
3370   if(cmd_set)
3371     get_property(cmd TARGET ${name} PROPERTY _EP_INSTALL_COMMAND)
3372   else()
3373     _ep_get_build_command(${name} INSTALL cmd)
3374   endif()
3375
3376   get_property(log TARGET ${name} PROPERTY _EP_LOG_INSTALL)
3377   if(log)
3378     set(log LOG 1)
3379   else()
3380     set(log "")
3381   endif()
3382
3383   get_property(uses_terminal TARGET ${name} PROPERTY
3384     _EP_USES_TERMINAL_INSTALL)
3385   if(uses_terminal)
3386     set(uses_terminal USES_TERMINAL 1)
3387   else()
3388     set(uses_terminal "")
3389   endif()
3390
3391   set(__cmdQuoted)
3392   foreach(__item IN LISTS cmd)
3393     string(APPEND __cmdQuoted " [==[${__item}]==]")
3394   endforeach()
3395   cmake_language(EVAL CODE "
3396     ExternalProject_Add_Step(${name} install
3397       INDEPENDENT FALSE
3398       COMMAND ${__cmdQuoted}
3399       WORKING_DIRECTORY \${binary_dir}
3400       DEPENDEES build
3401       ${log}
3402       ${uses_terminal}
3403       )"
3404   )
3405 endfunction()
3406
3407
3408 function(_ep_add_test_command name)
3409   ExternalProject_Get_Property(${name} binary_dir)
3410
3411   get_property(before TARGET ${name} PROPERTY _EP_TEST_BEFORE_INSTALL)
3412   get_property(after TARGET ${name} PROPERTY _EP_TEST_AFTER_INSTALL)
3413   get_property(exclude TARGET ${name} PROPERTY _EP_TEST_EXCLUDE_FROM_MAIN)
3414   get_property(cmd_set TARGET ${name} PROPERTY _EP_TEST_COMMAND SET)
3415
3416   # Only actually add the test step if one of the test related properties is
3417   # explicitly set. (i.e. the test step is omitted unless requested...)
3418   #
3419   if(cmd_set OR before OR after OR exclude)
3420     if(cmd_set)
3421       get_property(cmd TARGET ${name} PROPERTY _EP_TEST_COMMAND)
3422     else()
3423       _ep_get_build_command(${name} TEST cmd)
3424     endif()
3425
3426     if(before)
3427       set(dependees_args DEPENDEES build)
3428     else()
3429       set(dependees_args DEPENDEES install)
3430     endif()
3431
3432     if(exclude)
3433       set(dependers_args "")
3434       set(exclude_args EXCLUDE_FROM_MAIN 1)
3435     else()
3436       if(before)
3437         set(dependers_args DEPENDERS install)
3438       else()
3439         set(dependers_args "")
3440       endif()
3441       set(exclude_args "")
3442     endif()
3443
3444     get_property(log TARGET ${name} PROPERTY _EP_LOG_TEST)
3445     if(log)
3446       set(log LOG 1)
3447     else()
3448       set(log "")
3449     endif()
3450
3451     get_property(uses_terminal TARGET ${name} PROPERTY
3452       _EP_USES_TERMINAL_TEST)
3453     if(uses_terminal)
3454       set(uses_terminal USES_TERMINAL 1)
3455     else()
3456       set(uses_terminal "")
3457     endif()
3458
3459     set(__cmdQuoted)
3460     foreach(__item IN LISTS cmd)
3461       string(APPEND __cmdQuoted " [==[${__item}]==]")
3462     endforeach()
3463     cmake_language(EVAL CODE "
3464       ExternalProject_Add_Step(${name} test
3465         INDEPENDENT FALSE
3466         COMMAND ${__cmdQuoted}
3467         WORKING_DIRECTORY \${binary_dir}
3468         ${dependees_args}
3469         ${dependers_args}
3470         ${exclude_args}
3471         ${log}
3472         ${uses_terminal}
3473         )"
3474     )
3475   endif()
3476 endfunction()
3477
3478
3479 function(ExternalProject_Add name)
3480   cmake_policy(GET CMP0097 _EP_CMP0097
3481     PARENT_SCOPE # undocumented, do not use outside of CMake
3482     )
3483   cmake_policy(GET CMP0114 cmp0114
3484     PARENT_SCOPE # undocumented, do not use outside of CMake
3485     )
3486   if(CMAKE_XCODE_BUILD_SYSTEM VERSION_GREATER_EQUAL 12 AND NOT cmp0114 STREQUAL "NEW")
3487     message(AUTHOR_WARNING
3488       "Policy CMP0114 is not set to NEW.  "
3489       "In order to support the Xcode \"new build system\", "
3490       "this project must be updated to set policy CMP0114 to NEW."
3491       "\n"
3492       "Since CMake is generating for the Xcode \"new build system\", "
3493       "ExternalProject_Add will use policy CMP0114's NEW behavior anyway, "
3494       "but the generated build system may not match what the project intends."
3495       )
3496     set(cmp0114 "NEW")
3497   endif()
3498
3499   _ep_get_configuration_subdir_suffix(cfgdir)
3500
3501   # Add a custom target for the external project.
3502   set(cmf_dir ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles)
3503   _ep_get_complete_stampfile(${name} complete_stamp_file)
3504
3505   cmake_policy(PUSH)
3506   if(cmp0114 STREQUAL "NEW")
3507     # To implement CMP0114 NEW behavior with Makefile generators,
3508     # we need CMP0113 NEW behavior.
3509     cmake_policy(SET CMP0113 NEW)
3510   endif()
3511   # The "ALL" option to add_custom_target just tells it to not set the
3512   # EXCLUDE_FROM_ALL target property. Later, if the EXCLUDE_FROM_ALL
3513   # argument was passed, we explicitly set it for the target.
3514   add_custom_target(${name} ALL DEPENDS ${complete_stamp_file})
3515   cmake_policy(POP)
3516   set_property(TARGET ${name} PROPERTY _EP_IS_EXTERNAL_PROJECT 1)
3517   set_property(TARGET ${name} PROPERTY LABELS ${name})
3518   set_property(TARGET ${name} PROPERTY FOLDER "ExternalProjectTargets/${name}")
3519
3520   set_property(TARGET ${name} PROPERTY _EP_CMP0114 "${cmp0114}")
3521
3522   set(keywords
3523     #
3524     # Directory options
3525     #
3526     PREFIX
3527     TMP_DIR
3528     STAMP_DIR
3529     LOG_DIR
3530     DOWNLOAD_DIR
3531     SOURCE_DIR
3532     BINARY_DIR
3533     INSTALL_DIR
3534     #
3535     # Download step options
3536     #
3537     DOWNLOAD_COMMAND
3538     #
3539     URL
3540     URL_HASH
3541     URL_MD5
3542     DOWNLOAD_NAME
3543     DOWNLOAD_NO_EXTRACT
3544     DOWNLOAD_NO_PROGRESS
3545     TIMEOUT
3546     INACTIVITY_TIMEOUT
3547     HTTP_USERNAME
3548     HTTP_PASSWORD
3549     HTTP_HEADER
3550     TLS_VERIFY     # Also used for git clone operations
3551     TLS_CAINFO
3552     NETRC
3553     NETRC_FILE
3554     #
3555     GIT_REPOSITORY
3556     GIT_TAG
3557     GIT_REMOTE_NAME
3558     GIT_SUBMODULES
3559     GIT_SUBMODULES_RECURSE
3560     GIT_SHALLOW
3561     GIT_PROGRESS
3562     GIT_CONFIG
3563     GIT_REMOTE_UPDATE_STRATEGY
3564     #
3565     SVN_REPOSITORY
3566     SVN_REVISION
3567     SVN_USERNAME
3568     SVN_PASSWORD
3569     SVN_TRUST_CERT
3570     #
3571     HG_REPOSITORY
3572     HG_TAG
3573     #
3574     CVS_REPOSITORY
3575     CVS_MODULE
3576     CVS_TAG
3577     #
3578     # Update step options
3579     #
3580     UPDATE_COMMAND
3581     UPDATE_DISCONNECTED
3582     #
3583     # Patch step options
3584     #
3585     PATCH_COMMAND
3586     #
3587     # Configure step options
3588     #
3589     CONFIGURE_COMMAND
3590     CMAKE_COMMAND
3591     CMAKE_GENERATOR
3592     CMAKE_GENERATOR_PLATFORM
3593     CMAKE_GENERATOR_TOOLSET
3594     CMAKE_GENERATOR_INSTANCE
3595     CMAKE_ARGS
3596     CMAKE_CACHE_ARGS
3597     CMAKE_CACHE_DEFAULT_ARGS
3598     SOURCE_SUBDIR
3599     CONFIGURE_HANDLED_BY_BUILD
3600     #
3601     # Build step options
3602     #
3603     BUILD_COMMAND
3604     BUILD_IN_SOURCE
3605     BUILD_ALWAYS
3606     BUILD_BYPRODUCTS
3607     #
3608     # Install step options
3609     #
3610     INSTALL_COMMAND
3611     #
3612     # Test step options
3613     #
3614     TEST_COMMAND
3615     TEST_BEFORE_INSTALL
3616     TEST_AFTER_INSTALL
3617     TEST_EXCLUDE_FROM_MAIN
3618     #
3619     # Logging options
3620     #
3621     LOG_DOWNLOAD
3622     LOG_UPDATE
3623     LOG_PATCH
3624     LOG_CONFIGURE
3625     LOG_BUILD
3626     LOG_INSTALL
3627     LOG_TEST
3628     LOG_MERGED_STDOUTERR
3629     LOG_OUTPUT_ON_FAILURE
3630     #
3631     # Terminal access options
3632     #
3633     USES_TERMINAL_DOWNLOAD
3634     USES_TERMINAL_UPDATE
3635     USES_TERMINAL_CONFIGURE
3636     USES_TERMINAL_BUILD
3637     USES_TERMINAL_INSTALL
3638     USES_TERMINAL_TEST
3639     #
3640     # Target options
3641     #
3642     DEPENDS
3643     EXCLUDE_FROM_ALL
3644     STEP_TARGETS
3645     INDEPENDENT_STEP_TARGETS
3646     #
3647     # Miscellaneous options
3648     #
3649     LIST_SEPARATOR
3650   )
3651   _ep_parse_arguments(ExternalProject_Add "${keywords}" ${name} _EP_ "${ARGN}")
3652   _ep_set_directories(${name})
3653   _ep_get_step_stampfile(${name} "done" done_stamp_file)
3654   _ep_get_step_stampfile(${name} "install" install_stamp_file)
3655
3656   # Set the EXCLUDE_FROM_ALL target property if required.
3657   get_property(exclude_from_all TARGET ${name} PROPERTY _EP_EXCLUDE_FROM_ALL)
3658   if(exclude_from_all)
3659     set_property(TARGET ${name} PROPERTY EXCLUDE_FROM_ALL TRUE)
3660   endif()
3661
3662   # The 'complete' step depends on all other steps and creates a
3663   # 'done' mark.  A dependent external project's 'configure' step
3664   # depends on the 'done' mark so that it rebuilds when this project
3665   # rebuilds.  It is important that 'done' is not the output of any
3666   # custom command so that CMake does not propagate build rules to
3667   # other external project targets, which may cause problems during
3668   # parallel builds.  However, the Ninja generator needs to see the entire
3669   # dependency graph, and can cope with custom commands belonging to
3670   # multiple targets, so we add the 'done' mark as an output for Ninja only.
3671   set(complete_outputs ${complete_stamp_file})
3672   if(${CMAKE_GENERATOR} MATCHES "Ninja")
3673     set(complete_outputs ${complete_outputs} ${done_stamp_file})
3674   endif()
3675
3676   add_custom_command(
3677     OUTPUT ${complete_outputs}
3678     COMMENT "Completed '${name}'"
3679     COMMAND ${CMAKE_COMMAND} -E make_directory ${cmf_dir}${cfgdir}
3680     COMMAND ${CMAKE_COMMAND} -E touch ${complete_stamp_file}
3681     COMMAND ${CMAKE_COMMAND} -E touch ${done_stamp_file}
3682     DEPENDS ${install_stamp_file}
3683     VERBATIM
3684     )
3685
3686
3687   # Depend on other external projects (target-level).
3688   get_property(deps TARGET ${name} PROPERTY _EP_DEPENDS)
3689   foreach(arg IN LISTS deps)
3690     add_dependencies(${name} ${arg})
3691   endforeach()
3692
3693   # Set up custom build steps based on the target properties.
3694   # Each step depends on the previous one.
3695   #
3696   # The target depends on the output of the final step.
3697   # (Already set up above in the DEPENDS of the add_custom_target command.)
3698   #
3699   _ep_add_mkdir_command(${name})
3700   _ep_add_download_command(${name})
3701   _ep_add_update_command(${name})
3702   _ep_add_patch_command(${name})
3703   _ep_add_configure_command(${name})
3704   _ep_add_build_command(${name})
3705   _ep_add_install_command(${name})
3706
3707   # Test is special in that it might depend on build, or it might depend
3708   # on install.
3709   #
3710   _ep_add_test_command(${name})
3711 endfunction()
3712
3713 cmake_policy(POP)