forked from SharonIV0x86/CinderPeak
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
executable file
·491 lines (387 loc) · 17.5 KB
/
Copy pathbuild.py
File metadata and controls
executable file
·491 lines (387 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
#!/usr/bin/env python3
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, REMAINDER
from pathlib import Path
import platform
from subprocess import Popen, PIPE
import sys
from typing import List, Any, Optional, Tuple
from shutil import which
import os
class Config:
DEFAULT_BUILD_DIR = "build"
DEFAULT_BUILD_TYPE = "RelWithDebInfo"
DEFAULT_CMAKE = "cmake"
DEFAULT_CLANG_FORMAT = "clang-format"
DEFAULT_CLANG_TIDY = "clang-tidy"
DEFAULT_RUN_CLANG_TIDY = "run-clang-tidy"
FLAG_MAP = {
"with_tests": ("-DBUILD_TESTS=ON",),
"with_examples": ("-DBUILD_EXAMPLES=ON",),
"sanitize": ("-DSANITIZE=ON",),
"coverage": ("-DBUILD_COVERAGE=ON",),
"pedantic_warnings": ("-DPEDANTIC_WARNINGS=ON",),
"no_warnings": ("-DPEDANTIC_WARNINGS=OFF",),
}
def handle_build_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except KeyboardInterrupt:
print("\n\nBuild interrupted by user.", file=sys.stderr)
sys.exit(130)
except Exception as e:
print(f"\nError: {e}", file=sys.stderr)
sys.exit(1)
return wrapper
def run(*args: str, msg: Optional[str] = None, verbose: bool = False, stream: bool = True, **kwargs: Any) -> Popen:
sys.stdout.flush()
if verbose:
print(f"$ {' '.join(args)}")
if stream and 'stdout' not in kwargs:
kwargs['stdout'] = sys.stdout
kwargs['stderr'] = sys.stderr
p = Popen(args, **kwargs)
code = p.wait()
if code != 0:
err = f"\nfailed to run: {' '.join(args)}\nexit with code: {code}\n"
if msg:
err += f"error message: {msg}\n"
raise RuntimeError(err)
return p
def run_pipe(*args: str, msg: Optional[str] = None, verbose: bool = False, **kwargs: Any):
p = run(*args, msg=msg, verbose=verbose, stream=False, stdout=PIPE, universal_newlines=True, **kwargs)
return p.stdout
def find_command(command: str, msg: Optional[str] = None) -> str:
cmd_path = which(command)
if cmd_path is None:
raise RuntimeError(msg or f"Command '{command}' not found in PATH")
return cmd_path
def detect_generator() -> Optional[str]:
if which("ninja"):
return "Ninja"
system = platform.system()
if system == "Windows" and which("msbuild"):
return None
elif system in ("Linux", "Darwin") and which("make"):
return "Unix Makefiles"
return None
@handle_build_errors
def configure(build_dir: str = None, build_type: str = None,
with_tests: bool = False, with_examples: bool = False,
sanitize: bool = False, coverage: bool = False,
pedantic_warnings: bool = True, no_warnings: bool = False,
generator: Optional[str] = None, toolchain: Optional[str] = None,
cmake_path: str = None, ninja: bool = False,
D: Optional[List[str]] = None, **kwargs: Any) -> None:
build_dir = build_dir or Config.DEFAULT_BUILD_DIR
build_type = build_type or Config.DEFAULT_BUILD_TYPE
cmake_path = cmake_path or Config.DEFAULT_CMAKE
basedir = Path(__file__).parent.absolute()
cmake = find_command(cmake_path, msg="CMake is required")
os.makedirs(build_dir, exist_ok=True)
cmake_options = [f"-DCMAKE_BUILD_TYPE={build_type}"]
if with_tests:
cmake_options.extend(FLAG_MAP["with_tests"])
if with_examples:
cmake_options.extend(FLAG_MAP["with_examples"])
if sanitize:
cmake_options.extend(FLAG_MAP["sanitize"])
if coverage:
cmake_options.extend(FLAG_MAP["coverage"])
# Enable comprehensive warnings by default unless explicitly disabled
if no_warnings:
cmake_options.extend(FLAG_MAP["no_warnings"])
elif pedantic_warnings:
cmake_options.extend(FLAG_MAP["pedantic_warnings"])
if ninja:
cmake_options.append("-GNinja")
elif generator:
cmake_options.append(f"-G{generator}")
else:
detected = detect_generator()
if detected:
print(f"Auto-detected generator: {detected}")
cmake_options.append(f"-G{detected}")
if toolchain:
cmake_options.append(f"-DCMAKE_TOOLCHAIN_FILE={toolchain}")
if D:
cmake_options.extend([f"-D{opt}" for opt in D])
run(cmake, str(basedir), *cmake_options, verbose=True, cwd=build_dir)
print(f"\nConfiguration complete. Build directory: {build_dir}")
@handle_build_errors
def build(build_dir: str = None, jobs: Optional[int] = None,
target: Optional[str] = None, cmake_path: str = None,
skip_build: bool = False, config: Optional[str] = None, **kwargs: Any) -> None:
if skip_build:
print("Skipping build as requested.")
return
build_dir = build_dir or Config.DEFAULT_BUILD_DIR
cmake_path = cmake_path or Config.DEFAULT_CMAKE
if not os.path.exists(build_dir):
raise RuntimeError(f"Build directory '{build_dir}' not found. Run configure first.")
cmake = find_command(cmake_path, msg="CMake is required")
options = ["--build", build_dir]
if config:
options.extend(["--config", config])
if jobs is not None:
options.extend(["-j", str(jobs)])
if target:
options.extend(["--target", target])
run(cmake, *options, verbose=True)
print("\nBuild complete.")
def detect_build_config(build_dir: str) -> Optional[str]:
build_path = Path(build_dir)
bin_dir = build_path / 'bin'
if bin_dir.exists():
for cfg in ['Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel']:
test_dirs = list(bin_dir.glob(f'*/{cfg}/*.exe')) + list(bin_dir.glob(f'*/*/{cfg}/*.exe'))
if test_dirs:
return cfg
cmake_cache = build_path / "CMakeCache.txt"
if cmake_cache.exists():
with open(cmake_cache, 'r') as f:
for line in f:
if line.startswith("CMAKE_BUILD_TYPE:"):
config = line.split('=')[1].strip()
if config:
return config
if platform.system() == "Windows":
return "Debug"
return None
@handle_build_errors
def test(build_dir: str = None, cpp: bool = False, all: bool = False,
config: Optional[str] = None, rest: Optional[List[str]] = None,
**kwargs: Any) -> None:
build_dir = build_dir or Config.DEFAULT_BUILD_DIR
if not os.path.exists(build_dir):
raise RuntimeError(f"Build directory '{build_dir}' not found.")
ctest = find_command("ctest", msg="CTest is required")
options = ["--test-dir", build_dir, "--verbose"]
if config is None:
config = detect_build_config(build_dir)
if config:
print(f"Auto-detected build configuration: {config}")
if config:
options.extend(["-C", config])
if rest:
options.extend(rest)
run(ctest, *options, verbose=True)
print("\nTests complete.")
@handle_build_errors
def clean(build_dir: str = None, **kwargs: Any) -> None:
import shutil
build_dir = build_dir or Config.DEFAULT_BUILD_DIR
if os.path.exists(build_dir):
print(f"Removing build directory: {build_dir}")
shutil.rmtree(build_dir)
print("Clean complete.")
else:
print(f"Build directory '{build_dir}' does not exist.")
@handle_build_errors
def format_code(clang_format_path: str = None, fix: bool = False, **kwargs: Any) -> None:
from glob import glob
clang_format_path = clang_format_path or Config.DEFAULT_CLANG_FORMAT
basedir = Path(__file__).parent.absolute()
command = find_command(clang_format_path, msg="clang-format is required")
sources = [
*glob(str(basedir / "src/**/*.hpp"), recursive=True),
*glob(str(basedir / "src/**/*.cpp"), recursive=True),
*glob(str(basedir / "tests/**/*.cpp"), recursive=True),
*glob(str(basedir / "examples/**/*.cpp"), recursive=True),
]
if not sources:
print("No source files found.")
return
options = ['-i'] if fix else ['--dry-run', '--Werror']
run(command, *options, *sources, verbose=True)
print("Format complete." if fix else "Format check complete.")
@handle_build_errors
def check(subcommand: str = None, **kwargs: Any) -> None:
if subcommand == "format":
format_code(fix=False, **kwargs)
elif subcommand == "tidy":
check_tidy(**kwargs)
else:
print("Usage: build.py check {format|tidy}")
@handle_build_errors
def check_tidy(build_dir: str = None, jobs: Optional[int] = None,
clang_tidy_path: str = None,
run_clang_tidy_path: str = None,
fix: bool = False, **kwargs: Any) -> None:
build_dir = build_dir or Config.DEFAULT_BUILD_DIR
clang_tidy_path = clang_tidy_path or Config.DEFAULT_CLANG_TIDY
run_clang_tidy_path = run_clang_tidy_path or Config.DEFAULT_RUN_CLANG_TIDY
tidy_command = find_command(clang_tidy_path, msg="clang-tidy is required")
compile_commands = Path(build_dir) / 'compile_commands.json'
if not compile_commands.exists():
raise RuntimeError(f"compile_commands.json not found in {build_dir}")
run_command = which(run_clang_tidy_path)
basedir = Path(__file__).parent.absolute()
if run_command:
options = ['-p', build_dir, '-clang-tidy-binary', tidy_command]
if jobs is not None:
options.append(f'-j{jobs}')
if fix:
options.append('-fix')
options.append('-header-filter=src/|tests/|examples/')
run(run_command, *options, 'src/', verbose=True, cwd=str(basedir))
else:
print(f"Warning: {run_clang_tidy_path} not found")
from glob import glob
sources = glob(str(basedir / "src/**/*.cpp"), recursive=True)
options = [f'-p={build_dir}']
if fix:
options.append('-fix')
run(tidy_command, *options, *sources, verbose=True)
print("Tidy check complete.")
@handle_build_errors
def prepare(**kwargs: Any) -> None:
basedir = Path(__file__).parent.absolute()
hooks_dir = basedir / "scripts"
git_hooks_dir = basedir / ".git" / "hooks"
if not git_hooks_dir.exists():
print("Warning: .git/hooks not found.")
return
if not hooks_dir.exists():
print(f"No hooks found in {hooks_dir}")
return
import filecmp
git_hooks_dir.mkdir(exist_ok=True)
for hook in hooks_dir.iterdir():
if hook.is_file():
dst = git_hooks_dir / hook.name
if dst.exists():
if filecmp.cmp(hook, dst, shallow=False):
print(f"{hook.name} already installed.")
continue
else:
if platform.system() == "Windows":
import shutil
shutil.copy2(hook, dst)
else:
dst.symlink_to(hook)
print(f"{hook.name} installed at {dst}.")
print("Development environment prepared.")
@handle_build_errors
def package(subcommand: str = None, release_version: str = None, **kwargs: Any) -> None:
if subcommand == "source":
if not release_version:
raise RuntimeError("--release-version is required")
git = find_command('git', msg='git is required')
folder = f'cinderpeak-{release_version}-src'
tarball = f'{folder}.tar.gz'
print(f"Creating source tarball: {tarball}")
run(git, 'archive', '--format=tar.gz', f'--output={tarball}',
f'--prefix={folder}/', 'HEAD', verbose=True)
print(f"Source package created: {tarball}")
else:
print("Usage: build.py package source --release-version VERSION")
@handle_build_errors
def all_command(build_dir: str = None, build_type: str = None,
with_tests: bool = False, with_examples: bool = False,
sanitize: bool = False, coverage: bool = False,
pedantic_warnings: bool = True, no_warnings: bool = False,
jobs: Optional[int] = None, skip_tests: bool = False,
config: Optional[str] = None, **kwargs: Any) -> None:
build_dir = build_dir or Config.DEFAULT_BUILD_DIR
build_type = build_type or Config.DEFAULT_BUILD_TYPE
print("Running complete build workflow...")
configure(build_dir=build_dir, build_type=build_type,
with_tests=with_tests, with_examples=with_examples,
sanitize=sanitize, coverage=coverage,
pedantic_warnings=pedantic_warnings, no_warnings=no_warnings, **kwargs)
build(build_dir=build_dir, jobs=jobs, config=config, **kwargs)
if with_tests and not skip_tests:
test(build_dir=build_dir, config=config, **kwargs)
print("\nWorkflow complete!")
if __name__ == '__main__':
parser = ArgumentParser(
description="CinderPeak Build Orchestrator",
formatter_class=ArgumentDefaultsHelpFormatter
)
subparsers = parser.add_subparsers(dest='command')
p = subparsers.add_parser('configure', help="Configure build system")
p.add_argument('build_dir', nargs='?', default='build')
p.add_argument('--build-type', default='RelWithDebInfo')
p.add_argument('--with-tests', action='store_true')
p.add_argument('--with-examples', action='store_true')
p.add_argument('--sanitize', action='store_true')
p.add_argument('--coverage', action='store_true')
p.add_argument('--pedantic-warnings', action='store_true', default=True,
help='Enable comprehensive compiler warnings (default: ON)')
p.add_argument('--no-warnings', action='store_true',
help='Disable comprehensive compiler warnings')
p.add_argument('--generator')
p.add_argument('--toolchain')
p.add_argument('--cmake-path', default='cmake')
p.add_argument('--ninja', action='store_true')
p.add_argument('-D', action='append', metavar='key=value')
p.set_defaults(func=configure)
p = subparsers.add_parser('build', help="Build project")
p.add_argument('build_dir', nargs='?', default='build')
p.add_argument('-j', '--jobs', type=int)
p.add_argument('--target')
p.add_argument('--config', help='Build configuration (Debug, Release, etc.)')
p.add_argument('--cmake-path', default='cmake')
p.add_argument('--skip-build', action='store_true')
p.set_defaults(func=build)
p = subparsers.add_parser('test', help="Run tests")
p.add_argument('build_dir', nargs='?', default='build')
p.add_argument('-C', '--config', help='Test configuration (Debug, Release, etc.)')
p.add_argument('--cpp', action='store_true')
p.add_argument('--all', action='store_true')
p.add_argument('rest', nargs=REMAINDER)
p.set_defaults(func=test)
p = subparsers.add_parser('clean', help="Clean build")
p.add_argument('build_dir', nargs='?', default='build')
p.set_defaults(func=clean)
p = subparsers.add_parser('format', help="Format code")
p.add_argument('--clang-format-path', default='clang-format')
p.add_argument('--fix', action='store_true')
p.set_defaults(func=format_code)
p = subparsers.add_parser('check', help="Check code")
p_sub = p.add_subparsers(dest='subcommand')
p_fmt = p_sub.add_parser('format')
p_fmt.add_argument('--clang-format-path', default='clang-format')
p_fmt.set_defaults(func=lambda **a: format_code(**a, fix=False))
p_tidy = p_sub.add_parser('tidy')
p_tidy.add_argument('build_dir', nargs='?', default='build')
p_tidy.add_argument('-j', '--jobs', type=int)
p_tidy.add_argument('--clang-tidy-path', default='clang-tidy')
p_tidy.add_argument('--run-clang-tidy-path', default='run-clang-tidy')
p_tidy.add_argument('--fix', action='store_true')
p_tidy.set_defaults(func=check_tidy)
p.set_defaults(func=check)
p = subparsers.add_parser('prepare', help="Setup dev environment")
p.set_defaults(func=prepare)
p = subparsers.add_parser('package', help="Package project")
p_sub = p.add_subparsers(dest='subcommand')
p_src = p_sub.add_parser('source')
p_src.add_argument('--release-version', required=True)
p_src.set_defaults(func=package)
p.set_defaults(func=package)
p = subparsers.add_parser('all', help="Run configure + build + test")
p.add_argument('build_dir', nargs='?', default=Config.DEFAULT_BUILD_DIR)
p.add_argument('--build-type', default=Config.DEFAULT_BUILD_TYPE)
p.add_argument('--with-tests', action='store_true')
p.add_argument('--with-examples', action='store_true')
p.add_argument('--sanitize', action='store_true')
p.add_argument('--coverage', action='store_true')
p.add_argument('--pedantic-warnings', action='store_true', default=True,
help='Enable comprehensive compiler warnings (default: ON)')
p.add_argument('--no-warnings', action='store_true',
help='Disable comprehensive compiler warnings')
p.add_argument('-j', '--jobs', type=int, help="Number of parallel build jobs")
p.add_argument('--config', help='Build/test configuration (Debug, Release, etc.)')
p.add_argument('--skip-tests', action='store_true', help="Skip running tests")
p.add_argument('--cmake-path', default=Config.DEFAULT_CMAKE)
p.add_argument('-D', action='append', metavar='key=value', help="CMake definitions")
p.set_defaults(func=all_command)
args = parser.parse_args()
if not hasattr(args, 'func'):
parser.print_help()
sys.exit(1)
arg_dict = dict(vars(args))
func = arg_dict.pop('func')
arg_dict.pop('command', None)
func(**arg_dict)