ExternalProject.cmake 112 KB
Newer Older
1
2
3
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

4
5
6
7
#[=======================================================================[.rst:
ExternalProject
---------------

8
9
10
11
12
13
.. only:: html

   .. contents::

External Project Definition
^^^^^^^^^^^^^^^^^^^^^^^^^^^
14

15
16
.. command:: ExternalProject_Add

17
  The ``ExternalProject_Add()`` function creates a custom target to drive
18
19
20
  download, update/patch, configure, build, install and test steps of an
  external project::

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
    ExternalProject_Add(<name> [<option>...])

  The individual steps within the process can be driven independently if
  required (e.g. for CDash submission) and extra custom steps can be defined,
  along with the ability to control the step dependencies. The directory
  structure used for the management of the external project can also be
  customized. The function supports a large number of options which can be used
  to tailor the external project behavior.

  **Directory Options:**
    Most of the time, the default directory layout is sufficient. It is largely
    an implementation detail that the main project usually doesn't need to
    change. In some circumstances, however, control over the directory layout
    can be useful or necessary. The directory options are potentially more
    useful from the point of view that the main build can use the
    :command:`ExternalProject_Get_Property` command to retrieve their values,
    thereby allowing the main project to refer to build artifacts of the
    external project.

    ``PREFIX <dir>``
      Root directory for the external project. Unless otherwise noted below,
      all other directories associated with the external project will be
      created under here.

    ``TMP_DIR <dir>``
      Directory in which to store temporary files.

    ``STAMP_DIR <dir>``
      Directory in which to store the timestamps of each step. Log files from
      individual steps are also created in here (see *Logging Options* below).

    ``DOWNLOAD_DIR <dir>``
      Directory in which to store downloaded files before unpacking them. This
      directory is only used by the URL download method, all other download
      methods use ``SOURCE_DIR`` directly instead.

    ``SOURCE_DIR <dir>``
      Source directory into which downloaded contents will be unpacked, or for
      non-URL download methods, the directory in which the repository should be
      checked out, cloned, etc. If no download method is specified, this must
      point to an existing directory where the external project has already
      been unpacked or cloned/checked out.

      .. note::
         If a download method is specified, any existing contents of the source
         directory may be deleted. Only the URL download method checks whether
         this directory is either missing or empty before initiating the
         download, stopping with an error if it is not empty. All other
         download methods silently discard any previous contents of the source
         directory.

    ``BINARY_DIR <dir>``
      Specify the build directory location. This option is ignored if
      ``BUILD_IN_SOURCE`` is enabled.

    ``INSTALL_DIR <dir>``
      Installation prefix to be placed in the ``<INSTALL_DIR>`` placeholder.
      This does not actually configure the external project to install to
      the given prefix. That must be done by passing appropriate arguments
      to the external project configuration step, e.g. using ``<INSTALL_DIR>``.

    If any of the above ``..._DIR`` options are not specified, their defaults
    are computed as follows. If the ``PREFIX`` option is given or the
    ``EP_PREFIX`` directory property is set, then an external project is built
    and installed under the specified prefix::

      TMP_DIR      = <prefix>/tmp
      STAMP_DIR    = <prefix>/src/<name>-stamp
      DOWNLOAD_DIR = <prefix>/src
      SOURCE_DIR   = <prefix>/src/<name>
      BINARY_DIR   = <prefix>/src/<name>-build
      INSTALL_DIR  = <prefix>

    Otherwise, if the ``EP_BASE`` directory property is set then components
    of an external project are stored under the specified base::

      TMP_DIR      = <base>/tmp/<name>
      STAMP_DIR    = <base>/Stamp/<name>
      DOWNLOAD_DIR = <base>/Download/<name>
      SOURCE_DIR   = <base>/Source/<name>
      BINARY_DIR   = <base>/Build/<name>
      INSTALL_DIR  = <base>/Install/<name>

    If no ``PREFIX``, ``EP_PREFIX``, or ``EP_BASE`` is specified, then the
    default is to set ``PREFIX`` to ``<name>-prefix``. Relative paths are
    interpreted with respect to :variable:`CMAKE_CURRENT_BINARY_DIR` at the
    point where ``ExternalProject_Add()`` is called.

  **Download Step Options:**
    A download method can be omitted if the ``SOURCE_DIR`` option is used to
    point to an existing non-empty directory. Otherwise, one of the download
    methods below must be specified (multiple download methods should not be
    given) or a custom ``DOWNLOAD_COMMAND`` provided.

    ``DOWNLOAD_COMMAND <cmd>...``
      Overrides the command used for the download step
      (:manual:`generator expressions <cmake-generator-expressions(7)>` are
      supported). If this option is specified, all other download options will
      be ignored. Providing an empty string for ``<cmd>`` effectively disables
      the download step.

    *URL Download*
      ``URL <url1> [<url2>...]``
        List of paths and/or URL(s) of the external project's source. When more
        than one URL is given, they are tried in turn until one succeeds. A URL
        may be an ordinary path in the local file system (in which case it
        must be the only URL provided) or any downloadable URL supported by the
        :command:`file(DOWNLOAD)` command. A local filesystem path may refer to
        either an existing directory or to an archive file, whereas a URL is
        expected to point to a file which can be treated as an archive. When an
        archive is used, it will be unpacked automatically unless the
        ``DOWNLOAD_NO_EXTRACT`` option is set to prevent it. The archive type
        is determined by inspecting the actual content rather than using logic
        based on the file extension.

      ``URL_HASH ALGO=<value>``
        Hash of the archive file to be downloaded. The ``<value>`` should be of
        the form ``algo=hashValue`` where ``algo`` can be any of the hashing
        algorithms supported by the :command:`file()` command. Specifying this
        option is strongly recommended for URL downloads, as it ensures the
        integrity of the downloaded content. It is also used as a check for a
        previously downloaded file, allowing connection to the remote location
        to be avoided altogether if the local directory already has a file from
        an earlier download that matches the specified hash.

      ``URL_MD5 <md5>``
        Equivalent to ``URL_HASH MD5=<md5>``.

      ``DOWNLOAD_NAME <fname>``
        File name to use for the downloaded file. If not given, the end of the
        URL is used to determine the file name. This option is rarely needed,
        the default name is generally suitable and is not normally used outside
        of code internal to the ``ExternalProject`` module.

      ``DOWNLOAD_NO_EXTRACT <bool>``
        Allows the extraction part of the download step to be disabled by
        passing a boolean true value for this option. If this option is not
        given, the downloaded contents will be unpacked automatically if
        required. If extraction has been disabled, the full path to the
        downloaded file is available as ``<DOWNLOADED_FILE>`` in subsequent
        steps or as the property ``DOWNLOADED_FILE`` with the
        :command:`ExternalProject_Get_Property` command.

      ``DOWNLOAD_NO_PROGRESS <bool>``
        Can be used to disable logging the download progress. If this option is
        not given, download progress messages will be logged.

      ``TIMEOUT <seconds>``
        Maximum time allowed for file download operations.

      ``HTTP_USERNAME <username>``
        Username for the download operation if authentication is required.

      ``HTTP_PASSWORD <password>``
        Password for the download operation if authentication is required.

      ``HTTP_HEADER <header1> [<header2>...]``
        Provides an arbitrary list of HTTP headers for the download operation.
        This can be useful for accessing content in systems like AWS, etc.

      ``TLS_VERIFY <bool>``
        Specifies whether certificate verification should be performed for
        https URLs. If this option is not provided, the default behavior is
        determined by the ``CMAKE_TLS_VERIFY`` variable (see
        :command:`file(DOWNLOAD)`). If that is also not set, certificate
        verification will not be performed. In situations where ``URL_HASH``
        cannot be provided, this option can be an alternative verification
        measure.

      ``TLS_CAINFO <file>``
        Specify a custom certificate authority file to use if ``TLS_VERIFY``
        is enabled. If this option is not specified, the value of the
        ``CMAKE_TLS_CAINFO`` variable will be used instead (see
        :command:`file(DOWNLOAD)`)

    *Git*
      NOTE: A git version of 1.6.5 or later is required if this download method
      is used.

      ``GIT_REPOSITORY <url>``
        URL of the git repository. Any URL understood by the ``git`` command
        may be used.

      ``GIT_TAG <tag>``
        Git branch name, tag or commit hash. Note that branch names and tags
        should generally be specified as remote names (i.e. ``origin/myBranch``
        rather than simply ``myBranch``). This ensures that if the remote end
        has its tag moved or branch rebased or history rewritten, the local
        clone will still be updated correctly. In general, however, specifying
        a commit hash should be preferred for a number of reasons:

        - If the local clone already has the commit corresponding to the hash,
          no ``git fetch`` needs to be performed to check for changes each time
          CMake is re-run. This can result in a significant speed up if many
          external projects are being used.
        - Using a specific git hash ensures that the main project's own history
          is fully traceable to a specific point in the external project's
          evolution. If a branch or tag name is used instead, then checking out
          a specific commit of the main project doesn't necessarily pin the
          whole build to a specific point in the life of the external project.
          The lack of such deterministic behavior makes the main project lose
          traceability and repeatability.

      ``GIT_REMOTE_NAME <name>``
        The optional name of the remote. If this option is not specified, it
        defaults to ``origin``.

      ``GIT_SUBMODULES <module>...``
        Specific git submodules that should also be updated. If this option is
        not provided, all git submodules will be updated.

      ``GIT_SHALLOW <bool>``
        When this option is enabled, the ``git clone`` operation will be given
        the ``--depth 1`` option. This performs a shallow clone, which avoids
        downloading the whole history and instead retrieves just the commit
        denoted by the ``GIT_TAG`` option.

      ``GIT_PROGRESS <bool>``
        When enabled, this option instructs the ``git clone`` operation to
        report its progress by passing it the ``--progress`` option. Without
        this option, the clone step for large projects may appear to make the
        build stall, since nothing will be logged until the clone operation
        finishes. While this option can be used to provide progress to prevent
        the appearance of the build having stalled, it may also make the build
        overly noisy if lots of external projects are used.

      ``GIT_CONFIG <option1> [<option2>...]``
        Specify a list of config options to pass to ``git clone``. Each option
        listed will be transformed into its own ``--config <option>`` on the
        ``git clone`` command line, with each option required to be in the
        form ``key=value``.

    *Subversion*
      ``SVN_REPOSITORY <url>``
        URL of the Subversion repository.

      ``SVN_REVISION -r<rev>``
        Revision to checkout from the Subversion repository.

      ``SVN_USERNAME <username>``
        Username for the Subversion checkout and update.

      ``SVN_PASSWORD <password>``
        Password for the Subversion checkout and update.

      ``SVN_TRUST_CERT <bool>``
        Specifies whether to trust the Subversion server site certificate. If
        enabled, the ``--trust-server-cert`` option is passed to the ``svn``
        checkout and update commands.

    *Mercurial*
      ``HG_REPOSITORY <url>``
        URL of the mercurial repository.

      ``HG_TAG <tag>``
        Mercurial branch name, tag or commit id.

    *CVS*
      ``CVS_REPOSITORY <cvsroot>``
        CVSROOT of the CVS repository.

      ``CVS_MODULE <mod>``
        Module to checkout from the CVS repository.

      ``CVS_TAG <tag>``
        Tag to checkout from the CVS repository.

  **Update/Patch Step Options:**
    Whenever CMake is re-run, by default the external project's sources will be
    updated if the download method supports updates (e.g. a git repository
    would be checked if the ``GIT_TAG`` does not refer to a specific commit).

    ``UPDATE_COMMAND <cmd>...``
      Overrides the download method's update step with a custom command.
      The command may use
      :manual:`generator expressions <cmake-generator-expressions(7)>`.

    ``UPDATE_DISCONNECTED <bool>``
      When enabled, this option causes the update step to be skipped. It does
      not, however, prevent the download step. The update step can still be
      added as a step target (see :command:`ExternalProject_Add_StepTargets`)
      and called manually. This is useful if you want to allow developers to
      build the project when disconnected from the network (the network may
      still be needed for the download step though).

      When this option is present, it is generally advisable to make the value
      a cache variable under the developer's control rather than hard-coding
      it. If this option is not present, the default value is taken from the
      ``EP_UPDATE_DISCONNECTED`` directory property. If that is also not
      defined, updates are performed as normal. The ``EP_UPDATE_DISCONNECTED``
      directory property is intended as a convenience for controlling the
      ``UPDATE_DISCONNECTED`` behavior for an entire section of a project's
      directory hierarchy and may be a more convenient method of giving
      developers control over whether or not to perform updates (assuming the
      project also provides a cache variable or some other convenient method
      for setting the directory property).

    ``PATCH_COMMAND <cmd>...``
      Specifies a custom command to patch the sources after an update. By
      default, no patch command is defined. Note that it can be quite difficult
      to define an appropriate patch command that performs robustly, especially
      for download methods such as git where changing the ``GIT_TAG`` will not
      discard changes from a previous patch, but the patch command will be
      called again after updating to the new tag.

  **Configure Step Options:**
    The configure step is run after the download and update steps. By default,
    the external project is assumed to be a CMake project, but this can be
    overridden if required.

    ``CONFIGURE_COMMAND <cmd>...``
      The default configure command runs CMake with options based on the main
      project. For non-CMake external projects, the ``CONFIGURE_COMMAND``
      option must be used to override this behavior
      (:manual:`generator expressions <cmake-generator-expressions(7)>` are
      supported). For projects that require no configure step, specify this
      option with an empty string as the command to execute.

    ``CMAKE_COMMAND /.../cmake``
      Specify an alternative cmake executable for the configure step (use an
      absolute path). This is generally not recommended, since it is
      usually desirable to use the same CMake version throughout the whole
      build. This option is ignored if a custom configure command has been
      specified with ``CONFIGURE_COMMAND``.

    ``CMAKE_GENERATOR <gen>``
      Override the CMake generator used for the configure step. Without this
      option, the same generator as the main build will be used. This option is
      ignored if a custom configure command has been specified with the
      ``CONFIGURE_COMMAND`` option.

    ``CMAKE_GENERATOR_PLATFORM <platform>``
      Pass a generator-specific platform name to the CMake command (see
      :variable:`CMAKE_GENERATOR_PLATFORM`). It is an error to provide this
      option without the ``CMAKE_GENERATOR`` option.

    ``CMAKE_GENERATOR_TOOLSET <toolset>``
      Pass a generator-specific toolset name to the CMake command (see
      :variable:`CMAKE_GENERATOR_TOOLSET`). It is an error to provide this
      option without the ``CMAKE_GENERATOR`` option.

    ``CMAKE_ARGS <arg>...``
      The specified arguments are passed to the ``cmake`` command line. They
      can be any argument the ``cmake`` command understands, not just cache
      values defined by ``-D...`` arguments (see also
      :manual:`CMake Options <cmake(1)>`). In addition, arguments may use
      :manual:`generator expressions <cmake-generator-expressions(7)>`.

    ``CMAKE_CACHE_ARGS <arg>...``
      This is an alternate way of specifying cache variables where command line
      length issues may become a problem. The arguments are expected to be in
      the form ``-Dvar:STRING=value``, which are then transformed into
      CMake :command:`set` commands with the ``FORCE`` option used. These
      ``set()`` commands are written to a pre-load script which is then applied
      using the :manual:`cmake -C <cmake(1)>` command line option. Arguments
      may use :manual:`generator expressions <cmake-generator-expressions(7)>`.

    ``CMAKE_CACHE_DEFAULT_ARGS <arg>...``
      This is the same as the ``CMAKE_CACHE_ARGS`` option except the ``set()``
      commands do not include the ``FORCE`` keyword. This means the values act
      as initial defaults only and will not override any variables already set
      from a previous run. Use this option with care, as it can lead to
      different behavior depending on whether the build starts from a fresh
      build directory or re-uses previous build contents.

    ``SOURCE_SUBDIR <dir>``
      When no ``CONFIGURE_COMMAND`` option is specified, the configure step
      assumes the external project has a ``CMakeLists.txt`` file at the top of
      its source tree (i.e. in ``SOURCE_DIR``). The ``SOURCE_SUBDIR`` option
      can be used to point to an alternative directory within the source tree
      to use as the top of the CMake source tree instead. This must be a
      relative path and it will be interpreted as being relative to
      ``SOURCE_DIR``.

  **Build Step Options:**
    If the configure step assumed the external project uses CMake as its build
    system, the build step will also. Otherwise, the build step will assume a
    Makefile-based build and simply run ``make`` with no arguments as the
    default build step. This can be overridden with custom build commands if
    required.

    ``BUILD_COMMAND <cmd>...``
      Overrides the default build command
      (:manual:`generator expressions <cmake-generator-expressions(7)>` are
      supported). If this option is not given, the default build command will
      be chosen to integrate with the main build in the most appropriate way
      (e.g. using recursive ``make`` for Makefile generators or
      ``cmake --build`` if the project uses a CMake build). This option can be
      specified with an empty string as the command to make the build step do
      nothing.

    ``BUILD_IN_SOURCE <bool>``
      When this option is enabled, the build will be done directly within the
      external project's source tree. This should generally be avoided, the use
      of a separate build directory is usually preferred, but it can be useful
      when the external project assumes an in-source build. The ``BINARY_DIR``
      option should not be specified if building in-source.

    ``BUILD_ALWAYS <bool>``
      Enabling this option forces the build step to always be run. This can be
      the easiest way to robustly ensure that the external project's own build
      dependencies are evaluated rather than relying on the default
      success timestamp-based method. This option is not normally needed unless
      developers are expected to modify something the external project's build
      depends on in a way that is not detectable via the step target
      dependencies (e.g. ``SOURCE_DIR`` is used without a download method and
      developers might modify the sources in ``SOURCE_DIR``).

    ``BUILD_BYPRODUCTS <file>...``
      Specifies files that will be generated by the build command but which
      might or might not have their modification time updated by subsequent
      builds. These ultimately get passed through as ``BYPRODUCTS`` to the
      build step's own underlying call to :command:`add_custom_command`.

  **Install Step Options:**
    If the configure step assumed the external project uses CMake as its build
    system, the install step will also. Otherwise, the install step will assume
    a Makefile-based build and simply run ``make install`` as the default build
    step. This can be overridden with custom install commands if required.

    ``INSTALL_COMMAND <cmd>...``
      The external project's own install step is invoked as part of the main
      project's *build*. It is done after the external project's build step
      and may be before or after the external project's test step (see the
      ``TEST_BEFORE_INSTALL`` option below). The external project's install
      rules are not part of the main project's install rules, so if anything
      from the external project should be installed as part of the main build,
      these need to be specified in the main build as additional
      :command:`install` commands. The default install step builds the
      ``install`` target of the external project, but this can be overridden
      with a custom command using this option
      (:manual:`generator expressions <cmake-generator-expressions(7)>` are
      supported). Passing an empty string as the ``<cmd>`` makes the install
      step do nothing.

  **Test Step Options:**
    The test step is only defined if at least one of the following ``TEST_...``
    options are provided.

    ``TEST_COMMAND <cmd>...``
      Overrides the default test command
      (:manual:`generator expressions <cmake-generator-expressions(7)>` are
      supported). If this option is not given, the default behavior of the test
      step is to build the external project's own ``test`` target. This option
      can be specified with ``<cmd>`` as an empty string, which allows the test
      step to still be defined, but it will do nothing. Do not specify any of
      the other ``TEST_...`` options if providing an empty string as the test
      command, but prefer to omit all ``TEST_...`` options altogether if the
      test step target is not needed.

    ``TEST_BEFORE_INSTALL <bool>``
      When this option is enabled, the test step will be executed before the
      install step. The default behavior is for the test step to run after the
      install step.

    ``TEST_AFTER_INSTALL <bool>``
      This option is mainly useful as a way to indicate that the test step is
      desired but all default behavior is sufficient. Specifying this option
      with a boolean true value ensures the test step is defined and that it
      comes after the install step. If both ``TEST_BEFORE_INSTALL`` and
      ``TEST_AFTER_INSTALL`` are enabled, the latter is silently ignored.

    ``TEST_EXCLUDE_FROM_MAIN <bool>``
      If enabled, the main build's default ALL target will not depend on the
      test step. This can be a useful way of ensuring the test step is defined
      but only gets invoked when manually requested.

  **Output Logging Options:**
    Each of the following ``LOG_...`` options can be used to wrap the relevant
    step in a script to capture its output to files. The log files will be
    created in the ``STAMP_DIR`` directory with step-specific file names.

    ``LOG_DOWNLOAD <bool>``
      When enabled, the output of the download step is logged to files.

    ``LOG_UPDATE <bool>``
      When enabled, the output of the update step is logged to files.

    ``LOG_CONFIGURE <bool>``
      When enabled, the output of the configure step is logged to files.

    ``LOG_BUILD <bool>``
      When enabled, the output of the build step is logged to files.

    ``LOG_INSTALL <bool>``
      When enabled, the output of the install step is logged to files.

    ``LOG_TEST <bool>``
      When enabled, the output of the test step is logged to files.

  **Terminal Access Options:**
    Steps can be given direct access to the terminal in some cases. Giving a
    step access to the terminal may allow it to receive terminal input if
    required, such as for authentication details not provided by other options.
    With the :generator:`Ninja` generator, these options place the steps in the
    ``console`` :prop_gbl:`job pool <JOB_POOLS>`. Each step can be given access
    to the terminal individually via the following options:

    ``USES_TERMINAL_DOWNLOAD <bool>``
      Give the download step access to the terminal.

    ``USES_TERMINAL_UPDATE <bool>``
      Give the update step access to the terminal.

    ``USES_TERMINAL_CONFIGURE <bool>``
      Give the configure step access to the terminal.

    ``USES_TERMINAL_BUILD <bool>``
      Give the build step access to the terminal.

    ``USES_TERMINAL_INSTALL <bool>``
      Give the install step access to the terminal.

    ``USES_TERMINAL_TEST <bool>``
      Give the test step access to the terminal.

  **Target Options:**
    ``DEPENDS <targets>...``
      Specify other targets on which the external project depends. The other
      targets will be brought up to date before any of the external project's
      steps are executed. Because the external project uses additional custom
      targets internally for each step, the ``DEPENDS`` option is the most
      convenient way to ensure all of those steps depend on the other targets.
      Simply doing
      :command:`add_dependencies(\<name\> \<targets\>) <add_dependencies>` will
      not make any of the steps dependent on ``<targets>``.

    ``EXCLUDE_FROM_ALL <bool>``
      When enabled, this option excludes the external project from the default
      ALL target of the main build.

    ``STEP_TARGETS <step-target>...``
      Generate custom targets for the specified steps. This is required if the
      steps need to be triggered manually or if they need to be used as
      dependencies of other targets. If this option is not specified, the
      default value is taken from the ``EP_STEP_TARGETS`` directory property.
      See :command:`ExternalProject_Add_Step` below for further discussion of
      the effects of this option.

    ``INDEPENDENT_STEP_TARGETS <step-target>...``
      Generate custom targets for the specified steps and prevent these targets
      from having the usual dependencies applied to them. If this option is not
      specified, the default value is taken from the
      ``EP_INDEPENDENT_STEP_TARGETS`` directory property. This option is mostly
      useful for allowing individual steps to be driven independently, such as
      for a CDash setup where each step should be initiated and reported
      individually rather than as one whole build. See
      :command:`ExternalProject_Add_Step` below for further discussion of the
      effects of this option.

  **Miscellaneous Options:**
    ``LIST_SEPARATOR <sep>``
      For any of the various ``..._COMMAND`` options, replace ``;`` with
      ``<sep>`` in the specified command lines. This can be useful where list
      variables may be given in commands where they should end up as
      space-separated arguments (``<sep>`` would be a single space character
      string in this case).

    ``COMMAND <cmd>...``
      Any of the other ``..._COMMAND`` options can have additional commands
      appended to them by following them with as many ``COMMAND ...`` options
      as needed
      (:manual:`generator expressions <cmake-generator-expressions(7)>` are
      supported). For example::

        ExternalProject_Add(example
          ... # Download options, etc.
          BUILD_COMMAND ${CMAKE_COMMAND} -E echo "Starting $<CONFIG> build"
          COMMAND       ${CMAKE_COMMAND} --build <BINARY_DIR> --config $<CONFIG>
          COMMAND       ${CMAKE_COMMAND} -E echo "$<CONFIG> build complete"
        )

  It should also be noted that each build step is created via a call to
  :command:`ExternalProject_Add_Step`. See that command's documentation for the
  automatic substitutions that are supported for some options.

Obtaining Project Properties
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. command:: ExternalProject_Get_Property

  The ``ExternalProject_Get_Property()`` function retrieves external project
  target properties::

    ExternalProject_Get_Property(<name> <prop1> [<prop2>...])

  The function stores property values in variables of the same name. Property
  names correspond to the keyword argument names of ``ExternalProject_Add()``.
  For example, the source directory might be retrieved like so:

  .. code-block:: cmake

    ExternalProject_Get_property(myExtProj SOURCE_DIR)
    message("Source dir of myExtProj = ${SOURCE_DIR}")

Explicit Step Management
^^^^^^^^^^^^^^^^^^^^^^^^

The ``ExternalProject_Add()`` function on its own is often sufficient for
incorporating an external project into the main build. Certain scenarios
require additional work to implement desired behavior, such as adding in a
custom step or making steps available as manually triggerable targets. The
``ExternalProject_Add_Step()``, ``ExternalProject_Add_StepTargets()`` and
``ExternalProject_Add_StepDependencies`` functions provide the lower level
control needed to implement such step-level capabilities.
626

627
628
.. command:: ExternalProject_Add_Step

629
630
631
  The ``ExternalProject_Add_Step()`` function specifies an additional custom
  step for an external project defined by an earlier call to
  :command:`ExternalProject_Add`::
632

633
    ExternalProject_Add_Step(<name> <step> [<option>...])
634

635
636
637
638
639
  ``<name>`` is the same as the name passed to the original call to
  :command:`ExternalProject_Add`. The specified ``<step>`` must not be one of
  the pre-defined steps (``mkdir``, ``download``, ``update``, ``skip-update``,
  ``patch``, ``configure``, ``build``, ``install`` or ``test``). The supported
  options are:
640
641

  ``COMMAND <cmd>...``
642
643
644
645
646
    The command line to be executed by this custom step
    (:manual:`generator expressions <cmake-generator-expressions(7)>` are
    supported). This option can be repeated multiple times to specify multiple
    commands to be executed in order.

647
  ``COMMENT "<text>..."``
648
649
    Text to be printed when the custom step executes.

650
  ``DEPENDEES <step>...``
651
652
    Other steps (custom or pre-defined) on which this step depends.

653
  ``DEPENDERS <step>...``
654
655
    Other steps (custom or pre-defined) that depend on this new custom step.

656
  ``DEPENDS <file>...``
657
658
    Files on which this custom step depends.

659
  ``BYPRODUCTS <file>...``
660
661
662
663
664
665
666
667
668
669
670
671
672
    Files that will be generated by this custom step but which might or might
    not have their modification time updated by subsequent builds. This list of
    files will ultimately be passed through as the ``BYPRODUCTS`` option to the
    :command:`add_custom_command` used to implement the custom step internally.

  ``ALWAYS <bool>``
    When enabled, this option specifies that the custom step should always be
    run (i.e. that it is always considered out of date).

  ``EXCLUDE_FROM_MAIN <bool>``
    When enabled, this option specifies that the external project's main target
    does not depend on the custom step.

673
  ``WORKING_DIRECTORY <dir>``
674
675
676
677
    Specifies the working directory to set before running the custom step's
    command. If this option is not specified, the directory will be the value
    of the :variable:`CMAKE_CURRENT_BINARY_DIR` at the point where
    ``ExternalProject_Add_Step()`` was called.
678

679
680
681
  ``LOG <bool>``
    If set, this causes the output from the custom step to be captured to files
    in the external project's ``STAMP_DIR``.
682

683
684
685
  ``USES_TERMINAL <bool>``
    If enabled, this gives the custom step direct access to the terminal if
    possible.
686

687
688
689
690
691
  The command line, comment, working directory and byproducts of every
  standard and custom step are processed to replace the tokens
  ``<SOURCE_DIR>``, ``<SOURCE_SUBDIR>``, ``<BINARY_DIR>``, ``<INSTALL_DIR>``
  and ``<TMP_DIR>`` with their corresponding property values defined in the
  original call to :command:`ExternalProject_Add`.
692

693
.. command:: ExternalProject_Add_StepTargets
694

695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
  The ``ExternalProject_Add_StepTargets()`` function generates targets for the
  steps listed. The name of each created target will be of the form
  ``<name>-<step>``::

    ExternalProject_Add_StepTargets(<name> [NO_DEPENDS] <step1> [<step2>...])

  Creating a target for a step allows it to be used as a dependency of another
  target or to be triggered manually. Having targets for specific steps also
  allows them to be driven independently of each other by specifying targets on
  build command lines. For example, you may be submitting to a sub-project
  based dashboard where you want to drive the configure portion of the build,
  then submit to the dashboard, followed by the build portion, followed
  by tests. If you invoke a custom target that depends on a step halfway
  through the step dependency chain, then all the previous steps will also run
  to ensure everything is up to date.

  If the ``NO_DEPENDS`` option is specified, the step target will not depend on
  the dependencies of the external project (i.e. on any dependencies of the
  ``<name>`` custom target created by :command:`ExternalProject_Add`). This is
  usually safe for the ``download``, ``update`` and ``patch`` steps, since they
  do not typically require that the dependencies are updated and built. Using
  ``NO_DEPENDS`` for any of the other pre-defined steps, however, may break
  parallel builds. Only use ``NO_DEPENDS`` where it is certain that the named
  steps genuinely do not have dependencies. For custom steps, consider whether
  or not the custom commands require the dependencies to be configured, built
  and installed.

  Internally, :command:`ExternalProject_Add` calls
  :command:`ExternalProject_Add_Step` to create each step. If any
  ``STEP_TARGETS`` or ``INDEPENDENT_STEP_TARGETS`` were specified, then
  ``ExternalProject_Add_StepTargets()`` will also be called after
  :command:`ExternalProject_Add_Step`. ``INDEPENDENT_STEP_TARGETS`` have the
  ``NO_DEPENDS`` option set, whereas ``STEP_TARGETS`` do not. Other than that,
  the two options result in ``ExternalProject_Add_StepTargets()`` being called
  in the same way. Even if a step is not mentioned in either of those two
  options, ``ExternalProject_Add_StepTargets()`` can still be called later to
  manually define a target for the step.

  The ``STEP_TARGETS`` and ``INDEPENDENT_STEP_TARGETS`` options for
  :command:`ExternalProject_Add` are generally the easiest way to ensure
  targets are created for specific steps of interest. For custom steps,
  ``ExternalProject_Add_StepTargets()`` must be called explicitly if a target
  should also be created for that custom step. An alternative to these two
  options is to populate the ``EP_STEP_TARGETS`` and
  ``EP_INDEPENDENT_STEP_TARGETS`` directory properties. These act as defaults
  for the step target options and can save having to repeatedly specify the
  same set of step targets when multiple external projects are being defined.
742

743
.. command:: ExternalProject_Add_StepDependencies
744

745
746
747
748
  The ``ExternalProject_Add_StepDependencies()`` function can be used to add
  dependencies to a step. The dependencies added must be targets CMake already
  knows about (these can be ordinary executable or library targets, custom
  targets or even step targets of another external project)::
749

750
    ExternalProject_Add_StepDependencies(<name> <step> <target1> [<target2>...])
751

752
753
754
755
  This function takes care to set both target and file level dependencies and
  will ensure that parallel builds will not break. It should be used instead of
  :command:`add_dependencies` whenever adding a dependency for some of the step
  targets generated by the ``ExternalProject`` module.
756

757
758
Examples
^^^^^^^^
759

760
761
The following example shows how to download and build a hypothetical project
called *FooBar* from github:
762

763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
.. code-block:: cmake

  include(ExternalProject)
  ExternalProject_Add(foobar
    GIT_REPOSITORY    git@github.com:FooCo/FooBar.git
    GIT_TAG           origin/release/1.2.3
  )

For the sake of the example, also define a second hypothetical external project
called *SecretSauce*, which is downloaded from a web server. Two URLs are given
to take advantage of a faster internal network if available, with a fallback to
a slower external server. The project is a typical ``Makefile`` project with no
configure step, so some of the default commands are overridden. The build is
only required to build the *sauce* target:

.. code-block:: cmake

  find_program(MAKE_EXE NAMES gmake nmake make)
  ExternalProject_Add(secretsauce
    URL               http://intranet.somecompany.com/artifacts/sauce-2.7.tgz
                      https://www.somecompany.com/downloads/sauce-2.7.zip
    URL_HASH          MD5=d41d8cd98f00b204e9800998ecf8427e
    CONFIGURE_COMMAND ""
    BUILD_COMMAND     ${MAKE_EXE} sauce
  )

Suppose the build step of ``secretsauce`` requires that ``foobar`` must already
be built. This could be enforced like so:

.. code-block:: cmake

  ExternalProject_Add_StepDependencies(secretsauce build foobar)

Another alternative would be to create a custom target for ``foobar``'s build
step and make ``secretsauce`` depend on that rather than the whole ``foobar``
project. This would mean ``foobar`` only needs to be built, it doesn't need to
run its install or test steps before ``secretsauce`` can be built. The
dependency can also be defined along with the ``secretsauce`` project:

.. code-block:: cmake

  ExternalProject_Add_StepTargets(foobar build)
  ExternalProject_Add(secretsauce
    URL               http://intranet.somecompany.com/artifacts/sauce-2.7.tgz
                      https://www.somecompany.com/downloads/sauce-2.7.zip
    URL_HASH          MD5=d41d8cd98f00b204e9800998ecf8427e
    CONFIGURE_COMMAND ""
    BUILD_COMMAND     ${MAKE_EXE} sauce
    DEPENDS           foobar-build
  )

Instead of calling :command:`ExternalProject_Add_StepTargets`, the target could
be defined along with the ``foobar`` project itself:

.. code-block:: cmake

  ExternalProject_Add(foobar
    GIT_REPOSITORY git@github.com:FooCo/FooBar.git
    GIT_TAG        origin/release/1.2.3
    STEP_TARGETS   build
  )

If many external projects should have the same set of step targets, setting a
directory property may be more convenient. The ``build`` step target could be
created automatically by setting the ``EP_STEP_TARGETS`` directory property
before creating the external projects with :command:`ExternalProject_Add`:

.. code-block:: cmake

  set_property(DIRECTORY PROPERTY EP_STEP_TARGETS build)

Lastly, suppose that ``secretsauce`` provides a script called ``makedoc`` which
can be used to generate its own documentation. Further suppose that the script
expects the output directory to be provided as the only parameter and that it
should be run from the ``secretsauce`` source directory. A custom step and a
custom target to trigger the script can be defined like so:

.. code-block:: cmake

  ExternalProject_Add_Step(secretsauce docs
    COMMAND           <SOURCE_DIR>/makedoc <BINARY_DIR>
    WORKING_DIRECTORY <SOURCE_DIR>
    COMMENT           "Building secretsauce docs"
    ALWAYS            TRUE
    EXCLUDE_FROM_MAIN TRUE
  )
  ExternalProject_Add_StepTargets(secretsauce docs)
850

851
The custom step could then be triggered from the main build like so::
852

853
  cmake --build . --target secretsauce-docs
854

855
#]=======================================================================]
856

857
858
859
cmake_policy(PUSH)
cmake_policy(SET CMP0054 NEW) # if() quoted variables not dereferenced

860
# Pre-compute a regex to match documented keywords for each command.
861
math(EXPR _ep_documentation_line_count "${CMAKE_CURRENT_LIST_LINE} - 4")
862
863
file(STRINGS "${CMAKE_CURRENT_LIST_FILE}" lines
     LIMIT_COUNT ${_ep_documentation_line_count}
864
     REGEX "^\\.\\. command:: [A-Za-z0-9_]+|^ +``[A-Z0-9_]+ [^`]*``$")
865
foreach(line IN LISTS lines)
866
  if("${line}" MATCHES "^\\.\\. command:: ([A-Za-z0-9_]+)")
867
    if(_ep_func)
Daniel Pfeifer's avatar
Daniel Pfeifer committed
868
      string(APPEND _ep_keywords_${_ep_func} ")$")
869
    endif()
870
    set(_ep_func "${CMAKE_MATCH_1}")
871
872
873
    #message("function [${_ep_func}]")
    set(_ep_keywords_${_ep_func} "^(")
    set(_ep_keyword_sep)
874
  elseif("${line}" MATCHES "^ +``([A-Z0-9_]+) [^`]*``$")
875
    set(_ep_key "${CMAKE_MATCH_1}")
876
877
878
879
880
881
882
883
    # COMMAND should never be included as a keyword,
    # for ExternalProject_Add(), as it is treated as a
    # special case by argument parsing as an extension
    # of a previous ..._COMMAND
    if("x${_ep_key}x" STREQUAL "xCOMMANDx" AND
       "x${_ep_func}x" STREQUAL "xExternalProject_Addx")
      continue()
    endif()
884
    #message("  keyword [${_ep_key}]")
Daniel Pfeifer's avatar
Daniel Pfeifer committed
885
886
    string(APPEND _ep_keywords_${_ep_func}
      "${_ep_keyword_sep}${_ep_key}")
887
888
889
890
    set(_ep_keyword_sep "|")
  endif()
endforeach()
if(_ep_func)
Daniel Pfeifer's avatar
Daniel Pfeifer committed
891
  string(APPEND _ep_keywords_${_ep_func} ")$")
892
893
endif()

894
# Save regex matching supported hash algorithm names.
895
set(_ep_hash_algos "MD5|SHA1|SHA224|SHA256|SHA384|SHA512|SHA3_224|SHA3_256|SHA3_384|SHA3_512")
896
set(_ep_hash_regex "^(${_ep_hash_algos})=([0-9A-Fa-f]+)$")
897

898
899
900
set(_ExternalProject_SELF "${CMAKE_CURRENT_LIST_FILE}")
get_filename_component(_ExternalProject_SELF_DIR "${_ExternalProject_SELF}" PATH)

901
902
903
904
905
906
function(_ep_parse_arguments f name ns args)
  # Transfer the arguments to this function into target properties for the
  # new custom target we just added so that we can set up all the build steps
  # correctly based on target properties.
  #
  # We loop through ARGN and consider the namespace starting with an
907
908
  # upper-case letter followed by at least two more upper-case letters,
  # numbers or underscores to be keywords.
909
  set(key)
910

911
  foreach(arg IN LISTS args)
912
913
    set(is_value 1)

914
    if(arg MATCHES "^[A-Z][A-Z0-9_][A-Z0-9_]+$" AND
915
        NOT (("x${arg}x" STREQUAL "x${key}x") AND ("x${key}x" STREQUAL "xCOMMANDx")) AND
916
        NOT arg MATCHES "^(TRUE|FALSE)$")
917
918
919
920
921
922
923
924
925
926
      if(_ep_keywords_${f} AND arg MATCHES "${_ep_keywords_${f}}")
        set(is_value 0)
      endif()
    endif()

    if(is_value)
      if(key)
        # Value
        if(NOT arg STREQUAL "")
          set_property(TARGET ${name} APPEND PROPERTY ${ns}${key} "${arg}")
927
        else()
928
929
930
931
932
933
934
          get_property(have_key TARGET ${name} PROPERTY ${ns}${key} SET)
          if(have_key)
            get_property(value TARGET ${name} PROPERTY ${ns}${key})
            set_property(TARGET ${name} PROPERTY ${ns}${key} "${value};${arg}")
          else()
            set_property(TARGET ${name} PROPERTY ${ns}${key} "${arg}")
          endif()
935
        endif()
936
937
938
      else()
        # Missing Keyword
        message(AUTHOR_WARNING "value '${arg}' with no previous keyword in ${f}")
939
940
      endif()
    else()
941
      set(key "${arg}")
942
943
    endif()
  endforeach()
944
endfunction()
945

946

947
948
949
define_property(DIRECTORY PROPERTY "EP_BASE" INHERITED
  BRIEF_DOCS "Base directory for External Project storage."
  FULL_DOCS
950
  "See documentation of the ExternalProject_Add() function in the "
951
952
953
954
955
956
  "ExternalProject module."
  )

define_property(DIRECTORY PROPERTY "EP_PREFIX" INHERITED
  BRIEF_DOCS "Top prefix for External Project storage."
  FULL_DOCS
957
  "See documentation of the ExternalProject_Add() function in the "
958
959
960
  "ExternalProject module."
  )

961
962
963
964
define_property(DIRECTORY PROPERTY "EP_STEP_TARGETS" INHERITED
  BRIEF_DOCS
  "List of ExternalProject steps that automatically get corresponding targets"
  FULL_DOCS
965
  "These targets will be dependent on the main target dependencies. "
966
967
968
969
  "See documentation of the ExternalProject_Add_StepTargets() function in the "
  "ExternalProject module."
  )

970
971
972
973
define_property(DIRECTORY PROPERTY "EP_INDEPENDENT_STEP_TARGETS" INHERITED
  BRIEF_DOCS
  "List of ExternalProject steps that automatically get corresponding targets"
  FULL_DOCS
974
  "These targets will not be dependent on the main target dependencies. "
975
976
977
  "See documentation of the ExternalProject_Add_StepTargets() function in the "
  "ExternalProject module."
  )
978

979
980
981
982
983
984
985
define_property(DIRECTORY PROPERTY "EP_UPDATE_DISCONNECTED" INHERITED
  BRIEF_DOCS "Never update automatically from the remote repo."
  FULL_DOCS
  "See documentation of the ExternalProject_Add() function in the "
  "ExternalProject module."
  )

986
function(_ep_write_gitclone_script script_filename source_dir git_EXECUTABLE git_repository git_tag git_remote_name git_submodules git_shallow git_progress git_config src_name work_dir gitclone_infofile gitclone_stampfile tls_verify)
987
988
989
990
991
  if(NOT GIT_VERSION_STRING VERSION_LESS 1.7.10)
    set(git_clone_shallow_options "--depth 1 --no-single-branch")
  else()
    set(git_clone_shallow_options "--depth 1")
  endif()
992
993
994
995
996
997
998
999
1000
  if(NOT GIT_VERSION_STRING VERSION_LESS 1.8.5)
    # Use `git checkout <tree-ish> --` to avoid ambiguity with a local path.
    set(git_checkout_explicit-- "--")
  else()
    # Use `git checkout <branch>` even though this risks ambiguity with a
    # local path.  Unfortunately we cannot use `git checkout <tree-ish> --`
    # because that will not search for remote branch names, a common use case.
    set(git_checkout_explicit-- "")
  endif()
1001
1002
1003
1004
1005
  file(WRITE ${script_filename}
"if(\"${git_tag}\" STREQUAL \"\")
  message(FATAL_ERROR \"Tag for git checkout should not be empty.\")
endif()

1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
set(run 0)

if(\"${gitclone_infofile}\" IS_NEWER_THAN \"${gitclone_stampfile}\")
  set(run 1)
endif()

if(NOT run)
  message(STATUS \"Avoiding repeated git clone, stamp file is up to date: '${gitclone_stampfile}'\")
  return()
endif()

1017
1018
1019
1020
1021
1022
1023
1024
execute_process(
  COMMAND \${CMAKE_COMMAND} -E remove_directory \"${source_dir}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to remove directory: '${source_dir}'\")
endif()

1025
set(git_options)
1026
1027
1028
1029

# disable cert checking if explicitly told not to do it
set(tls_verify \"${tls_verify}\")
if(NOT \"x${tls_verify}\" STREQUAL \"x\" AND NOT tls_verify)
1030
1031
1032
1033
  list(APPEND git_options
    -c http.sslVerify=false)
endif()

1034
1035
1036
1037
1038
1039
1040
set(git_clone_options)

set(git_shallow \"${git_shallow}\")
if(git_shallow)
  list(APPEND git_clone_options ${git_clone_shallow_options})
endif()

1041
1042
1043
1044
1045
set(git_progress \"${git_progress}\")
if(git_progress)
  list(APPEND git_clone_options --progress)
endif()

1046
1047
1048
1049
1050
set(git_config \"${git_config}\")
foreach(config IN LISTS git_config)
  list(APPEND git_clone_options --config \${config})
endforeach()

1051
1052
1053
1054
1055
# try the clone 3 times incase there is an odd git clone issue
set(error_code 1)
set(number_of_tries 0)
while(error_code AND number_of_tries LESS 3)
  execute_process(
1056
    COMMAND \"${git_EXECUTABLE}\" \${git_options} clone \${git_clone_options} --origin \"${git_remote_name}\" \"${git_repository}\" \"${src_name}\"
1057
1058
1059
1060
1061
1062
1063
1064
1065
    WORKING_DIRECTORY \"${work_dir}\"
    RESULT_VARIABLE error_code
    )
  math(EXPR number_of_tries \"\${number_of_tries} + 1\")
endwhile()
if(number_of_tries GREATER 1)
  message(STATUS \"Had to git clone more than once:
          \${number_of_tries} times.\")
endif()
1066
1067
1068
1069
1070
if(error_code)
  message(FATAL_ERROR \"Failed to clone repository: '${git_repository}'\")
endif()

execute_process(
1071
  COMMAND \"${git_EXECUTABLE}\" \${git_options} checkout ${git_tag} ${git_checkout_explicit--}
1072
1073
1074
1075
1076
1077
1078
1079
  WORKING_DIRECTORY \"${work_dir}/${src_name}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to checkout tag: '${git_tag}'\")
endif()

execute_process(
1080
  COMMAND \"${git_EXECUTABLE}\" \${git_options} submodule init ${git_submodules}
1081
1082
1083
1084
1085
1086
1087
1088
  WORKING_DIRECTORY \"${work_dir}/${src_name}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to init submodules in: '${work_dir}/${src_name}'\")
endif()

execute_process(
1089
  COMMAND \"${git_EXECUTABLE}\" \${git_options} submodule update --recursive --init ${git_submodules}
1090
1091
1092
1093
1094
1095
1096
  WORKING_DIRECTORY \"${work_dir}/${src_name}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to update submodules in: '${work_dir}/${src_name}'\")
endif()

1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
# Complete success, update the script-last-run stamp file:
#
execute_process(
  COMMAND \${CMAKE_COMMAND} -E copy
    \"${gitclone_infofile}\"
    \"${gitclone_stampfile}\"
  WORKING_DIRECTORY \"${work_dir}/${src_name}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to copy script-last-run stamp file: '${gitclone_stampfile}'\")
endif()

1110
1111
1112
"
)

1113
endfunction()
1114

1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
function(_ep_write_hgclone_script script_filename source_dir hg_EXECUTABLE hg_repository hg_tag src_name work_dir hgclone_infofile hgclone_stampfile)
  file(WRITE ${script_filename}
"if(\"${hg_tag}\" STREQUAL \"\")
  message(FATAL_ERROR \"Tag for hg checkout should not be empty.\")
endif()

set(run 0)

if(\"${hgclone_infofile}\" IS_NEWER_THAN \"${hgclone_stampfile}\")
  set(run 1)
endif()

if(NOT run)
  message(STATUS \"Avoiding repeated hg clone, stamp file is up to date: '${hgclone_stampfile}'\")
  return()
endif()

execute_process(
  COMMAND \${CMAKE_COMMAND} -E remove_directory \"${source_dir}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to remove directory: '${source_dir}'\")
endif()

execute_process(
1141
  COMMAND \"${hg_EXECUTABLE}\" clone -U \"${hg_repository}\" \"${src_name}\"
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
  WORKING_DIRECTORY \"${work_dir}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to clone repository: '${hg_repository}'\")
endif()

execute_process(
  COMMAND \"${hg_EXECUTABLE}\" update ${hg_tag}
  WORKING_DIRECTORY \"${work_dir}/${src_name}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to checkout tag: '${hg_tag}'\")
endif()

# Complete success, update the script-last-run stamp file:
#
execute_process(
  COMMAND \${CMAKE_COMMAND} -E copy
    \"${hgclone_infofile}\"
    \"${hgclone_stampfile}\"
  WORKING_DIRECTORY \"${work_dir}/${src_name}\"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR \"Failed to copy script-last-run stamp file: '${hgclone_stampfile}'\")
endif()

"
)

endfunction()

1176

1177
function(_ep_write_gitupdate_script script_filename git_EXECUTABLE git_tag git_remote_name git_submodules git_repository work_dir)
1178
1179
1180
1181
1182
  if(NOT GIT_VERSION_STRING VERSION_LESS 1.7.6)
    set(git_stash_save_options --all --quiet)
  else()
    set(git_stash_save_options --quiet)
  endif()
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
  file(WRITE ${script_filename}
"if(\"${git_tag}\" STREQUAL \"\")
  message(FATAL_ERROR \"Tag for git checkout should not be empty.\")
endif()

execute_process(
  COMMAND \"${git_EXECUTABLE}\" rev-list --max-count=1 HEAD
  WORKING_DIRECTORY \"${work_dir}\"
  RESULT_VARIABLE error_code
  OUTPUT_VARIABLE head_sha
1193
  OUTPUT_STRIP_TRAILING_WHITESPACE
1194
1195
1196
1197
1198
  )
if(error_code)
  message(FATAL_ERROR \"Failed to get the hash for HEAD\")
endif()

1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
execute_process(
  COMMAND \"${git_EXECUTABLE}\" show-ref ${git_tag}
  WORKING_DIRECTORY \"${work_dir}\"
  OUTPUT_VARIABLE show_ref_output
  )
# If a remote ref is asked for, which can possibly move around,
# we must always do a fetch and checkout.
if(\"\${show_ref_output}\" MATCHES \"remotes\")
  set(is_remote_ref 1)
else()
  set(is_remote_ref 0)
endif()

1212
1213
1214
1215
1216
1217
1218
# Tag is in the form <remote>/<tag> (i.e. origin/master) we must strip
# the remote from the tag.
if(\"\${show_ref_output}\" MATCHES \"refs/remotes/${git_tag}\")
  string(REGEX MATCH \"^([^/]+)/(.+)$\" _unused \"${git_tag}\")
  set(git_remote \"\${CMAKE_MATCH_1}\")
  set(git_tag \"\${CMAKE_MATCH_2}\")
else()
1219
  set(git_remote \"${git_remote_name}\")
1220
1221
1222
  set(git_tag \"${git_tag}\")
endif()

1223
1224
1225
1226
1227
1228
1229
# This will fail if the tag does not exist (it probably has not been fetched
# yet).
execute_process(
  COMMAND \"${git_EXECUTABLE}\" rev-list --max-count=1 ${git_tag}
  WORKING_DIRECTORY \"${work_dir}\"
  RESULT_VARIABLE error_code
  OUTPUT_VARIABLE tag_sha
1230
  OUTPUT_STRIP_TRAILING_WHITESPACE
1231
1232
1233
  )

# Is the hash checkout out that we want?
1234
if(error_code OR is_remote_ref OR NOT (\"\${tag_sha}\" STREQUAL \"\${head_sha}\"))
1235
1236
1237
1238
1239
1240
1241
1242
1243
  execute_process(
    COMMAND \"${git_EXECUTABLE}\" fetch
    WORKING_DIRECTORY \"${work_dir}\"
    RESULT_VARIABLE error_code
    )
  if(error_code)
    message(FATAL_ERROR \"Failed to fetch repository '${git_repository}'\")
  endif()

1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
  if(is_remote_ref)
    # Check if stash is needed
    execute_process(
      COMMAND \"${git_EXECUTABLE}\" status --porcelain
      WORKING_DIRECTORY \"${work_dir}\"
      RESULT_VARIABLE error_code
      OUTPUT_VARIABLE repo_status
      )
    if(error_code)
      message(FATAL_ERROR \"Failed to get the status\")
    endif()
    string(LENGTH \"\${repo_status}\" need_stash)

    # If not in clean state, stash changes in order to be able to be able to
    # perform git pull --rebase
    if(need_stash)
      execute_process(
1261
        COMMAND \"${git_EXECUTABLE}\" stash save ${git_stash_save_options}
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
        WORKING_DIRECTORY \"${work_dir}\"
        RESULT_VARIABLE error_code
        )
      if(error_code)
        message(FATAL_ERROR \"Failed to stash changes\")
      endif()
    endif()

    # Pull changes from the remote branch
    execute_process(
      COMMAND \"${git_EXECUTABLE}\" rebase \${git_remote}/\${git_tag}
      WORKING_DIRECTORY \"${work_dir}\"
      RESULT_VARIABLE error_code
      )
    if(error_code)
      # Rebase failed: Restore previous state.
      execute_process(
        COMMAND \"${git_EXECUTABLE}\" rebase --abort
        WORKING_DIRECTORY \"${work_dir}\"
      )
      if(need_stash)
        execute_process(
          COMMAND \"${git_EXECUTABLE}\" stash pop --index --quiet
          WORKING_DIRECTORY \"${work_dir}\"
          )
      endif()
      message(FATAL_ERROR \"\\nFailed to rebase in: '${work_dir}/${src_name}'.\\nYou will have to resolve the conflicts manually\")
    endif()

    if(need_stash)
      execute_process(
        COMMAND \"${git_EXECUTABLE}\" stash pop --index --quiet
        WORKING_DIRECTORY \"${work_dir}\"
        RESULT_VARIABLE error_code
        )
      if(error_code)
        # Stash pop --index failed: Try again dropping the index
        execute_process(
          COMMAND \"${git_EXECUTABLE}\" reset --hard --quiet
          WORKING_DIRECTORY \"${work_dir}\"
          RESULT_VARIABLE error_code
          )
        execute_process(
          COMMAND \"${git_EXECUTABLE}\" stash pop --quiet
          WORKING_DIRECTORY \"${work_dir}\"
          RESULT_VARIABLE error_code
          )
        if(error_code)
          # Stash pop failed: Restore previous state.
          execute_process(
            COMMAND \"${git_EXECUTABLE}\" reset --hard --quiet \${head_sha}
            WORKING_DIRECTORY \"${work_dir}\"
          )
          execute_process(
            COMMAND \"${git_EXECUTABLE}\" stash pop --index --quiet
            WORKING_DIRECTORY \"${work_dir}\"
          )
          message(FATAL_ERROR \"\\nFailed to unstash changes in: '${work_dir}/${src_name}'.\\nYou will have to resolve the conflicts manually\")
        endif()
      endif()
    endif()
  else()
    execute_process(
      COMMAND \"${git_EXECUTABLE}\" checkout ${git_tag}
      WORKING_DIRECTORY \"${work_dir}\"
      RESULT_VARIABLE error_code
      )
    if(error_code)
      message(FATAL_ERROR \"Failed to checkout tag: '${git_tag}'\")
    endif()
1332
1333
1334
  endif()

  execute_process(
1335
    COMMAND \"${git_EXECUTABLE}\" submodule update --recursive --init ${git_submodules}
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
    WORKING_DIRECTORY \"${work_dir}/${src_name}\"
    RESULT_VARIABLE error_code
    )
  if(error_code)
    message(FATAL_ERROR \"Failed to update submodules in: '${work_dir}/${src_name}'\")
  endif()
endif()

"
)

endfunction(_ep_write_gitupdate_script)

1349
function(_ep_write_downloadfile_script script_filename REMOTE LOCAL timeout no_progress hash tls_verify tls_cainfo userpwd http_headers)
1350
  if(timeout)
1351
1352
    set(TIMEOUT_ARGS TIMEOUT ${timeout})
    set(TIMEOUT_MSG "${timeout} seconds")
1353
  else()
1354
1355
    set(TIMEOUT_ARGS "# no TIMEOUT")
    set(TIMEOUT_MSG "none")
1356
1357
  endif()

1358
  if(no_progress)
1359
    set(SHOW_PROGRESS "")
1360
  else()
1361
    set(SHOW_PROGRESS "SHOW_PROGRESS")
1362
1363
  endif()

1364
  if("${hash}" MATCHES "${_ep_hash_regex}")
1365
    set(ALGO "${CMAKE_MATCH_1}")
1366
    string(TOLOWER "${CMAKE_MATCH_2}" EXPECT_VALUE)
1367
  else()
1368
1369
    set(ALGO "")
    set(EXPECT_VALUE "")
1370
1371
  endif()

1372
1373
  set(TLS_VERIFY_CODE "")
  set(TLS_CAINFO_CODE "")
1374

1375
  # check for curl globals in the project
Brad King's avatar
Brad King committed
1376
  if(DEFINED CMAKE_TLS_VERIFY)
1377
    set(TLS_VERIFY_CODE "set(CMAKE_TLS_VERIFY ${CMAKE_TLS_VERIFY})")
1378
  endif()
Brad King's avatar
Brad King committed
1379
  if(DEFINED CMAKE_TLS_CAINFO)
1380
    set(TLS_CAINFO_CODE "set(CMAKE_TLS_CAINFO \"${CMAKE_TLS_CAINFO}\")")
1381
1382
1383
1384
1385
  endif()

  # now check for curl locals so that the local values
  # will override the globals

Brad King's avatar
Brad King committed
1386
1387
1388
  # check for tls_verify argument
  string(LENGTH "${tls_verify}" tls_verify_len)
  if(tls_verify_len GREATER 0)
1389
    set(TLS_VERIFY_CODE "set(CMAKE_TLS_VERIFY ${tls_verify})")
1390
  endif()
Brad King's avatar
Brad King committed
1391
1392
1393
  # check for tls_cainfo argument
  string(LENGTH "${tls_cainfo}" tls_cainfo_len)
  if(tls_cainfo_len GREATER 0)
1394
    set(TLS_CAINFO_CODE "set(CMAKE_TLS_CAINFO \"${tls_cainfo}\")")
1395
  endif()
1396

1397
1398
1399
1400
1401
1402
  if(userpwd STREQUAL ":")
    set(USERPWD_ARGS)
  else()
    set(USERPWD_ARGS USERPWD "${userpwd}")
  endif()

1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
  set(HTTP_HEADERS_ARGS "")
  if(NOT http_headers STREQUAL "")
    foreach(header ${http_headers})
      set(
          HTTP_HEADERS_ARGS
          "HTTPHEADER \"${header}\"\n        ${HTTP_HEADERS_ARGS}"
      )
    endforeach()
  endif()

1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
  # Used variables:
  # * TLS_VERIFY_CODE
  # * TLS_CAINFO_CODE
  # * ALGO
  # * EXPECT_VALUE
  # * REMOTE
  # * LOCAL
  # * SHOW_PROGRESS
  # * TIMEOUT_ARGS
  # * TIMEOUT_MSG
1423
  # * USERPWD_ARGS
1424
  # * HTTP_HEADERS_ARGS
1425
1426
1427
1428
1429
  configure_file(
      "${_ExternalProject_SELF_DIR}/ExternalProject-download.cmake.in"
      "${script_filename}"
      @ONLY
  )
1430
endfunction()
1431

1432
function(_ep_write_verifyfile_script script_filename LOCAL hash)
1433
  if("${hash}" MATCHES "${_ep_hash_regex}")
1434
1435
    set(ALGO "${CMAKE_MATCH_1}")
    string(TOLOWER "${CMAKE_MATCH_2}" EXPECT_VALUE)
1436
  else()
1437
1438
    set(ALGO "")
    set(EXPECT_VALUE "")
1439
  endif()
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449

  # Used variables:
  # * ALGO
  # * EXPECT_VALUE
  # * LOCAL
  configure_file(
      "${_ExternalProject_SELF_DIR}/ExternalProject-verify.cmake.in"
      "${script_filename}"
      @ONLY
  )
1450
endfunction()
1451
1452


1453
function(_ep_write_extractfile_script script_filename name filename directory)
1454
1455
  set(args "")

1456
  if(filename MATCHES "(\\.|=)(7z|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip)$")
1457
1458
1459
    set(args xfz)
  endif()

1460
  if(filename MATCHES "(\\.|=)tar$")
1461
    set(args xf)
1462
1463
1464
  endif()

  if(args STREQUAL "")
1465
    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")
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
    return()
  endif()

  file(WRITE ${script_filename}
"# Make file names absolute:
#
get_filename_component(filename \"${filename}\" ABSOLUTE)
get_filename_component(directory \"${directory}\" ABSOLUTE)

message(STATUS \"extracting...
     src='\${filename}'
     dst='\${directory}'\")

1479
1480
1481
1482
if(NOT EXISTS \"\${filename}\")
  message(FATAL_ERROR \"error: file to extract does not exist: '\${filename}'\")
endif()

1483
1484
# Prepare a space for extracting:
#
1485
set(i 1234)
1486
while(EXISTS \"\${directory}/../ex-${name}\${i}\")
1487
1488
  math(EXPR i \"\${i} + 1\")
endwhile()
1489
set(ut_dir \"\${directory}/../ex-${name}\${i}\")
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
file(MAKE_DIRECTORY \"\${ut_dir}\")

# Extract it:
#
message(STATUS \"extracting... [tar ${args}]\")
execute_process(COMMAND \${CMAKE_COMMAND} -E tar ${args} \${filename}
  WORKING_DIRECTORY \${ut_dir}
  RESULT_VARIABLE rv)

if(NOT rv EQUAL 0)
  message(STATUS \"extracting... [error clean up]\")
  file(REMOVE_RECURSE \"\${ut_dir}\")
  message(FATAL_ERROR \"error: extract of '\${filename}' failed\")
endif()

# Analyze what came out of the tar file:
#
message(STATUS \"extracting... [analysis]\")
file(GLOB contents \"\${ut_dir}/*\")
1509
list(REMOVE_ITEM contents \"\${ut_dir}/.DS_Store\")
1510
1511
1512
1513
1514
list(LENGTH contents n)
if(NOT n EQUAL 1 OR NOT IS_DIRECTORY \"\${contents}\")
  set(contents \"\${ut_dir}\")
endif()

1515
# Move \"the one\" directory to the final directory:
1516
#
1517
1518
1519
1520
message(STATUS \"extracting... [rename]\")
file(REMOVE_RECURSE \${directory})
get_filename_component(contents \${contents} ABSOLUTE)
file(RENAME \${contents} \${directory})
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530

# Clean up:
#
message(STATUS \"extracting... [clean up]\")
file(REMOVE_RECURSE \"\${ut_dir}\")

message(STATUS \"extracting... done\")
"
)

1531
endfunction()
1532
1533


1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
function(_ep_set_directories name)
  get_property(prefix TARGET ${name} PROPERTY _EP_PREFIX)
  if(NOT prefix)
    get_property(prefix DIRECTORY PROPERTY EP_PREFIX)
    if(NOT prefix)
      get_property(base DIRECTORY PROPERTY EP_BASE)
      if(NOT base)
        set(prefix "${name}-prefix")
      endif()
    endif()
  endif()
  if(prefix)
    set(tmp_default "${prefix}/tmp")
    set(download_default "${prefix}/src")
    set(source_default "${prefix}/src/${name}")
    set(binary_default "${prefix}/src/${name}-build")
    set(stamp_default "${prefix}/src/${name}-stamp")
    set(install_default "${prefix}")
1552
  else()
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
    set(tmp_default "${base}/tmp/${name}")
    set(download_default "${base}/Download/${name}")
    set(source_default "${base}/Source/${name}")
    set(binary_default "${base}/Build/${name}")
    set(stamp_default "${base}/Stamp/${name}")
    set(install_default "${base}/Install/${name}")
  endif()
  get_property(build_in_source TARGET ${name} PROPERTY _EP_BUILD_IN_SOURCE)
  if(build_in_source)
    get_property(have_binary_dir TARGET ${name} PROPERTY _EP_BINARY_DIR SET)
    if(have_binary_dir)
      message(FATAL_ERROR
        "External project ${name} has both BINARY_DIR and BUILD_IN_SOURCE!")
    endif()
  endif()
  set(top "${CMAKE_CURRENT_BINARY_DIR}")
  set(places stamp download source binary install tmp)
  foreach(var ${places})
    string(TOUPPER "${var}" VAR)
    get_property(${var}_dir TARGET ${name} PROPERTY _EP_${VAR}_DIR)
    if(NOT ${var}_dir)
      set(${var}_dir "${${var}_default}")
    endif()
    if(NOT IS_ABSOLUTE "${${var}_dir}")
      get_filename_component(${var}_dir "${top}/${${var}_dir}" ABSOLUTE)
    endif()
    set_property(TARGET ${name} PROPERTY _EP_${VAR}_DIR "${${var}_dir}")
  endforeach()
1581
1582
  get_property(source_subdir TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR)
  if(NOT source_subdir)
1583
    set_property(TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR "")
1584
1585
1586
  elseif(IS_ABSOLUTE "${source_subdir}")
    message(FATAL_ERROR
      "External project ${name} has non-relative SOURCE_SUBDIR!")
1587
1588
1589
1590
  else()
    # Prefix with a slash so that when appended to the source directory, it
    # behaves as expected.
    set_property(TARGET ${name} PROPERTY _EP_SOURCE_SUBDIR "/${source_subdir}")
1591
  endif()
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
  if(build_in_source)
    get_property(source_dir TARGET ${name} PROPERTY _EP_SOURCE_DIR)
    set_property(TARGET ${name} PROPERTY _EP_BINARY_DIR "${source_dir}")
  endif()

  # Make the directories at CMake configure time *and* add a custom command
  # to make them at build time. They need to exist at makefile generation
  # time for Borland make and wmake so that CMake may generate makefiles
  # with "cd C:\short\paths\with\no\spaces" commands in them.
  #
  # Additionally, the add_custom_command is still used in case somebody
  # removes one of the necessary directories and tries to rebuild without
  # re-running cmake.
  foreach(var ${places})
    string(TOUPPER "${var}" VAR)
    get_property(dir TARGET ${name} PROPERTY _EP_${VAR}_DIR)
    file(MAKE_DIRECTORY "${dir}")
    if(NOT EXISTS "${dir}")
      message(FATAL_ERROR "dir '${dir}' does not exist after file(MAKE_DIRECTORY)")
    endif()
  endforeach()
1613
endfunction()
1614

1615
1616
1617
1618
1619
1620
1621
1622

# IMPORTANT: this MUST be a macro and not a function because of the
# in-place replacements that occur in each ${var}
#
macro(_ep_replace_location_tags target_name)
  set(vars ${ARGN})
  foreach(var ${vars})
    if(${var})
1623
      foreach(dir SOURCE_DIR SOURCE_SUBDIR BINARY_DIR INSTALL_DIR TMP_DIR DOWNLOADED_FILE)
1624
1625
1626
1627
1628
1629
1630
1631
        get_property(val TARGET ${target_name} PROPERTY _EP_${dir})
        string(REPLACE "<${dir}>" "${val}" ${var} "${${var}}")
      endforeach()
    endif()
  endforeach()
endmacro()


1632
function(_ep_command_line_to_initial_cache var args force)
1633
1634
  set(script_initial_cache "")
  set(regex "^([^:]+):([^=]+)=(.*)$")
1635
  set(setArg "")
1636
1637
1638
1639
  set(forceArg "")
  if(force)
    set(forceArg "FORCE")
  endif()
1640
  foreach(line ${args})
1641
1642
    if("${line}" MATCHES "^-D(.*)")
      set(line "${CMAKE_MATCH_1}")
1643
1644
      if(setArg)
        # This is required to build up lists in variables, or complete an entry
Daniel Pfeifer's avatar
Daniel Pfeifer committed
1645
1646
        string(APPEND setArg "${accumulator}\" CACHE ${type} \"Initial cache\" ${forceArg})")
        string(APPEND script_initial_cache "\n${setArg}")
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
        set(accumulator "")
        set(setArg "")
      endif()
      if("${line}" MATCHES "${regex}")
        set(name "${CMAKE_MATCH_1}")
        set(type "${CMAKE_MATCH_2}")
        set(value "${CMAKE_MATCH_3}")
        set(setArg "set(${name} \"${value}")
      else()
        message(WARNING "Line '${line}' does not match regex. Ignoring.")
      endif()
    else()
      # Assume this is a list to append to the last var
1660
      string(APPEND accumulator ";${line}")
1661
1662
    endif()
  endforeach()
1663
1664
  # Catch the final line of the args
  if(setArg)
Daniel Pfeifer's avatar
Daniel Pfeifer committed
1665
1666
    string(APPEND setArg "${accumulator}\" CACHE ${type} \"Initial cache\" ${forceArg})")
    string(APPEND script_initial_cache "\n${setArg}")
1667
  endif()
1668
1669
1670
1671
1672
1673
  set(${var} ${script_initial_cache} PARENT_SCOPE)
endfunction()


function(_ep_write_initial_cache target_name script_filename script_initial_cache)
  # Write out values into an initial cache, that will be passed to CMake with -C
1674
1675
  # Replace location tags.
  _ep_replace_location_tags(${target_name} script_initial_cache)
1676
  _ep_replace_location_tags(${target_name} script_filename)
1677
  # Write out the initial cache file to the location specified.
1678
  file(GENERATE OUTPUT "${script_filename}" CONTENT "${script_initial_cache}")
1679
endfunction()
1680

1681

1682
function(ExternalProject_Get_Property name)
1683
1684
  foreach(var ${ARGN})
    string(TOUPPER "${var}" VAR)
1685
1686
    get_property(is_set TARGET ${name} PROPERTY _EP_${VAR} SET)
    if(NOT is_set)
1687
1688
      message(FATAL_ERROR "External project \"${name}\" has no ${var}")
    endif()
1689
    get_property(${var} TARGET ${name} PROPERTY _EP_${VAR})
1690
1691
    set(${var} "${${var}}" PARENT_SCOPE)
  endforeach()
1692
endfunction()
1693

1694

1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
function(_ep_get_configure_command_id name cfg_cmd_id_var)
  get_target_property(cmd ${name} _EP_CONFIGURE_COMMAND)

  if(cmd STREQUAL "")
    # Explicit empty string means no configure step for this project
    set(${cfg_cmd_id_var} "none" PARENT_SCOPE)
  else()
    if(NOT cmd)
      # Default is "use cmake":
      set(${cfg_cmd_id_var} "cmake" PARENT_SCOPE)
    else()
      # Otherwise we have to analyze the value:
      if(cmd MATCHES "^[^;]*/configure")
        set(${cfg_cmd_id_var} "configure" PARENT_SCOPE)
      elseif(cmd MATCHES "^[^;]*/cmake" AND NOT cmd MATCHES ";-[PE];")
        set(${cfg_cmd_id_var} "cmake" PARENT_SCOPE)
      elseif(cmd MATCHES "config")
        set(${cfg_cmd_id_var} "configure" PARENT_SCOPE)
      else()
        set(${cfg_cmd_id_var} "unknown:${cmd}" PARENT_SCOPE)
      endif()
    endif()
  endif()
1718
endfunction()
1719

1720

1721
function(_ep_get_build_command name step cmd_var)
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
  set(cmd "")
  set(args)
  _ep_get_configure_command_id(${name} cfg_cmd_id)
  if(cfg_cmd_id STREQUAL "cmake")
    # CMake project.  Select build command based on generator.
    get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR)
    if("${CMAKE_GENERATOR}" MATCHES "Make" AND
       ("${cmake_generator}" MATCHES "Make" OR NOT cmake_generator))
      # The project uses the same Makefile generator.  Use recursive make.
      set(cmd "$(MAKE)")
      if(step STREQUAL "INSTALL")
        set(args install)
      endif()
      if("x${step}x" STREQUAL "xTESTx")
        set(args test)
1737
      endif()
1738
    else()
1739
1740
1741
1742
      # Drive the project with "cmake --build".
      get_target_property(cmake_command ${name} _EP_CMAKE_COMMAND)
      if(cmake_command)
        set(cmd "${cmake_command}")
1743
      else()
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
        set(cmd "${CMAKE_COMMAND}")
      endif()
      set(args --build ".")
      if(CMAKE_CONFIGURATION_TYPES)
        if (CMAKE_CFG_INTDIR AND
            NOT CMAKE_CFG_INTDIR STREQUAL "." AND
            NOT CMAKE_CFG_INTDIR MATCHES "\\$")
          # CMake 3.4 and below used the CMAKE_CFG_INTDIR placeholder value
          # provided by multi-configuration generators.  Some projects were
          # taking advantage of that undocumented implementation detail to
          # specify a specific configuration here.  They should use
          # BUILD_COMMAND to change the default command instead, but for
          # compatibility honor the value.
          set(config ${CMAKE_CFG_INTDIR})
          message(AUTHOR_WARNING "CMAKE_CFG_INTDIR should not be set by project code.\n"
            "To get a non-default build command, use the BUILD_COMMAND option.")
        else()
          set(config $<CONFIG>)
        endif()
        list(APPEND args --config ${config})
1764
      endif()
1765
      if(step STREQUAL "INSTALL")
1766
        list(APPEND args --target install)
1767
      endif()
1768
      # But for "TEST" drive the project with corresponding "ctest".
1769
      if("x${step}x" STREQUAL "xTESTx")