cmake-pre-commit-hooks 1.10.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cmake_pc_hooks/__init__.py +15 -0
- cmake_pc_hooks/_argparse.py +332 -0
- cmake_pc_hooks/_call_process.py +74 -0
- cmake_pc_hooks/_cmake.py +659 -0
- cmake_pc_hooks/_utils.py +242 -0
- cmake_pc_hooks/clang_format.py +59 -0
- cmake_pc_hooks/clang_tidy.py +82 -0
- cmake_pc_hooks/cppcheck.py +87 -0
- cmake_pc_hooks/cpplint.py +20 -0
- cmake_pc_hooks/include_what_you_use.py +141 -0
- cmake_pc_hooks/lizard.py +72 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/METADATA +396 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/RECORD +17 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/WHEEL +5 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/entry_points.txt +7 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/licenses/LICENSE +201 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/top_level.txt +1 -0
cmake_pc_hooks/_cmake.py
ADDED
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
# Copyright 2023 Damien Nguyen <ngn.damien@gmail.com>
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""CMake related function and classes."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import contextlib
|
|
20
|
+
import json
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import platform
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess as sp
|
|
27
|
+
import sys
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
import fasteners
|
|
31
|
+
|
|
32
|
+
from . import _argparse, _call_process
|
|
33
|
+
|
|
34
|
+
log = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
# ==============================================================================
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _try_calling_cmake(cmake_cmd: list[str | Path]) -> bool:
|
|
40
|
+
"""
|
|
41
|
+
Try to call CMake using the provided command.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
cmake_cmd: CMake command line
|
|
45
|
+
|
|
46
|
+
Return:
|
|
47
|
+
True if command line is valid, False otherwise
|
|
48
|
+
"""
|
|
49
|
+
with Path(os.devnull).open(mode='w', encoding='utf-8') as devnull:
|
|
50
|
+
try:
|
|
51
|
+
sp.check_call([*cmake_cmd, '--version'], stdout=devnull, stderr=devnull)
|
|
52
|
+
except (OSError, sp.CalledProcessError):
|
|
53
|
+
return False
|
|
54
|
+
else:
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def get_cmake_command(cmake_names=None): # pragma: nocover
|
|
59
|
+
"""
|
|
60
|
+
Get the path to a CMake executable on the PATH or in the virtual environment.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
cmake_names (:obj:`list` of :obj:`str`): Names for the CMake command
|
|
64
|
+
Defaults to ['cmake', 'cmake3']
|
|
65
|
+
"""
|
|
66
|
+
if not cmake_names:
|
|
67
|
+
cmake_names = ['cmake', 'cmake3']
|
|
68
|
+
|
|
69
|
+
for cmake in cmake_names:
|
|
70
|
+
cmake_cmd = shutil.which(cmake)
|
|
71
|
+
if cmake_cmd is not None and _try_calling_cmake([cmake_cmd]):
|
|
72
|
+
return [cmake_cmd]
|
|
73
|
+
|
|
74
|
+
# CMake not in PATH, should have installed Python CMake module
|
|
75
|
+
# -> try to find out where it is
|
|
76
|
+
python_executable = Path(sys.executable)
|
|
77
|
+
try:
|
|
78
|
+
root_path = Path(os.environ['VIRTUAL_ENV'])
|
|
79
|
+
python = python_executable.name
|
|
80
|
+
except KeyError:
|
|
81
|
+
root_path = python_executable.parent
|
|
82
|
+
python = python_executable.name
|
|
83
|
+
|
|
84
|
+
search_paths = [root_path, root_path / 'bin', root_path / 'Scripts']
|
|
85
|
+
|
|
86
|
+
# First try executing CMake directly
|
|
87
|
+
for base_path in search_paths:
|
|
88
|
+
cmake_cmd = [base_path / cmake]
|
|
89
|
+
if _try_calling_cmake(cmake_cmd):
|
|
90
|
+
return cmake_cmd
|
|
91
|
+
|
|
92
|
+
# That did not work: try calling it through Python
|
|
93
|
+
for base_path in search_paths:
|
|
94
|
+
cmake_cmd = [python, base_path / 'cmake']
|
|
95
|
+
if _try_calling_cmake(cmake_cmd):
|
|
96
|
+
return cmake_cmd
|
|
97
|
+
|
|
98
|
+
# Nothing worked -> give up!
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class CMakeCommand:
|
|
103
|
+
"""Class used to encapsulate all CMake related functionality."""
|
|
104
|
+
|
|
105
|
+
DEFAULT_BUILD_DIR = '.cmake_build'
|
|
106
|
+
DEFAULT_TRACE_LOG = 'trace_log.json'
|
|
107
|
+
CODEGEN_TARGET = 'codegen'
|
|
108
|
+
CODEGEN_MIN_VERSION = (3, 31)
|
|
109
|
+
CODEGEN_GENERATORS = ('Ninja', 'Makefiles')
|
|
110
|
+
|
|
111
|
+
def __init__(self, cmake_names=None):
|
|
112
|
+
"""
|
|
113
|
+
Initialize a CMakeCommand object.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
cmake_names (list[str] | None): List of possible names for the CMake executable
|
|
117
|
+
"""
|
|
118
|
+
self.command = get_cmake_command(cmake_names)
|
|
119
|
+
self.source_dir = None
|
|
120
|
+
self.build_dir = None
|
|
121
|
+
self.cmake_args = ['-DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=ON']
|
|
122
|
+
self.cmake_trace_log = None
|
|
123
|
+
self.cmake_configured_files = []
|
|
124
|
+
self.no_cmake_configure = False
|
|
125
|
+
self.build_targets = []
|
|
126
|
+
self.codegen = False
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def add_cmake_arguments_to_parser(parser):
|
|
130
|
+
"""Add CMake options to an argparse.ArgumentParser."""
|
|
131
|
+
# Create option group here to control the order
|
|
132
|
+
cmake_options = parser.add_argument_group(
|
|
133
|
+
title='CMake options',
|
|
134
|
+
description='Options mirroring those of CMake and that will be passed onto CMake as-is.',
|
|
135
|
+
)
|
|
136
|
+
options = parser.add_argument_group(
|
|
137
|
+
title='Other CMake related options',
|
|
138
|
+
description='Options used to configure how CMake is called',
|
|
139
|
+
)
|
|
140
|
+
platform_specific_cmake = parser.add_argument_group(
|
|
141
|
+
title='Options to define platform-dependent CMake variables',
|
|
142
|
+
description=(
|
|
143
|
+
'This allows you to set CMake variables during the configuration depending on the platform the hooks '
|
|
144
|
+
'are currently running on.'
|
|
145
|
+
'For example --unix="CMAKE_CXX_COMPILER=g++" will only define this CMake variable on UNIX platforms.'
|
|
146
|
+
),
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Custom options
|
|
150
|
+
options.add_argument('--clean', action='store_true', help='Start from a clean build directory')
|
|
151
|
+
options.add_argument(
|
|
152
|
+
'--cmake',
|
|
153
|
+
type=_argparse.executable_path,
|
|
154
|
+
help='Specify path to CMake executable.',
|
|
155
|
+
)
|
|
156
|
+
options.add_argument(
|
|
157
|
+
'--cmake-build-target',
|
|
158
|
+
action='append',
|
|
159
|
+
dest='build_targets',
|
|
160
|
+
type=str,
|
|
161
|
+
help=(
|
|
162
|
+
'Build a CMake target after the configure step and before running the hook, e.g. to generate source '
|
|
163
|
+
'files (may be specified multiple times)'
|
|
164
|
+
),
|
|
165
|
+
default=[],
|
|
166
|
+
)
|
|
167
|
+
options.add_argument(
|
|
168
|
+
'--codegen',
|
|
169
|
+
action='store_true',
|
|
170
|
+
help=(
|
|
171
|
+
'Build the `codegen` CMake target after the configure step in order to generate source files '
|
|
172
|
+
'(requires CMake >= 3.31 and a Ninja or Makefile generator)'
|
|
173
|
+
),
|
|
174
|
+
)
|
|
175
|
+
options.add_argument(
|
|
176
|
+
'--detect-configured-files',
|
|
177
|
+
action='store_true',
|
|
178
|
+
help='Enable tracing of files generated using the configure_file(...) CMake function',
|
|
179
|
+
)
|
|
180
|
+
options.add_argument(
|
|
181
|
+
'--no-automatic-discovery',
|
|
182
|
+
action='store_false',
|
|
183
|
+
dest='automatic_discovery',
|
|
184
|
+
help='Do not attempt to automatically look for a build directory',
|
|
185
|
+
)
|
|
186
|
+
options.add_argument(
|
|
187
|
+
'--no-cmake-configure',
|
|
188
|
+
action='store_true',
|
|
189
|
+
dest='no_cmake_configure',
|
|
190
|
+
help=(
|
|
191
|
+
'Do not call CMake configure to generate a compilation database '
|
|
192
|
+
'(ie. do not call CMake but still try to locate a compilation database if possible)'
|
|
193
|
+
),
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
# Platform-specific CMake options
|
|
197
|
+
platform_specific_cmake.add_argument(
|
|
198
|
+
'--unix',
|
|
199
|
+
action=_argparse.OSSpecificAction,
|
|
200
|
+
type=str,
|
|
201
|
+
help='Unix-only (ie. Linux and MacOS) options for CMake',
|
|
202
|
+
)
|
|
203
|
+
platform_specific_cmake.add_argument(
|
|
204
|
+
'--linux',
|
|
205
|
+
action=_argparse.OSSpecificAction,
|
|
206
|
+
type=str,
|
|
207
|
+
help='Linux-only options for CMake',
|
|
208
|
+
)
|
|
209
|
+
platform_specific_cmake.add_argument(
|
|
210
|
+
'--mac',
|
|
211
|
+
action=_argparse.OSSpecificAction,
|
|
212
|
+
type=str,
|
|
213
|
+
help='Mac-only options for CMake',
|
|
214
|
+
)
|
|
215
|
+
platform_specific_cmake.add_argument(
|
|
216
|
+
'--win',
|
|
217
|
+
action=_argparse.OSSpecificAction,
|
|
218
|
+
type=str,
|
|
219
|
+
help='Windows-only options for CMake',
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
# CMake-like options
|
|
223
|
+
cmake_options.add_argument('-S', '--source-dir', type=str, help='Path to build directory', default='.')
|
|
224
|
+
cmake_options.add_argument(
|
|
225
|
+
'-B',
|
|
226
|
+
'--build-dir',
|
|
227
|
+
action='append',
|
|
228
|
+
type=str,
|
|
229
|
+
help='Path to build directory',
|
|
230
|
+
)
|
|
231
|
+
cmake_options.add_argument(
|
|
232
|
+
'-D',
|
|
233
|
+
dest='defines',
|
|
234
|
+
action='append',
|
|
235
|
+
type=str,
|
|
236
|
+
help='Create or update a cmake cache entry.',
|
|
237
|
+
default=[],
|
|
238
|
+
)
|
|
239
|
+
cmake_options.add_argument(
|
|
240
|
+
'-U',
|
|
241
|
+
dest='undefines',
|
|
242
|
+
action='append',
|
|
243
|
+
type=str,
|
|
244
|
+
help='Remove matching entries from CMake cache.',
|
|
245
|
+
default=[],
|
|
246
|
+
)
|
|
247
|
+
cmake_options.add_argument('-G', dest='generator', type=str, help='Specify a build system generator.')
|
|
248
|
+
cmake_options.add_argument(
|
|
249
|
+
'-T',
|
|
250
|
+
dest='toolset',
|
|
251
|
+
type=str,
|
|
252
|
+
help='Specify toolset name if supported by generator.',
|
|
253
|
+
)
|
|
254
|
+
cmake_options.add_argument(
|
|
255
|
+
'-A',
|
|
256
|
+
dest='platform',
|
|
257
|
+
type=str,
|
|
258
|
+
help='Specify platform if supported by generator.',
|
|
259
|
+
)
|
|
260
|
+
cmake_options.add_argument(
|
|
261
|
+
'-Werror',
|
|
262
|
+
dest='errors',
|
|
263
|
+
choices=['dev'],
|
|
264
|
+
help='Make developer warnings errors.',
|
|
265
|
+
default=[],
|
|
266
|
+
)
|
|
267
|
+
cmake_options.add_argument(
|
|
268
|
+
'-Wno-error',
|
|
269
|
+
dest='no_errors',
|
|
270
|
+
choices=['dev'],
|
|
271
|
+
help='Make developer warnings not errors.',
|
|
272
|
+
default=[],
|
|
273
|
+
)
|
|
274
|
+
cmake_options.add_argument('--preset', type=str, help='Specify a configure preset.')
|
|
275
|
+
|
|
276
|
+
cmake_options.add_argument(
|
|
277
|
+
'-Wdev',
|
|
278
|
+
dest='dev_warnings',
|
|
279
|
+
action='store_true',
|
|
280
|
+
help='Enable developer warnings.',
|
|
281
|
+
)
|
|
282
|
+
cmake_options.add_argument(
|
|
283
|
+
'-Wno-dev',
|
|
284
|
+
dest='no_dev_warnings',
|
|
285
|
+
action='store_true',
|
|
286
|
+
help='Suppress developer warnings.',
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
def resolve_build_directory(self, build_dir_list=None, *, automatic_discovery=True):
|
|
290
|
+
"""Locate a valid build directory based on internal list and automatic discovery if enabled."""
|
|
291
|
+
# First try to locate a valid build directory based on internal list
|
|
292
|
+
build_dir_list = [] if build_dir_list is None else [Path(path) for path in build_dir_list]
|
|
293
|
+
for build_dir in build_dir_list:
|
|
294
|
+
if build_dir.exists() and Path(build_dir, 'CMakeCache.txt').exists():
|
|
295
|
+
log.debug(
|
|
296
|
+
'Located valid build directory with CMakeCache.txt at: %s',
|
|
297
|
+
build_dir,
|
|
298
|
+
)
|
|
299
|
+
self.build_dir = build_dir.resolve()
|
|
300
|
+
return
|
|
301
|
+
|
|
302
|
+
# If that fails or none have been passed, attempt automatic discovery
|
|
303
|
+
if automatic_discovery:
|
|
304
|
+
for path in sorted(self.source_dir.glob('*')):
|
|
305
|
+
if path.is_dir() and (path / 'CMakeCache.txt').exists():
|
|
306
|
+
log.info('Automatic build dir discovery resulted in: %s', path)
|
|
307
|
+
self.build_dir = path
|
|
308
|
+
return
|
|
309
|
+
|
|
310
|
+
if self.no_cmake_configure:
|
|
311
|
+
log.info('Unable to locate a valid build directory. Will not be creating one')
|
|
312
|
+
self.build_dir = None
|
|
313
|
+
return
|
|
314
|
+
|
|
315
|
+
if not build_dir_list:
|
|
316
|
+
self.build_dir = self.source_dir / self.DEFAULT_BUILD_DIR
|
|
317
|
+
else:
|
|
318
|
+
self.build_dir = Path(build_dir_list[0]).resolve()
|
|
319
|
+
log.info(
|
|
320
|
+
'Unable to locate a valid build directory. Will be creating one at %s',
|
|
321
|
+
self.build_dir,
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
def _process_keyword_cmake_args(self, cmake_args):
|
|
325
|
+
"""Process keyword-style CMake arguments."""
|
|
326
|
+
keyword_args = {
|
|
327
|
+
'defines': ([], '-D{}'),
|
|
328
|
+
'undefines': ([], '-U{}'),
|
|
329
|
+
'errors': ([], '-Werror={}'),
|
|
330
|
+
'no_errors': ([], '-Wno-error={}'),
|
|
331
|
+
'generator': ('', '-G{}'),
|
|
332
|
+
'toolset': ('', '-T{}'),
|
|
333
|
+
'platform': ('', '-A{}'),
|
|
334
|
+
'preset': ('', '--preset={}'),
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
for key, (default, format_str) in keyword_args.items():
|
|
338
|
+
value = getattr(cmake_args, key, default)
|
|
339
|
+
if value:
|
|
340
|
+
if isinstance(value, str):
|
|
341
|
+
self.cmake_args.append(format_str.format(value))
|
|
342
|
+
else:
|
|
343
|
+
for element in value:
|
|
344
|
+
self.cmake_args.append(format_str.format(element))
|
|
345
|
+
|
|
346
|
+
def _process_flag_cmake_args(self, cmake_args):
|
|
347
|
+
"""Process flag-style CMake arguments."""
|
|
348
|
+
flag_args = {
|
|
349
|
+
'dev_warnings': (False, '-Wdev'),
|
|
350
|
+
'no_dev_warnings': (False, '-Wno-dev'),
|
|
351
|
+
}
|
|
352
|
+
for key, (default, flag_str) in flag_args.items():
|
|
353
|
+
if getattr(cmake_args, key, default):
|
|
354
|
+
self.cmake_args.append(flag_str)
|
|
355
|
+
|
|
356
|
+
def _process_platform_cmake_args(self, cmake_args):
|
|
357
|
+
"""Process platform-specific CMake arguments."""
|
|
358
|
+
platform_args_config = {
|
|
359
|
+
'linux': ([], 'Linux'),
|
|
360
|
+
'mac': ([], 'Darwin'),
|
|
361
|
+
'win': ([], 'Windows'),
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
for key, (default, platform_name) in platform_args_config.items():
|
|
365
|
+
platform_arg_values = getattr(cmake_args, key, default)
|
|
366
|
+
if platform.system() == platform_name and platform_arg_values:
|
|
367
|
+
for arg in platform_arg_values:
|
|
368
|
+
self.cmake_args.append(arg.strip('"\''))
|
|
369
|
+
|
|
370
|
+
def setup_cmake_args(self, cmake_args):
|
|
371
|
+
"""
|
|
372
|
+
Setup CMake arguments.
|
|
373
|
+
|
|
374
|
+
Args:
|
|
375
|
+
cmake_args: Dictionary-like data structure with following keys:
|
|
376
|
+
- 'defines': list[str]
|
|
377
|
+
- 'undefined': list[str]
|
|
378
|
+
- 'errors': list[str]
|
|
379
|
+
- 'no_errors': list[str]
|
|
380
|
+
- 'generator': str
|
|
381
|
+
- 'toolset': str
|
|
382
|
+
- 'platform': str
|
|
383
|
+
- 'preset': str
|
|
384
|
+
- 'cmake': str
|
|
385
|
+
- 'dev_warnings': bool
|
|
386
|
+
- 'no_dev_warnings': bool
|
|
387
|
+
- 'linux': list[str]
|
|
388
|
+
- 'mac': list[str]
|
|
389
|
+
- 'win': list[str]
|
|
390
|
+
"""
|
|
391
|
+
self.source_dir = Path(cmake_args.source_dir).resolve()
|
|
392
|
+
if cmake_args.cmake:
|
|
393
|
+
self.command = [Path(cmake_args.cmake).resolve()]
|
|
394
|
+
self.no_cmake_configure = cmake_args.no_cmake_configure
|
|
395
|
+
self.codegen = bool(getattr(cmake_args, 'codegen', False))
|
|
396
|
+
self.build_targets = list(getattr(cmake_args, 'build_targets', None) or [])
|
|
397
|
+
if self.codegen and self.CODEGEN_TARGET not in self.build_targets:
|
|
398
|
+
self.build_targets.append(self.CODEGEN_TARGET)
|
|
399
|
+
|
|
400
|
+
self.resolve_build_directory(
|
|
401
|
+
build_dir_list=cmake_args.build_dir,
|
|
402
|
+
automatic_discovery=cmake_args.automatic_discovery,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
if cmake_args.detect_configured_files and self.build_dir:
|
|
406
|
+
self.cmake_trace_log = self.build_dir / self.DEFAULT_TRACE_LOG
|
|
407
|
+
|
|
408
|
+
self._process_keyword_cmake_args(cmake_args)
|
|
409
|
+
self._process_flag_cmake_args(cmake_args)
|
|
410
|
+
self._process_platform_cmake_args(cmake_args)
|
|
411
|
+
|
|
412
|
+
def configure(self, command, *, clean_build=False):
|
|
413
|
+
"""
|
|
414
|
+
Run a CMake configure step (multi-process safe).
|
|
415
|
+
|
|
416
|
+
Args:
|
|
417
|
+
command (str): Name of calling command
|
|
418
|
+
clean_build (bool): Clean build directory before calling CMake configure
|
|
419
|
+
"""
|
|
420
|
+
if self.no_cmake_configure:
|
|
421
|
+
log.debug('Not calling CMake configure')
|
|
422
|
+
if self.build_targets:
|
|
423
|
+
log.warning(
|
|
424
|
+
'Not building CMake target(s) %s since --no-cmake-configure was specified',
|
|
425
|
+
', '.join(self.build_targets),
|
|
426
|
+
)
|
|
427
|
+
return
|
|
428
|
+
|
|
429
|
+
if self.source_dir is None:
|
|
430
|
+
log.error('No source dir was for CMake! Did you call `setup_cmake_args()`?')
|
|
431
|
+
sys.exit(1)
|
|
432
|
+
|
|
433
|
+
if self.codegen:
|
|
434
|
+
self._check_codegen_cmake_version()
|
|
435
|
+
|
|
436
|
+
cmake_configure_lock_file = Path(self.build_dir, '_cmake_configure_lock')
|
|
437
|
+
|
|
438
|
+
self.build_dir.mkdir(exist_ok=True)
|
|
439
|
+
|
|
440
|
+
# NB: whether a process runs the CMake configure step or waits for another process to do so must be decided
|
|
441
|
+
# by a single atomic operation. Otherwise a process may be done waiting before the configure step of
|
|
442
|
+
# another process even started.
|
|
443
|
+
cmake_configure_lock = fasteners.InterProcessReaderWriterLock(cmake_configure_lock_file)
|
|
444
|
+
step = 'configure'
|
|
445
|
+
if cmake_configure_lock.acquire_write_lock(blocking=False):
|
|
446
|
+
try:
|
|
447
|
+
log.debug('Command %s with id %s is running CMake configure', command, os.getpid())
|
|
448
|
+
step, returncode = self._configure_and_build(
|
|
449
|
+
lock_files=(cmake_configure_lock_file,), clean_build=clean_build
|
|
450
|
+
)
|
|
451
|
+
log.debug('Command %s with id %s is done running CMake configure', command, os.getpid())
|
|
452
|
+
finally:
|
|
453
|
+
cmake_configure_lock.release_write_lock()
|
|
454
|
+
else:
|
|
455
|
+
log.debug('Command %s with id %s is not running CMake configure and waiting', command, os.getpid())
|
|
456
|
+
with cmake_configure_lock.read_lock():
|
|
457
|
+
log.debug('Command %s with id %s is done waiting', command, os.getpid())
|
|
458
|
+
returncode = 0
|
|
459
|
+
|
|
460
|
+
if returncode != 0:
|
|
461
|
+
log.error('CMake %s step failed. See output for more information.', step)
|
|
462
|
+
sys.exit(returncode)
|
|
463
|
+
|
|
464
|
+
if self.cmake_trace_log is not None:
|
|
465
|
+
self._parse_cmake_trace_log()
|
|
466
|
+
|
|
467
|
+
def _configure_and_build(self, lock_files, clean_build):
|
|
468
|
+
"""
|
|
469
|
+
Run a CMake configure step followed by a build of the requested targets (if any).
|
|
470
|
+
|
|
471
|
+
The return value is a tuple with the name of the last step that was run and its return code.
|
|
472
|
+
"""
|
|
473
|
+
returncode = self._configure(lock_files=lock_files, clean_build=clean_build)
|
|
474
|
+
if returncode == 0 and self.build_targets:
|
|
475
|
+
return 'build', self._build()
|
|
476
|
+
return 'configure', returncode
|
|
477
|
+
|
|
478
|
+
def get_version(self):
|
|
479
|
+
"""
|
|
480
|
+
Retrieve the version of the CMake executable.
|
|
481
|
+
|
|
482
|
+
The version is a tuple of integers (major, minor, patch) or None if the version could not be determined.
|
|
483
|
+
"""
|
|
484
|
+
if not self.command:
|
|
485
|
+
return None
|
|
486
|
+
|
|
487
|
+
try:
|
|
488
|
+
result = _call_process.call_process([*(str(cmd) for cmd in self.command), '--version'])
|
|
489
|
+
except OSError:
|
|
490
|
+
return None
|
|
491
|
+
|
|
492
|
+
version = re.search(r'version\s+(\d+)\.(\d+)(?:\.(\d+))?', result.stdout)
|
|
493
|
+
if result.returncode != 0 or not version:
|
|
494
|
+
return None
|
|
495
|
+
return tuple(int(part or 0) for part in version.groups())
|
|
496
|
+
|
|
497
|
+
def _check_codegen_cmake_version(self):
|
|
498
|
+
"""Make sure that the CMake executable is recent enough to provide the `codegen` target."""
|
|
499
|
+
version = self.get_version()
|
|
500
|
+
min_version_str = '.'.join(str(part) for part in self.CODEGEN_MIN_VERSION)
|
|
501
|
+
if version is None:
|
|
502
|
+
log.warning(
|
|
503
|
+
'Unable to determine the CMake version: --codegen requires CMake >= %s',
|
|
504
|
+
min_version_str,
|
|
505
|
+
)
|
|
506
|
+
return
|
|
507
|
+
|
|
508
|
+
if version[: len(self.CODEGEN_MIN_VERSION)] < self.CODEGEN_MIN_VERSION:
|
|
509
|
+
log.error(
|
|
510
|
+
'--codegen requires CMake >= %s, but found CMake %s. Either upgrade CMake (or use --cmake to point to '
|
|
511
|
+
'a newer one) or use --cmake-build-target to build a target of your project that generates the files.',
|
|
512
|
+
min_version_str,
|
|
513
|
+
'.'.join(str(part) for part in version),
|
|
514
|
+
)
|
|
515
|
+
sys.exit(1)
|
|
516
|
+
|
|
517
|
+
def _get_generator(self):
|
|
518
|
+
"""Read the name of the CMake generator from the CMake cache (None if not found)."""
|
|
519
|
+
try:
|
|
520
|
+
cache = Path(self.build_dir, 'CMakeCache.txt').read_text(encoding='utf-8', errors='replace')
|
|
521
|
+
except OSError:
|
|
522
|
+
return None
|
|
523
|
+
generator = re.search(r'^CMAKE_GENERATOR:\w+=(.*)$', cache, flags=re.MULTILINE)
|
|
524
|
+
return generator.group(1).strip() if generator else None
|
|
525
|
+
|
|
526
|
+
def _build(self):
|
|
527
|
+
"""Build some CMake targets (must be called after a successful CMake configure step)."""
|
|
528
|
+
if self.codegen:
|
|
529
|
+
generator = self._get_generator()
|
|
530
|
+
if generator is not None and not any(name in generator for name in self.CODEGEN_GENERATORS):
|
|
531
|
+
log.error(
|
|
532
|
+
'--codegen is only supported with the Ninja and Makefile generators, but %s is using "%s"',
|
|
533
|
+
self.build_dir,
|
|
534
|
+
generator,
|
|
535
|
+
)
|
|
536
|
+
return 1
|
|
537
|
+
|
|
538
|
+
command = [*(str(cmd) for cmd in self.command), '--build', str(self.build_dir), '--target', *self.build_targets]
|
|
539
|
+
log.debug('Building CMake target(s): %s', ', '.join(self.build_targets))
|
|
540
|
+
result = _call_process.call_process(command)
|
|
541
|
+
|
|
542
|
+
if result.returncode != 0:
|
|
543
|
+
result.stdout = f'Running CMake with: {command}\n{result.stdout}\n'
|
|
544
|
+
if self.CODEGEN_TARGET in self.build_targets:
|
|
545
|
+
result.stderr += (
|
|
546
|
+
f'\nNB: the `{self.CODEGEN_TARGET}` target is only generated by CMake if policy CMP0171 is set to '
|
|
547
|
+
'NEW in your project, e.g. by using cmake_minimum_required(VERSION 3.31) or newer.\n\n'
|
|
548
|
+
)
|
|
549
|
+
result.to_stdout_and_stderr()
|
|
550
|
+
|
|
551
|
+
return result.returncode
|
|
552
|
+
|
|
553
|
+
def _call_cmake(self, extra_args=None):
|
|
554
|
+
command = [str(cmd) for cmd in self.command]
|
|
555
|
+
if extra_args is None:
|
|
556
|
+
extra_args = []
|
|
557
|
+
|
|
558
|
+
result = _call_process.call_process(
|
|
559
|
+
[*command, str(self.source_dir), *self.cmake_args, *extra_args],
|
|
560
|
+
cwd=str(self.build_dir),
|
|
561
|
+
)
|
|
562
|
+
result.stdout = '\n'.join(
|
|
563
|
+
[
|
|
564
|
+
f'Running CMake with: {[*command, str(self.source_dir), *self.cmake_args]}',
|
|
565
|
+
f' from within {self.build_dir}',
|
|
566
|
+
result.stdout,
|
|
567
|
+
'',
|
|
568
|
+
]
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
return result
|
|
572
|
+
|
|
573
|
+
def _configure(self, lock_files, clean_build):
|
|
574
|
+
"""Run a CMake configure step."""
|
|
575
|
+
self.build_dir.mkdir(exist_ok=True)
|
|
576
|
+
|
|
577
|
+
if clean_build:
|
|
578
|
+
for path in self.build_dir.iterdir():
|
|
579
|
+
if path.is_dir():
|
|
580
|
+
shutil.rmtree(path)
|
|
581
|
+
elif path not in lock_files:
|
|
582
|
+
path.unlink()
|
|
583
|
+
|
|
584
|
+
extra_args = []
|
|
585
|
+
if self.cmake_trace_log:
|
|
586
|
+
extra_args.extend(
|
|
587
|
+
[
|
|
588
|
+
'--trace-expand',
|
|
589
|
+
'--trace-format=json-v1',
|
|
590
|
+
f'--trace-redirect={self.cmake_trace_log}',
|
|
591
|
+
]
|
|
592
|
+
)
|
|
593
|
+
|
|
594
|
+
result = self._call_cmake(extra_args=extra_args)
|
|
595
|
+
|
|
596
|
+
compiledb = Path(self.build_dir, 'compile_commands.json')
|
|
597
|
+
if not compiledb.exists():
|
|
598
|
+
result.returncode = 1
|
|
599
|
+
result.stderr += f'\nUnable to locate {compiledb}\n\n'
|
|
600
|
+
|
|
601
|
+
if result.returncode != 0:
|
|
602
|
+
result.to_stdout_and_stderr()
|
|
603
|
+
|
|
604
|
+
return result.returncode
|
|
605
|
+
|
|
606
|
+
def _parse_cmake_trace_log(self):
|
|
607
|
+
log.info('attempting to parse CMake trace log to detect calls to configure_file()')
|
|
608
|
+
self.cmake_configured_files = []
|
|
609
|
+
|
|
610
|
+
if not self.cmake_trace_log:
|
|
611
|
+
log.info('no trace log provided, aborting.')
|
|
612
|
+
return
|
|
613
|
+
|
|
614
|
+
result = self._call_cmake(extra_args=['-N', '-LA'])
|
|
615
|
+
if result.returncode != 0:
|
|
616
|
+
log.error('failed to retrieve CMake cache variables')
|
|
617
|
+
return
|
|
618
|
+
|
|
619
|
+
cmake_cache_variables = {}
|
|
620
|
+
for line in result.stdout.splitlines():
|
|
621
|
+
cmake_var = re.match(r'^(\w+):(BOOL|FILEPATH|PATH|STRING|INTERNAL)=(.*)$', line)
|
|
622
|
+
if cmake_var:
|
|
623
|
+
cmake_cache_variables[cmake_var.group(1)] = cmake_var.group(3)
|
|
624
|
+
|
|
625
|
+
# ------------------------------
|
|
626
|
+
|
|
627
|
+
def _is_relevant_configure_file_call(json_data):
|
|
628
|
+
"""
|
|
629
|
+
Filter out the list of configure_file() calls.
|
|
630
|
+
|
|
631
|
+
The criteria are:
|
|
632
|
+
- Being a call to configure_file()
|
|
633
|
+
- Originating from a CMake file located inside the source directory
|
|
634
|
+
- Not originating from a CMake file located in FETCHCONTENT_BASE_DIR (if defined)
|
|
635
|
+
"""
|
|
636
|
+
if json_data.get('cmd', '') != 'configure_file':
|
|
637
|
+
return False
|
|
638
|
+
|
|
639
|
+
is_relevant = self.source_dir.as_posix() in json_data['file']
|
|
640
|
+
with contextlib.suppress(KeyError):
|
|
641
|
+
is_relevant &= cmake_cache_variables['FETCHCONTENT_BASE_DIR'] not in json_data['file']
|
|
642
|
+
return is_relevant
|
|
643
|
+
|
|
644
|
+
with self.cmake_trace_log.open('r') as fd:
|
|
645
|
+
configure_file_calls = [json.loads(line) for line in fd.readlines()]
|
|
646
|
+
|
|
647
|
+
for configure_file_call in (data for data in configure_file_calls if _is_relevant_configure_file_call(data)):
|
|
648
|
+
input_file, configured_file = (Path(arg) for arg in configure_file_call['args'][:2])
|
|
649
|
+
if not configured_file.is_absolute():
|
|
650
|
+
configured_file = self.build_dir / configured_file
|
|
651
|
+
log.debug(
|
|
652
|
+
'detected call to configure_file(%s %s [...])',
|
|
653
|
+
input_file,
|
|
654
|
+
configured_file,
|
|
655
|
+
)
|
|
656
|
+
self.cmake_configured_files.append(str(configured_file))
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
# ==============================================================================
|