ExternalProject.cmake 62.7 KB
Newer Older
1
2
3
4
5
6
#.rst:
# ExternalProject
# ---------------
#
# Create custom targets to build projects in external trees
#
7
# The ``ExternalProject_Add`` function creates a custom target to drive
8
9
# download, update/patch, configure, build, install and test steps of an
# external project:
10
#
11
# .. code-block:: cmake
12
#
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#  ExternalProject_Add(<name>    # Name for custom target
#    [DEPENDS projects...]       # Targets on which the project depends
#    [PREFIX dir]                # Root dir for entire project
#    [LIST_SEPARATOR sep]        # Sep to be replaced by ; in cmd lines
#    [TMP_DIR dir]               # Directory to store temporary files
#    [STAMP_DIR dir]             # Directory to store step timestamps
#   #--Download step--------------
#    [DOWNLOAD_NAME fname]       # File name to store (if not end of URL)
#    [DOWNLOAD_DIR dir]          # Directory to store downloaded files
#    [DOWNLOAD_COMMAND cmd...]   # Command to download source tree
#    [CVS_REPOSITORY cvsroot]    # CVSROOT of CVS repository
#    [CVS_MODULE mod]            # Module to checkout from CVS repo
#    [CVS_TAG tag]               # Tag to checkout from CVS repo
#    [SVN_REPOSITORY url]        # URL of Subversion repo
#    [SVN_REVISION rev]          # Revision to checkout from Subversion repo
#    [SVN_USERNAME john ]        # Username for Subversion checkout and update
#    [SVN_PASSWORD doe ]         # Password for Subversion checkout and update
#    [SVN_TRUST_CERT 1 ]         # Trust the Subversion server site certificate
#    [GIT_REPOSITORY url]        # URL of git repo
#    [GIT_TAG tag]               # Git branch name, commit id or tag
33
#    [GIT_SUBMODULES modules...] # Git submodules that shall be updated, all if empty
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
#    [HG_REPOSITORY url]         # URL of mercurial repo
#    [HG_TAG tag]                # Mercurial branch name, commit id or tag
#    [URL /.../src.tgz]          # Full path or URL of source
#    [URL_HASH ALGO=value]       # Hash of file at URL
#    [URL_MD5 md5]               # Equivalent to URL_HASH MD5=md5
#    [TLS_VERIFY bool]           # Should certificate for https be checked
#    [TLS_CAINFO file]           # Path to a certificate authority file
#    [TIMEOUT seconds]           # Time allowed for file download operations
#   #--Update/Patch step----------
#    [UPDATE_COMMAND cmd...]     # Source work-tree update command
#    [PATCH_COMMAND cmd...]      # Command to patch downloaded source
#   #--Configure step-------------
#    [SOURCE_DIR dir]            # Source dir to be used for build
#    [CONFIGURE_COMMAND cmd...]  # Build tree configuration command
#    [CMAKE_COMMAND /.../cmake]  # Specify alternative cmake executable
#    [CMAKE_GENERATOR gen]       # Specify generator for native build
#    [CMAKE_GENERATOR_TOOLSET t] # Generator-specific toolset name
#    [CMAKE_ARGS args...]        # Arguments to CMake command line
#    [CMAKE_CACHE_ARGS args...]  # Initial cache arguments, of the form -Dvar:string=on
#   #--Build step-----------------
#    [BINARY_DIR dir]            # Specify build dir location
#    [BUILD_COMMAND cmd...]      # Command to drive the native build
#    [BUILD_IN_SOURCE 1]         # Use source dir for build dir
#   #--Install step---------------
#    [INSTALL_DIR dir]           # Installation prefix
#    [INSTALL_COMMAND cmd...]    # Command to drive install after build
#   #--Test step------------------
#    [TEST_BEFORE_INSTALL 1]     # Add test step executed before install step
#    [TEST_AFTER_INSTALL 1]      # Add test step executed after install step
#    [TEST_COMMAND cmd...]       # Command to drive test
#   #--Output logging-------------
#    [LOG_DOWNLOAD 1]            # Wrap download in script to log output
#    [LOG_UPDATE 1]              # Wrap update in script to log output
#    [LOG_CONFIGURE 1]           # Wrap configure in script to log output
#    [LOG_BUILD 1]               # Wrap build in script to log output
#    [LOG_TEST 1]                # Wrap test in script to log output
#    [LOG_INSTALL 1]             # Wrap install in script to log output
#   #--Custom targets-------------
#    [STEP_TARGETS st1 st2 ...]  # Generate custom targets for these steps
#    )
74
#
75
# The ``*_DIR`` options specify directories for the project, with default
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
# directories computed as follows.  If the ``PREFIX`` option is given to
# ``ExternalProject_Add()`` 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 the build directory corresponding to the
# source directory in which ``ExternalProject_Add`` is invoked.
#
# If ``SOURCE_DIR`` is explicitly set to an existing directory the project
103
# will be built from it.  Otherwise a download step must be specified
104
105
106
# using one of the ``DOWNLOAD_COMMAND``, ``CVS_*``, ``SVN_*``, or ``URL``
# options.  The ``URL`` option may refer locally to a directory or source
# tarball, or refer to a remote tarball (e.g. ``http://.../src.tgz``).
107
#
108
# The ``ExternalProject_Add_Step`` function adds a custom step to an
109
110
# external project:
#
111
# .. code-block:: cmake
112
#
113
114
115
116
117
118
119
120
121
122
#  ExternalProject_Add_Step(<name> <step> # Names of project and custom step
#    [COMMAND cmd...]        # Command line invoked by this step
#    [COMMENT "text..."]     # Text printed when step executes
#    [DEPENDEES steps...]    # Steps on which this step depends
#    [DEPENDERS steps...]    # Steps that depend on this step
#    [DEPENDS files...]      # Files on which this step depends
#    [ALWAYS 1]              # No stamp file, step always runs
#    [WORKING_DIRECTORY dir] # Working directory for command
#    [LOG 1]                 # Wrap step in script to log output
#    )
123
124
#
# The command line, comment, and working directory of every standard and
125
126
127
# custom step is processed to replace tokens ``<SOURCE_DIR>``,
# ``<BINARY_DIR>``, ``<INSTALL_DIR>``, and ``<TMP_DIR>`` with
# corresponding property values.
128
#
129
130
131
132
# Any builtin step that specifies a ``<step>_COMMAND cmd...`` or custom
# step that specifies a ``COMMAND cmd...`` may specify additional command
# lines using the form ``COMMAND cmd...``.  At build time the commands
# will be executed in order and aborted if any one fails.  For example::
133
#
134
#  ... BUILD_COMMAND make COMMAND echo done ...
135
#
136
# specifies to run ``make`` and then ``echo done`` during the build step.
137
# Whether the current working directory is preserved between commands is
138
# not defined.  Behavior of shell operators like ``&&`` is not defined.
139
#
140
141
# The ``ExternalProject_Get_Property`` function retrieves external project
# target properties::
142
#
143
#  ExternalProject_Get_Property(<name> [prop1 [prop2 [...]]])
144
145
146
#
# It stores property values in variables of the same name.  Property
# names correspond to the keyword argument names of
147
# ``ExternalProject_Add``.
148
#
149
150
# The ``ExternalProject_Add_StepTargets`` function generates custom
# targets for the steps listed::
151
#
152
#  ExternalProject_Add_StepTargets(<name> [step1 [step2 [...]]])
153
#
154
# If ``STEP_TARGETS`` is set then ``ExternalProject_Add_StepTargets`` is
155
# automatically called at the end of matching calls to
156
157
158
159
# ``ExternalProject_Add_Step``.  Pass ``STEP_TARGETS`` explicitly to
# individual ``ExternalProject_Add`` calls, or implicitly to all
# ``ExternalProject_Add`` calls by setting the directory property
# ``EP_STEP_TARGETS``.
160
#
161
162
163
# If ``STEP_TARGETS`` is not set, clients may still manually call
# ``ExternalProject_Add_StepTargets`` after calling
# ``ExternalProject_Add`` or ``ExternalProject_Add_Step``.
164
165
#
# This functionality is provided to make it easy to drive the steps
166
167
168
169
170
171
172
173
174
# 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.
#
# For example, to drive configure, build and test steps independently
175
176
177
# for each ``ExternalProject_Add`` call in your project, write the following
# line prior to any ``ExternalProject_Add`` calls in your ``CMakeLists.txt``
# file::
178
#
179
#  set_property(DIRECTORY PROPERTY EP_STEP_TARGETS configure build test)
180

181
#=============================================================================
182
# Copyright 2008-2013 Kitware, Inc.
183
184
185
186
187
188
189
190
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
191
# (To distribute this file outside of CMake, substitute the full
192
#  License text for the above reference.)
193

194
# Pre-compute a regex to match documented keywords for each command.
195
196
197
math(EXPR _ep_documentation_line_count "${CMAKE_CURRENT_LIST_LINE} - 16")
file(STRINGS "${CMAKE_CURRENT_LIST_FILE}" lines
     LIMIT_COUNT ${_ep_documentation_line_count}
198
     REGEX "^#  (  \\[[A-Z0-9_]+ [^]]*\\] +#.*$|[A-Za-z0-9_]+\\()")
199
foreach(line IN LISTS lines)
200
  if("${line}" MATCHES "^#  [A-Za-z0-9_]+\\(")
201
202
203
    if(_ep_func)
      set(_ep_keywords_${_ep_func} "${_ep_keywords_${_ep_func}})$")
    endif()
204
    string(REGEX REPLACE "^#  ([A-Za-z0-9_]+)\\(.*" "\\1" _ep_func "${line}")
205
206
207
208
    #message("function [${_ep_func}]")
    set(_ep_keywords_${_ep_func} "^(")
    set(_ep_keyword_sep)
  else()
209
    string(REGEX REPLACE "^#    \\[([A-Z0-9_]+) .*" "\\1" _ep_key "${line}")
210
211
212
213
214
215
216
217
218
219
    #message("  keyword [${_ep_key}]")
    set(_ep_keywords_${_ep_func}
      "${_ep_keywords_${_ep_func}}${_ep_keyword_sep}${_ep_key}")
    set(_ep_keyword_sep "|")
  endif()
endforeach()
if(_ep_func)
  set(_ep_keywords_${_ep_func} "${_ep_keywords_${_ep_func}})$")
endif()

220
221
222
# Save regex matching supported hash algorithm names.
set(_ep_hash_algos "MD5|SHA1|SHA224|SHA256|SHA384|SHA512")
set(_ep_hash_regex "^(${_ep_hash_algos})=([0-9A-Fa-f]+)$")
223

224
225
226
227
228
229
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
230
231
  # upper-case letter followed by at least two more upper-case letters,
  # numbers or underscores to be keywords.
232
  set(key)
233

234
  foreach(arg IN LISTS args)
235
236
    set(is_value 1)

237
    if(arg MATCHES "^[A-Z][A-Z0-9_][A-Z0-9_]+$" AND
238
239
        NOT ((arg STREQUAL "${key}") AND (key STREQUAL "COMMAND")) AND
        NOT arg MATCHES "^(TRUE|FALSE)$")
240
241
242
243
244
245
246
247
248
249
      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}")
250
        else()
251
252
253
254
255
256
257
          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()
258
        endif()
259
260
261
      else()
        # Missing Keyword
        message(AUTHOR_WARNING "value '${arg}' with no previous keyword in ${f}")
262
263
      endif()
    else()
264
      set(key "${arg}")
265
266
    endif()
  endforeach()
267
endfunction()
268

269

270
271
272
define_property(DIRECTORY PROPERTY "EP_BASE" INHERITED
  BRIEF_DOCS "Base directory for External Project storage."
  FULL_DOCS
273
  "See documentation of the ExternalProject_Add() function in the "
274
275
276
277
278
279
  "ExternalProject module."
  )

define_property(DIRECTORY PROPERTY "EP_PREFIX" INHERITED
  BRIEF_DOCS "Top prefix for External Project storage."
  FULL_DOCS
280
  "See documentation of the ExternalProject_Add() function in the "
281
282
283
  "ExternalProject module."
  )

284
285
286
287
288
289
290
291
define_property(DIRECTORY PROPERTY "EP_STEP_TARGETS" INHERITED
  BRIEF_DOCS
  "List of ExternalProject steps that automatically get corresponding targets"
  FULL_DOCS
  "See documentation of the ExternalProject_Add_StepTargets() function in the "
  "ExternalProject module."
  )

292

293
function(_ep_write_gitclone_script script_filename source_dir git_EXECUTABLE git_repository git_tag git_submodules src_name work_dir gitclone_infofile gitclone_stampfile)
294
295
296
297
298
  file(WRITE ${script_filename}
"if(\"${git_tag}\" STREQUAL \"\")
  message(FATAL_ERROR \"Tag for git checkout should not be empty.\")
endif()

299
300
301
302
303
304
305
306
307
308
309
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()

310
311
312
313
314
315
316
317
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()

318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# 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(
    COMMAND \"${git_EXECUTABLE}\" clone \"${git_repository}\" \"${src_name}\"
    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()
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
if(error_code)
  message(FATAL_ERROR \"Failed to clone repository: '${git_repository}'\")
endif()

execute_process(
  COMMAND \"${git_EXECUTABLE}\" checkout ${git_tag}
  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(
  COMMAND \"${git_EXECUTABLE}\" submodule init
  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(
356
  COMMAND \"${git_EXECUTABLE}\" submodule update --recursive ${git_submodules}
357
358
359
360
361
362
363
  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()

364
365
366
367
368
369
370
371
372
373
374
375
376
# 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()

377
378
379
"
)

380
endfunction()
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
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(
  COMMAND \"${hg_EXECUTABLE}\" clone \"${hg_repository}\" \"${src_name}\"
  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()

443

444
function(_ep_write_gitupdate_script script_filename git_EXECUTABLE git_tag git_submodules git_repository work_dir)
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
  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
  )
if(error_code)
  message(FATAL_ERROR \"Failed to get the hash for HEAD\")
endif()

460
461
462
463
464
465
466
467
468
469
470
471
472
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()

473
474
475
476
477
478
479
480
481
482
# 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
  )

# Is the hash checkout out that we want?
483
if(error_code OR is_remote_ref OR NOT (\"\${tag_sha}\" STREQUAL \"\${head_sha}\"))
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
  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()

  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()

  execute_process(
503
    COMMAND \"${git_EXECUTABLE}\" submodule update --recursive ${git_submodules}
504
505
506
507
508
509
510
511
512
513
514
515
516
    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)

Brad King's avatar
Brad King committed
517
function(_ep_write_downloadfile_script script_filename remote local timeout hash tls_verify tls_cainfo)
518
519
520
521
522
523
  if(timeout)
    set(timeout_args TIMEOUT ${timeout})
    set(timeout_msg "${timeout} seconds")
  else()
    set(timeout_args "# no TIMEOUT")
    set(timeout_msg "none")
524
525
  endif()

526
  if("${hash}" MATCHES "${_ep_hash_regex}")
527
    set(hash_args EXPECTED_HASH ${CMAKE_MATCH_1}=${CMAKE_MATCH_2})
528
  else()
529
    set(hash_args "# no EXPECTED_HASH")
530
  endif()
531
  # check for curl globals in the project
Brad King's avatar
Brad King committed
532
533
  if(DEFINED CMAKE_TLS_VERIFY)
    set(tls_verify "set(CMAKE_TLS_VERIFY ${CMAKE_TLS_VERIFY})")
534
  endif()
Brad King's avatar
Brad King committed
535
536
  if(DEFINED CMAKE_TLS_CAINFO)
    set(tls_cainfo "set(CMAKE_TLS_CAINFO \"${CMAKE_TLS_CAINFO}\")")
537
538
539
540
541
  endif()

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

Brad King's avatar
Brad King committed
542
543
544
545
  # check for tls_verify argument
  string(LENGTH "${tls_verify}" tls_verify_len)
  if(tls_verify_len GREATER 0)
    set(tls_verify "set(CMAKE_TLS_VERIFY ${tls_verify})")
546
  endif()
Brad King's avatar
Brad King committed
547
548
549
550
  # check for tls_cainfo argument
  string(LENGTH "${tls_cainfo}" tls_cainfo_len)
  if(tls_cainfo_len GREATER 0)
    set(tls_cainfo "set(CMAKE_TLS_CAINFO \"${tls_cainfo}\")")
551
  endif()
552

553
554
555
  file(WRITE ${script_filename}
"message(STATUS \"downloading...
     src='${remote}'
556
557
     dst='${local}'
     timeout='${timeout_msg}'\")
558

Brad King's avatar
Brad King committed
559
560
${tls_verify}
${tls_cainfo}
561

562
563
564
file(DOWNLOAD
  \"${remote}\"
  \"${local}\"
565
  SHOW_PROGRESS
566
  ${hash_args}
567
  ${timeout_args}
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
  STATUS status
  LOG log)

list(GET status 0 status_code)
list(GET status 1 status_string)

if(NOT status_code EQUAL 0)
  message(FATAL_ERROR \"error: downloading '${remote}' failed
  status_code: \${status_code}
  status_string: \${status_string}
  log: \${log}
\")
endif()

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

586
endfunction()
587
588


589
function(_ep_write_verifyfile_script script_filename local hash retries download_script)
590
591
592
593
  if("${hash}" MATCHES "${_ep_hash_regex}")
    set(algo "${CMAKE_MATCH_1}")
    string(TOLOWER "${CMAKE_MATCH_2}" expect_value)
    set(script_content "set(expect_value \"${expect_value}\")
594
595
596
597
598
599
600
601
602
603
604
605
606
607
set(attempt 0)
set(succeeded 0)
while(\${attempt} LESS ${retries} OR \${attempt} EQUAL ${retries} AND NOT \${succeeded})
  file(${algo} \"\${file}\" actual_value)
  if(\"\${actual_value}\" STREQUAL \"\${expect_value}\")
    set(succeeded 1)
  elseif(\${attempt} LESS ${retries})
    message(STATUS \"${algo} hash of \${file}
does not match expected value
  expected: \${expect_value}
    actual: \${actual_value}
Retrying download.
\")
    file(REMOVE \"\${file}\")
608
    execute_process(COMMAND \${CMAKE_COMMAND} -P \"${download_script}\")
609
610
611
612
  endif()
endwhile()

if(\${succeeded})
613
614
  message(STATUS \"verifying file... done\")
else()
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
  message(FATAL_ERROR \"error: ${algo} hash of
  \${file}
does not match expected value
  expected: \${expect_value}
    actual: \${actual_value}
\")
endif()")
  else()
    set(script_content "message(STATUS \"verifying file... warning: did not verify file - no URL_HASH specified?\")")
  endif()
  file(WRITE ${script_filename} "set(file \"${local}\")
message(STATUS \"verifying file...
     file='\${file}'\")
${script_content}
")
630
endfunction()
631
632


633
function(_ep_write_extractfile_script script_filename name filename directory)
634
635
  set(args "")

636
  if(filename MATCHES "(\\.|=)(bz2|tar\\.gz|tgz|zip)$")
637
638
639
    set(args xfz)
  endif()

640
  if(filename MATCHES "(\\.|=)tar$")
641
    set(args xf)
642
643
644
  endif()

  if(args STREQUAL "")
645
    message(SEND_ERROR "error: do not know how to extract '${filename}' -- known types are .bz2, .tar, .tar.gz, .tgz and .zip")
646
647
648
649
650
651
652
653
654
655
656
657
658
    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}'\")

659
660
661
662
if(NOT EXISTS \"\${filename}\")
  message(FATAL_ERROR \"error: file to extract does not exist: '\${filename}'\")
endif()

663
664
# Prepare a space for extracting:
#
665
set(i 1234)
666
while(EXISTS \"\${directory}/../ex-${name}\${i}\")
667
668
  math(EXPR i \"\${i} + 1\")
endwhile()
669
set(ut_dir \"\${directory}/../ex-${name}\${i}\")
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
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}/*\")
list(LENGTH contents n)
if(NOT n EQUAL 1 OR NOT IS_DIRECTORY \"\${contents}\")
  set(contents \"\${ut_dir}\")
endif()

694
# Move \"the one\" directory to the final directory:
695
#
696
697
698
699
message(STATUS \"extracting... [rename]\")
file(REMOVE_RECURSE \${directory})
get_filename_component(contents \${contents} ABSOLUTE)
file(RENAME \${contents} \${directory})
700
701
702
703
704
705
706
707
708
709

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

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

710
endfunction()
711
712


713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
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}")
731
  else()
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
    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()
  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()
781
endfunction()
782

783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800

# 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})
      foreach(dir SOURCE_DIR BINARY_DIR INSTALL_DIR TMP_DIR)
        get_property(val TARGET ${target_name} PROPERTY _EP_${dir})
        string(REPLACE "<${dir}>" "${val}" ${var} "${${var}}")
      endforeach()
    endif()
  endforeach()
endmacro()


function(_ep_write_initial_cache target_name script_filename args)
801
802
803
  # Write out values into an initial cache, that will be passed to CMake with -C
  set(script_initial_cache "")
  set(regex "^([^:]+):([^=]+)=(.*)$")
804
  set(setArg "")
805
  foreach(line ${args})
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
    if("${line}" MATCHES "^-D")
      if(setArg)
        # This is required to build up lists in variables, or complete an entry
        set(setArg "${setArg}${accumulator}\" CACHE ${type} \"Initial cache\" FORCE)")
        set(script_initial_cache "${script_initial_cache}\n${setArg}")
        set(accumulator "")
        set(setArg "")
      endif()
      string(REGEX REPLACE "^-D" "" line ${line})
      if("${line}" MATCHES "${regex}")
        string(REGEX MATCH "${regex}" match "${line}")
        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
      set(accumulator "${accumulator};${line}")
827
828
    endif()
  endforeach()
829
830
831
832
833
  # Catch the final line of the args
  if(setArg)
    set(setArg "${setArg}${accumulator}\" CACHE ${type} \"Initial cache\" FORCE)")
    set(script_initial_cache "${script_initial_cache}\n${setArg}")
  endif()
834
835
  # Replace location tags.
  _ep_replace_location_tags(${target_name} script_initial_cache)
836
837
  # Write out the initial cache file to the location specified.
  if(NOT EXISTS "${script_filename}.in")
838
    file(WRITE "${script_filename}.in" "\@script_initial_cache\@\n")
839
840
  endif()
  configure_file("${script_filename}.in" "${script_filename}")
841
endfunction()
842

843

844
function(ExternalProject_Get_Property name)
845
846
847
848
849
850
851
852
  foreach(var ${ARGN})
    string(TOUPPER "${var}" VAR)
    get_property(${var} TARGET ${name} PROPERTY _EP_${VAR})
    if(NOT ${var})
      message(FATAL_ERROR "External project \"${name}\" has no ${var}")
    endif()
    set(${var} "${${var}}" PARENT_SCOPE)
  endforeach()
853
endfunction()
854

855

856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
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()
879
endfunction()
880

881

882
883
884
885
886
887
888
889
function(_ep_get_build_command name step cmd_var)
  set(cmd "${${cmd_var}}")
  if(NOT 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)
890
      if("${CMAKE_GENERATOR}" MATCHES "Make" AND
891
         ("${cmake_generator}" MATCHES "Make" OR NOT cmake_generator))
892
893
894
895
896
        # The project uses the same Makefile generator.  Use recursive make.
        set(cmd "$(MAKE)")
        if(step STREQUAL "INSTALL")
          set(args install)
        endif()
897
898
899
        if(step STREQUAL "TEST")
          set(args test)
        endif()
900
901
902
903
904
905
906
907
908
909
910
911
      else()
        # Drive the project with "cmake --build".
        get_target_property(cmake_command ${name} _EP_CMAKE_COMMAND)
        if(cmake_command)
          set(cmd "${cmake_command}")
        else()
          set(cmd "${CMAKE_COMMAND}")
        endif()
        set(args --build ${binary_dir} --config ${CMAKE_CFG_INTDIR})
        if(step STREQUAL "INSTALL")
          list(APPEND args --target install)
        endif()
912
913
914
915
916
        # But for "TEST" drive the project with corresponding "ctest".
        if(step STREQUAL "TEST")
          string(REGEX REPLACE "^(.*/)cmake([^/]*)$" "\\1ctest\\2" cmd "${cmd}")
          set(args "")
        endif()
917
      endif()
918
    else()
919
      # Non-CMake project.  Guess "make" and "make install" and "make test".
920
921
922
923
924
925
      if("${CMAKE_GENERATOR}" MATCHES "Makefiles")
        # Try to get the parallel arguments
        set(cmd "$(MAKE)")
      else()
        set(cmd "make")
      endif()
926
927
928
      if(step STREQUAL "INSTALL")
        set(args install)
      endif()
929
930
931
      if(step STREQUAL "TEST")
        set(args test)
      endif()
932
933
934
935
936
937
938
939
940
941
942
943
    endif()

    # Use user-specified arguments instead of default arguments, if any.
    get_property(have_args TARGET ${name} PROPERTY _EP_${step}_ARGS SET)
    if(have_args)
      get_target_property(args ${name} _EP_${step}_ARGS)
    endif()

    list(APPEND cmd ${args})
  endif()

  set(${cmd_var} "${cmd}" PARENT_SCOPE)
944
endfunction()
945

946
947
948
949
950
function(_ep_write_log_script name step cmd_var)
  ExternalProject_Get_Property(${name} stamp_dir)
  set(command "${${cmd_var}}")

  set(make "")
951
  set(code_cygpath_make "")
952
953
954
955
956
  if("${command}" MATCHES "^\\$\\(MAKE\\)")
    # GNU make recognizes the string "$(MAKE)" as recursive make, so
    # ensure that it appears directly in the makefile.
    string(REGEX REPLACE "^\\$\\(MAKE\\)" "\${make}" command "${command}")
    set(make "-Dmake=$(MAKE)")
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973

    if(WIN32 AND NOT CYGWIN)
      set(code_cygpath_make "
if(\${make} MATCHES \"^/\")
  execute_process(
    COMMAND cygpath -w \${make}
    OUTPUT_VARIABLE cygpath_make
    ERROR_VARIABLE cygpath_make
    RESULT_VARIABLE cygpath_error
    OUTPUT_STRIP_TRAILING_WHITESPACE
  )
  if(NOT cygpath_error)
    set(make \${cygpath_make})
  endif()
endif()
")
    endif()
974
975
976
977
978
979
980
981
982
983
984
985
  endif()

  set(config "")
  if("${CMAKE_CFG_INTDIR}" MATCHES "^\\$")
    string(REPLACE "${CMAKE_CFG_INTDIR}" "\${config}" command "${command}")
    set(config "-Dconfig=${CMAKE_CFG_INTDIR}")
  endif()

  # Wrap multiple 'COMMAND' lines up into a second-level wrapper
  # script so all output can be sent to one log file.
  if("${command}" MATCHES ";COMMAND;")
    set(code_execute_process "
986
${code_cygpath_make}
987
988
989
990
991
execute_process(COMMAND \${command} RESULT_VARIABLE result)
if(result)
  set(msg \"Command failed (\${result}):\\n\")
  foreach(arg IN LISTS command)
    set(msg \"\${msg} '\${arg}'\")
992
  endforeach()
993
994
995
996
997
998
999
1000
  message(FATAL_ERROR \"\${msg}\")
endif()
")
    set(code "")
    set(cmd "")
    set(sep "")
    foreach(arg IN LISTS command)
      if("x${arg}" STREQUAL "xCOMMAND")