-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdo.py
More file actions
executable file
·1553 lines (1327 loc) · 57.7 KB
/
Copy pathdo.py
File metadata and controls
executable file
·1553 lines (1327 loc) · 57.7 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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
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
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
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
850
851
852
853
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import json
import os
import pathlib
import re
import shlex
import shutil
import stat
import subprocess
import tempfile
import sys
from datetime import datetime
WINDOWS_CRT_RUNTIME_LIBRARIES = (
"msvcp140.dll",
"msvcp140_atomic_wait.dll",
"vcruntime140.dll",
"vcruntime140_1.dll",
)
def repo_root() -> pathlib.Path:
return pathlib.Path(__file__).resolve().parent
def build_dir(root: pathlib.Path) -> pathlib.Path:
return root / "build"
def build_dirs(root: pathlib.Path) -> list[pathlib.Path]:
"""Return repository-root build trees owned by Draxul's build workflows."""
candidates = [build_dir(root), *sorted(root.glob("build-*"))]
return [path for path in candidates if path.is_dir() and not path.is_symlink()]
def _remove_tree(path: pathlib.Path) -> None:
def remove_readonly(function, failed_path, _error_info):
os.chmod(failed_path, stat.S_IWRITE)
function(failed_path)
shutil.rmtree(path, onerror=remove_readonly)
def draxul_exe(bd: pathlib.Path, config: str) -> pathlib.Path:
"""Return the expected executable path for a given build dir and config."""
if sys.platform.startswith("win"):
config_exe = bd / config / "draxul.exe"
if config_exe.exists():
return config_exe
return bd / "draxul.exe"
bundle_exe = bd / "draxul.app" / "Contents" / "MacOS" / "draxul"
if bundle_exe.exists():
return bundle_exe
return bd / "draxul"
def draxul_path(root: pathlib.Path) -> pathlib.Path:
"""Legacy helper — probe common locations for the executable."""
if sys.platform.startswith("win"):
release = build_dir(root) / "Release" / "draxul.exe"
if release.exists():
return release
debug = build_dir(root) / "Debug" / "draxul.exe"
if debug.exists():
return debug
return release
bundle_exe = build_dir(root) / "draxul.app" / "Contents" / "MacOS" / "draxul"
if bundle_exe.exists():
return bundle_exe
return build_dir(root) / "draxul"
# ---------------------------------------------------------------------------
# Build helpers for the `run` command
# ---------------------------------------------------------------------------
_VSDEVCMD_SEARCH_PATHS = [
r"C:\Program Files\Microsoft Visual Studio\2022\Preview\Common7\Tools\VsDevCmd.bat",
r"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\VsDevCmd.bat",
r"C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\Tools\VsDevCmd.bat",
r"C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\Tools\VsDevCmd.bat",
r"C:\Program Files (x86)\Microsoft Visual Studio\2022\Preview\Common7\Tools\VsDevCmd.bat",
r"C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\Common7\Tools\VsDevCmd.bat",
r"C:\Program Files (x86)\Microsoft Visual Studio\2022\Professional\Common7\Tools\VsDevCmd.bat",
r"C:\Program Files (x86)\Microsoft Visual Studio\2022\Enterprise\Common7\Tools\VsDevCmd.bat",
]
def _capture_msvc_env(bat_path: str, bat_args: list[str]) -> dict[str, str] | None:
"""Run a VS env-setup .bat file and capture the resulting environment.
Uses a temporary batch file to avoid quoting issues when subprocess
launches cmd.exe from Git Bash or other non-cmd shells.
"""
import tempfile
args_str = " ".join(bat_args)
bat_content = f'@call "{bat_path}" {args_str} >nul 2>&1\r\nset\r\n'
tmp_bat = os.path.join(tempfile.gettempdir(), "_draxul_env.bat")
try:
with open(tmp_bat, "wb") as f:
f.write(bat_content.encode("ascii"))
result = subprocess.run(
["cmd", "/c", tmp_bat],
capture_output=True, text=True, check=False,
encoding="utf-8", errors="replace",
)
finally:
if os.path.isfile(tmp_bat):
os.unlink(tmp_bat)
if result.returncode != 0:
return None
env: dict[str, str] = {}
for line in result.stdout.splitlines():
if "=" in line:
k, _, v = line.partition("=")
env[k] = v
if not env:
return None
# Verify that cl.exe is actually on the resulting PATH.
path_val = env.get("Path", env.get("PATH", ""))
for d in path_val.split(";"):
if os.path.isfile(os.path.join(d, "cl.exe")):
return env
return None
def _ensure_msvc_env() -> dict[str, str]:
"""If `cl.exe` is not on PATH, find VsDevCmd.bat and capture its env."""
if shutil.which("cl"):
return dict(os.environ)
for p in _VSDEVCMD_SEARCH_PATHS:
if not os.path.isfile(p):
continue
env = _capture_msvc_env(p, ["-arch=x64", "-host_arch=x64"])
if env:
return env
# Also try vcvarsall.bat (more reliable when vswhere is missing).
for p in _VSDEVCMD_SEARCH_PATHS:
vcvars = pathlib.Path(p).parents[2] / "VC" / "Auxiliary" / "Build" / "vcvarsall.bat"
if not vcvars.is_file():
continue
env = _capture_msvc_env(str(vcvars), ["x64"])
if env:
return env
print("\nFailed to initialise the MSVC toolchain for Ninja builds.")
print("Use --vs to fall back to the Visual Studio generator.")
sys.exit(1)
def _cache_build_type(cache_file: pathlib.Path) -> str | None:
"""Read CMAKE_BUILD_TYPE from an existing CMakeCache.txt."""
if not cache_file.exists():
return None
for line in cache_file.read_text().splitlines():
if line.startswith("CMAKE_BUILD_TYPE:STRING="):
return line.split("=", 1)[1]
return None
def _cache_value(cache_file: pathlib.Path, key: str) -> str | None:
"""Read a typed CMake cache value by name."""
if not cache_file.exists():
return None
prefix = f"{key}:"
for line in cache_file.read_text().splitlines():
if line.startswith(prefix):
return line.split("=", 1)[1]
return None
def _missing_generated_build_file(
cache_file: pathlib.Path, bd: pathlib.Path, config: str,
) -> pathlib.Path | None:
"""Return a missing generated build-system file, if the cache is incomplete."""
generator = _cache_value(cache_file, "CMAKE_GENERATOR")
if generator is None:
return None
if generator == "Ninja Multi-Config":
build_file = bd / "build.ninja"
if not build_file.exists():
return build_file
config_build_file = bd / f"build-{config}.ninja"
if not config_build_file.exists():
return config_build_file
return None
if generator == "Ninja":
build_file = bd / "build.ninja"
return None if build_file.exists() else build_file
if generator.startswith("Visual Studio"):
solution_file = bd / "draxul.sln"
return None if solution_file.exists() else solution_file
if generator.endswith("Makefiles"):
makefile = bd / "Makefile"
return None if makefile.exists() else makefile
return None
def _check_metal_toolchain() -> None:
if sys.platform != "darwin":
return
if shutil.which("xcrun") is None:
print("Missing xcrun. Install Xcode Command Line Tools.", file=sys.stderr)
sys.exit(1)
r = subprocess.run(["xcrun", "--find", "metal"], capture_output=True, check=False)
if r.returncode != 0:
print("Missing Metal compiler. Install Xcode Command Line Tools and the Metal toolchain.", file=sys.stderr)
print("Suggested fix: xcodebuild -downloadComponent MetalToolchain", file=sys.stderr)
sys.exit(1)
r = subprocess.run(["xcrun", "-sdk", "macosx", "metal", "-v"], capture_output=True, check=False)
if r.returncode != 0:
print("The Metal compiler is present but not runnable because the Metal Toolchain is missing.", file=sys.stderr)
print("Suggested fix: xcodebuild -downloadComponent MetalToolchain", file=sys.stderr)
sys.exit(1)
def _parse_build_args(args: list[str]) -> tuple[str, bool, str, bool, list[str]]:
"""Parse shared build/run arguments.
Returns (mode, force_reconfigure, build_system, use_console, app_args).
"""
mode = "debug"
force_reconfigure = False
build_system = "ninja"
use_console = False
app_args: list[str] = []
i = 0
while i < len(args):
a = args[i]
mode_arg = a.lower()
if mode_arg in ("debug", "release", "relwithdebinfo"):
mode = mode_arg
elif a == "--reconfigure":
force_reconfigure = True
elif a == "--vs":
build_system = "vs"
elif a == "--ninja":
build_system = "ninja"
elif a == "--console":
use_console = True
app_args.append(a)
elif a == "--":
app_args.extend(args[i + 1:])
break
else:
app_args.append(a)
i += 1
return mode, force_reconfigure, build_system, use_console, app_args
def _normalize_megacity_parser(parser: str) -> str:
parser = parser.lower().replace("-", "_")
if parser in ("treesitter", "tree_sitter", "treesitter_db", "tree_sitter_db"):
return "treesitter_db"
raise ValueError("--parser must be one of: treesitter, treesitter_db")
def _has_megacity_host(app_args: list[str]) -> bool:
for i, arg in enumerate(app_args):
if arg == "--host" and i + 1 < len(app_args):
return app_args[i + 1].lower() == "megacity"
return False
def _consume_megacity_parser_args(app_args: list[str]) -> tuple[list[str], str | None]:
"""Consume do.py's MegaCity parser helper flag from app args."""
parser: str | None = None
stripped_args: list[str] = []
i = 0
while i < len(app_args):
arg = app_args[i]
if arg == "--parser":
if i + 1 >= len(app_args):
raise ValueError("--parser requires a value")
if parser is not None:
raise ValueError("--parser may be specified only once")
parser = _normalize_megacity_parser(app_args[i + 1])
i += 2
continue
stripped_args.append(arg)
i += 1
if parser is not None and not _has_megacity_host(stripped_args):
raise ValueError("--parser is only supported with --host megacity")
return stripped_args, parser
def _default_config_path() -> pathlib.Path:
if sys.platform.startswith("win"):
base = pathlib.Path(os.environ.get("APPDATA") or ".")
return base / "draxul" / "config.toml"
if sys.platform == "darwin":
base = pathlib.Path(os.environ.get("HOME") or ".")
return base / "Library" / "Application Support" / "draxul" / "config.toml"
xdg = os.environ.get("XDG_CONFIG_HOME")
if xdg:
base = pathlib.Path(xdg)
else:
base = pathlib.Path(os.environ.get("HOME") or ".") / ".config"
return base / "draxul" / "config.toml"
def _toml_string(value: str) -> str:
return json.dumps(value)
def _merge_key_value(lines: list[str], start: int, end: int, key: str, value: str, newline: str) -> None:
pattern = re.compile(rf"^(\s*){re.escape(key)}\s*=")
replacement = f"{key} = {_toml_string(value)}{newline}"
for index in range(start, end):
match = pattern.match(lines[index])
if match:
indent = match.group(1)
lines[index] = f"{indent}{replacement}"
return
insert_at = end
while insert_at > start and lines[insert_at - 1].strip() == "":
insert_at -= 1
lines.insert(insert_at, replacement)
def _table_end(lines: list[str], section_start: int) -> int:
for index in range(section_start + 1, len(lines)):
stripped = lines[index].strip()
if stripped.startswith("[") and stripped.endswith("]"):
return index
return len(lines)
def _remove_key_value(lines: list[str], start: int, end: int, key: str) -> int:
pattern = re.compile(rf"^\s*{re.escape(key)}\s*=")
index = start
while index < end:
if pattern.match(lines[index]):
del lines[index]
end -= 1
continue
index += 1
return end
def _merge_megacity_parser_config(text: str, parser: str) -> str:
parser = _normalize_megacity_parser(parser)
newline = "\r\n" if "\r\n" in text else "\n"
lines = text.splitlines(keepends=True)
section_start: int | None = None
section_end = len(lines)
for index, line in enumerate(lines):
if line.strip() == "[mega_city_code]":
section_start = index
break
if section_start is None:
prefix = "" if not text else newline
if text and not text.endswith(("\n", "\r")):
prefix = newline + prefix
merged = f"{text}{prefix}[mega_city_code]{newline}"
merged += f"code_source = {_toml_string(parser)}{newline}"
return merged
section_end = _table_end(lines, section_start)
_merge_key_value(lines, section_start + 1, section_end, "code_source", parser, newline)
section_end = _table_end(lines, section_start)
_remove_key_value(lines, section_start + 1, section_end, "graphify_graph_path")
return "".join(lines)
def _apply_megacity_parser_config(parser: str) -> pathlib.Path:
config_path = _default_config_path()
text = config_path.read_text(encoding="utf-8") if config_path.exists() else ""
merged = _merge_megacity_parser_config(text, parser)
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(merged, encoding="utf-8")
return config_path
def _parallel_jobs() -> str:
"""Bounded build parallelism. A bare `cmake --build --parallel` maps to an
unlimited `make -j` with the Makefiles generator; a job storm across large
third-party deps (e.g. Verovio's ~400 files) can swamp the machine."""
return str(os.cpu_count() or 8)
def _test_parallel_jobs() -> str:
"""Bound test concurrency while still running independent shards in parallel."""
return str(min(os.cpu_count() or 4, 4))
def _configure_and_build(
root: pathlib.Path, mode: str, force_reconfigure: bool, build_system: str,
targets: tuple[str, ...] = ("draxul",),
) -> tuple[int, pathlib.Path, str, dict[str, str] | None]:
"""Configure + build. Returns (rc, build_dir, config, env)."""
is_win = sys.platform.startswith("win")
is_mac = sys.platform.startswith("darwin")
if is_win:
if build_system == "ninja":
config = {
"debug": "Debug",
"release": "Release",
"relwithdebinfo": "RelWithDebInfo",
}[mode]
preset = f"win-ninja-{mode}"
bd = root / f"build-ninja-{mode}"
else:
config = {
"debug": "Debug",
"release": "Release",
"relwithdebinfo": "RelWithDebInfo",
}[mode]
preset = "default" if mode == "debug" else "release"
bd = root / "build"
elif is_mac:
if mode == "relwithdebinfo":
print("RelWithDebInfo is currently supported only on Windows in do.py. Use raw cmake if you need it on macOS.", file=sys.stderr)
return 1, root / "build", "RelWithDebInfo", None
config = "Debug" if mode == "debug" else "Release"
preset = f"mac-{mode}"
bd = root / "build"
else:
if mode == "relwithdebinfo":
print("RelWithDebInfo is currently supported only on Windows in do.py. Use raw cmake if you need it on this platform.", file=sys.stderr)
return 1, root / "build", "RelWithDebInfo", None
config = "Debug" if mode == "debug" else "Release"
preset = f"mac-{mode}"
bd = root / "build"
cache_file = bd / "CMakeCache.txt"
print(f"\n=== {config} / {build_system if is_win else 'make'} ===")
env: dict[str, str] | None = None
if is_win and build_system == "ninja":
env = _ensure_msvc_env()
if is_mac:
_check_metal_toolchain()
need_configure = force_reconfigure or not cache_file.exists()
if not need_configure:
cached = _cache_build_type(cache_file)
if cached and cached != config:
need_configure = True
if not need_configure:
missing_build_file = _missing_generated_build_file(cache_file, bd, config)
if missing_build_file is not None:
print(f"\n> CMake cache exists but generated build file is missing: {missing_build_file}")
need_configure = True
if need_configure:
rc = run(["cmake", "--preset", preset], root, env=env)
if rc != 0:
return rc, bd, config, env
else:
print(f"\n> using existing CMake cache: {cache_file}")
build_cmd = ["cmake", "--build", str(bd), "--config", config]
if targets:
build_cmd.extend(["--target", *targets])
build_cmd.extend(["--parallel", _parallel_jobs()])
rc = run(build_cmd, root, env=env)
return rc, bd, config, env
def cmd_build(root: pathlib.Path, args: list[str]) -> int:
"""Configure + build only (no run)."""
mode, force_reconfigure, build_system, _, _ = _parse_build_args(args)
rc, _, _, _ = _configure_and_build(root, mode, force_reconfigure, build_system)
return rc
_TEST_PRODUCT_SCOPES = ("megacity", "satview", "scoreview", "pcbview", "rezonality")
def _parse_test_args(args: list[str]) -> tuple[str, bool, str, bool, set[str], bool]:
verbose = False
product_scopes: set[str] = set()
all_tests = False
build_args: list[str] = []
for arg in args:
if arg == "--verbose":
verbose = True
elif arg == "--megacity":
product_scopes.add("megacity")
elif arg == "--satview":
product_scopes.add("satview")
elif arg == "--scoreview":
product_scopes.add("scoreview")
elif arg == "--pcbview":
product_scopes.add("pcbview")
elif arg == "--rezonality":
product_scopes.add("rezonality")
elif arg == "--products":
product_scopes.update(_TEST_PRODUCT_SCOPES)
elif arg == "--all":
all_tests = True
elif arg == "--unit":
# Compatibility with t.bat/scripts/run_tests.* terminology. `do test`
# is intentionally the focused unit path by default.
continue
else:
build_args.append(arg)
mode, force_reconfigure, build_system, use_console, extra_args = _parse_build_args(build_args)
if use_console or extra_args:
raise ValueError(
"test accepts [debug|release|relwithdebinfo] "
"[--reconfigure] [--vs|--ninja] [--verbose] "
"[--megacity|--satview|--scoreview|--pcbview|--rezonality|--products|--all]"
)
return mode, force_reconfigure, build_system, verbose, product_scopes, all_tests
def _test_scope_selection(
product_scopes: set[str], all_tests: bool,
) -> tuple[tuple[str, ...], list[str], str]:
if all_tests:
return ("draxul-tests",), ["--label-regex", "unit"], "all unit tests"
targets = ["draxul-tests-core"]
patterns = [
r"draxul-test-core-shard-[0-9]+",
r"draxul-test-app-shard-[0-9]+",
r"draxul-test-markdown-kanban-shard-[0-9]+",
r"draxul-do-py-tests",
r"draxul-review-skill-py-tests",
]
for scope in _TEST_PRODUCT_SCOPES:
if scope not in product_scopes:
continue
targets.append(f"draxul-tests-{scope}")
patterns.append(rf"draxul-test-{scope}-shard-[0-9]+")
if scope == "satview":
patterns.append(r"draxul-satview-catalog-py-tests")
elif scope == "scoreview":
patterns.append(r"draxul-test-scoreview-runtime-shard-[0-9]+")
elif scope == "pcbview":
patterns.append(r"draxul-render-pcbview-plugin")
elif scope == "rezonality":
patterns.append(r"draxul-rezonality-agent-layout")
patterns.append(r"draxul-rezonality-neovim")
patterns.append(r"draxul-render-rezonality-plugin")
patterns.append(r"draxul-render-rezonality-blend-waves")
patterns.append(r"draxul-render-rezonality-deferred-shading")
patterns.append(r"draxul-render-rezonality-protoplanetary-disc")
patterns.append(r"draxul-render-rezonality-pbr-robot")
patterns.append(r"draxul-render-rezonality-ray-tracer")
patterns.append(r"draxul-render-rezonality-audio-spectrum")
scope_label = "core" if not product_scopes else "core + " + ", ".join(
scope for scope in _TEST_PRODUCT_SCOPES if scope in product_scopes
)
regex = "^(" + "|".join(patterns) + ")$"
return tuple(targets), ["--tests-regex", regex], scope_label
def cmd_test(root: pathlib.Path, args: list[str]) -> int:
"""Build and run unit tests through the same cached path as build/run."""
try:
(
mode,
force_reconfigure,
build_system,
verbose,
product_scopes,
all_tests,
) = _parse_test_args(args)
except ValueError as error:
print(f"ERROR: {error}", file=sys.stderr)
return 2
targets, ctest_filter, scope_label = _test_scope_selection(
product_scopes, all_tests
)
print(f"\n> test scope: {scope_label}")
rc, bd, config, env = _configure_and_build(
root,
mode,
force_reconfigure,
build_system,
targets=targets,
)
if rc != 0:
return rc
command = [
"ctest",
"--test-dir", str(bd),
"--build-config", config,
"--parallel", _test_parallel_jobs(),
"--timeout", "120",
]
command.extend(ctest_filter)
command.append("--verbose" if verbose else "--output-on-failure")
return run(command, root, env=env)
def cmd_run(root: pathlib.Path, args: list[str]) -> int:
"""Full configure + build + run cycle (replaces r.bat / r.sh)."""
mode, force_reconfigure, build_system, use_console, app_args = _parse_build_args(args)
try:
app_args, megacity_parser = _consume_megacity_parser_args(app_args)
except ValueError as e:
print(f"ERROR: {e}", file=sys.stderr)
return 2
rc, bd, config, env = _configure_and_build(root, mode, force_reconfigure, build_system)
if rc != 0:
return rc
exe = draxul_exe(bd, config)
if not exe.exists():
print(f"\nMissing executable: {exe}")
return 1
if megacity_parser is not None:
config_path = _apply_megacity_parser_config(megacity_parser)
print(f"\n> megacity parser: {megacity_parser} ({config_path})")
is_win = sys.platform.startswith("win")
cmd: list[str] = [str(exe)] + app_args
if is_win and not use_console:
print(f"\n> start {' '.join(cmd)}")
proc = subprocess.run(["cmd", "/c", "start", ""] + cmd, cwd=root, check=False, env=env)
return proc.returncode
else:
return run(cmd, root, env=env)
def _deploy_platform_name(platform: str = sys.platform) -> str:
if platform.startswith("win"):
return "win"
if platform == "darwin":
return "mac"
raise RuntimeError("deploy is currently supported only on macOS and Windows")
def _deploy_date_label(now: datetime | None = None) -> str:
return (now or datetime.now()).strftime("%Y_%m_%d")
def _deploy_output_paths(
root: pathlib.Path,
date_label: str,
platform: str = sys.platform,
) -> tuple[pathlib.Path, pathlib.Path]:
platform_name = _deploy_platform_name(platform)
date_dir = root / "deploy" / date_label
platform_dir = date_dir / platform_name
archive_path = date_dir / f"draxul-{date_label}-{platform_name}.zip"
return platform_dir, archive_path
def _deploy_payload_source(bd: pathlib.Path, config: str, platform: str = sys.platform) -> pathlib.Path:
if platform.startswith("win"):
config_exe = bd / config / "draxul.exe"
return config_exe if config_exe.exists() else bd / "draxul.exe"
if platform == "darwin":
bundle = bd / "draxul.app"
if bundle.exists():
return bundle
return bd / "draxul"
raise RuntimeError("deploy is currently supported only on macOS and Windows")
def _parse_deploy_args(args: list[str]) -> tuple[bool, str]:
mode, force_reconfigure, build_system, _, app_args = _parse_build_args(args)
requested_modes = [arg.lower() for arg in args if arg.lower() in ("debug", "release", "relwithdebinfo")]
if app_args:
raise ValueError("deploy accepts build flags only: [release] [--reconfigure] [--vs|--ninja]")
if requested_modes and mode != "release":
raise ValueError("deploy always creates a release build; use `do deploy` or `do deploy release`")
return force_reconfigure, build_system
def _stage_deploy_payload(
source: pathlib.Path,
platform_dir: pathlib.Path,
archive_path: pathlib.Path,
windows_runtime_directory: pathlib.Path | None = None,
) -> None:
if platform_dir.exists():
_remove_tree(platform_dir)
platform_dir.mkdir(parents=True, exist_ok=True)
if source.is_dir() and source.suffix == ".app":
shutil.copytree(source, platform_dir / source.name)
elif source.suffix.lower() == ".exe":
shutil.copy2(source, platform_dir / source.name)
for directory_name in ("assets", "fonts", "shaders"):
runtime_directory = source.parent / directory_name
if runtime_directory.is_dir():
shutil.copytree(runtime_directory, platform_dir / directory_name)
for runtime_library in sorted(source.parent.glob("*.dll")):
shutil.copy2(runtime_library, platform_dir / runtime_library.name)
if windows_runtime_directory is None and sys.platform.startswith("win"):
system_root = os.environ.get("SystemRoot")
if system_root:
windows_runtime_directory = pathlib.Path(system_root) / "System32"
if windows_runtime_directory is not None:
for library_name in WINDOWS_CRT_RUNTIME_LIBRARIES:
destination = platform_dir / library_name
if destination.exists():
continue
runtime_library = windows_runtime_directory / library_name
if not runtime_library.is_file():
raise FileNotFoundError(f"Missing Windows runtime library: {runtime_library}")
shutil.copy2(runtime_library, destination)
elif source.is_dir():
for child in source.iterdir():
destination = platform_dir / child.name
if child.is_dir():
shutil.copytree(child, destination)
else:
shutil.copy2(child, destination)
else:
shutil.copy2(source, platform_dir / source.name)
if archive_path.exists():
archive_path.unlink()
archive_base = archive_path.with_suffix("")
shutil.make_archive(
str(archive_base),
"zip",
root_dir=platform_dir.parent,
base_dir=platform_dir.name,
)
def cmd_deploy(root: pathlib.Path, args: list[str]) -> int:
"""Build Release and write a compressed deploy package."""
try:
force_reconfigure, build_system = _parse_deploy_args(args)
except ValueError as error:
print(f"ERROR: {error}", file=sys.stderr)
return 2
rc, bd, config, _ = _configure_and_build(root, "release", force_reconfigure, build_system)
if rc != 0:
return rc
source = _deploy_payload_source(bd, config)
if not source.exists():
print(f"Missing deploy payload: {source}", file=sys.stderr)
return 1
date_label = _deploy_date_label()
platform_dir, archive_path = _deploy_output_paths(root, date_label)
try:
_stage_deploy_payload(source, platform_dir, archive_path)
except OSError as error:
print(f"Failed to stage deploy payload: {error}", file=sys.stderr)
return 1
print(f"\nDeploy folder: {platform_dir}")
print(f"Deploy archive: {archive_path}")
return 0
def scenario_path(root: pathlib.Path, name: str) -> pathlib.Path:
return root / "tests" / "render" / f"{name}.toml"
RENDER_SCENARIO_REQUIRED_FIELDS = {
"name",
"purpose",
"status",
"platforms",
"ctest",
"reference_required",
"renderall",
"blessall",
"compare_command",
"bless_command",
}
RENDER_SCENARIO_OPTIONAL_FIELDS = {
"requires_target",
"test_scope",
}
RENDER_SCENARIO_FIELDS = (
RENDER_SCENARIO_REQUIRED_FIELDS | RENDER_SCENARIO_OPTIONAL_FIELDS
)
def load_render_manifest(root: pathlib.Path, *, validate_files: bool = True) -> list[dict]:
manifest_path = root / "tests" / "render" / "manifest.json"
try:
document = json.loads(manifest_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise ValueError(f"invalid render manifest {manifest_path}: {exc}") from exc
if set(document) != {"version", "scenarios"} or document.get("version") != 1:
raise ValueError("render manifest must contain only version=1 and scenarios")
scenarios = document.get("scenarios")
if not isinstance(scenarios, list) or not scenarios:
raise ValueError("render manifest scenarios must be a non-empty list")
names: set[str] = set()
commands: set[str] = set()
for index, scenario in enumerate(scenarios):
if not isinstance(scenario, dict):
raise ValueError(f"render scenario #{index} must be an object")
unknown = set(scenario) - RENDER_SCENARIO_FIELDS
missing = RENDER_SCENARIO_REQUIRED_FIELDS - set(scenario)
if unknown or missing:
raise ValueError(
f"render scenario #{index} fields invalid; unknown={sorted(unknown)}, missing={sorted(missing)}"
)
name = scenario["name"]
if not isinstance(name, str) or not name:
raise ValueError(f"render scenario #{index} has an invalid name")
if name in names:
raise ValueError(f"duplicate render scenario: {name}")
names.add(name)
if scenario["status"] not in {"regression", "developer", "documentation"}:
raise ValueError(f"render scenario {name} has unknown status {scenario['status']!r}")
platforms = scenario["platforms"]
if not isinstance(platforms, list) or not platforms or set(platforms) - {"windows", "macos", "linux"}:
raise ValueError(f"render scenario {name} has invalid platforms")
for field in ("ctest", "reference_required", "renderall", "blessall"):
if not isinstance(scenario[field], bool):
raise ValueError(f"render scenario {name} field {field} must be boolean")
for field in ("purpose", "compare_command", "bless_command"):
if not isinstance(scenario[field], str):
raise ValueError(f"render scenario {name} field {field} must be a string")
for field in RENDER_SCENARIO_OPTIONAL_FIELDS:
if field in scenario and (
not isinstance(scenario[field], str) or not scenario[field]
):
raise ValueError(
f"render scenario {name} field {field} must be a non-empty string"
)
if scenario["ctest"] and not scenario["reference_required"]:
raise ValueError(f"CTest render scenario {name} must require references")
if scenario["renderall"] != scenario["ctest"]:
raise ValueError(f"renderall and CTest inventory differ for {name}")
if scenario["blessall"] and not scenario["reference_required"]:
raise ValueError(f"blessall scenario {name} must require references")
for field in ("compare_command", "bless_command"):
command = scenario[field]
if command:
if command in commands:
raise ValueError(f"duplicate render command: {command}")
commands.add(command)
if validate_files:
render_dir = root / "tests" / "render"
toml_names = {path.stem for path in render_dir.glob("*.toml")}
missing_toml = names - toml_names
orphan_toml = toml_names - names
if missing_toml or orphan_toml:
raise ValueError(
f"render TOML inventory mismatch; missing={sorted(missing_toml)}, orphaned={sorted(orphan_toml)}"
)
required_references = {
f"{scenario['name']}.{platform}.bmp"
for scenario in scenarios
if scenario["reference_required"]
for platform in scenario["platforms"]
}
reference_dir = render_dir / "reference"
actual_references = {path.name for path in reference_dir.glob("*.bmp")}
missing_references = required_references - actual_references
declared_reference_prefixes = {f"{name}." for name in names}
orphan_references = {
reference
for reference in actual_references
if not any(reference.startswith(prefix) for prefix in declared_reference_prefixes)
}
if missing_references or orphan_references:
raise ValueError(
"render reference inventory mismatch; "
f"missing={sorted(missing_references)}, orphaned={sorted(orphan_references)}"
)
return scenarios
def render_command_map(root: pathlib.Path) -> dict[str, tuple[str, bool]]:
result: dict[str, tuple[str, bool]] = {}
for scenario in load_render_manifest(root):
if scenario["compare_command"]:
result[scenario["compare_command"]] = (scenario["name"], False)
if scenario["bless_command"]:
result[scenario["bless_command"]] = (scenario["name"], True)
return result
def render_scenario_names(root: pathlib.Path, flag: str) -> list[str]:
return [scenario["name"] for scenario in load_render_manifest(root) if scenario[flag]]
def platform_suffix() -> str:
if sys.platform.startswith("win"):
return "windows"
if sys.platform.startswith("darwin"):
return "macos"
return "linux"
def print_render_report(root: pathlib.Path, scenario_name: str) -> None:
report_path = root / "tests" / "render" / "out" / f"{scenario_name}.{platform_suffix()}.report.json"
if not report_path.exists():
print(f" [no report found: {report_path}]")
return
try:
data = json.loads(report_path.read_text())
except Exception as e:
print(f" [failed to read report: {e}]")
return
if "error" in data:
print(f" [{scenario_name}] ERROR: {data['error']}")
return
if "changed_pixels_pct" in data:
passed = data.get("passed", False)
label = "PASS" if passed else "FAIL"
print(
f" [{scenario_name}] diff: {data['changed_pixels_pct']:.4f}% changed pixels"
f" ({data['changed_pixels']}/{data['width'] * data['height']})"
f", max_channel_delta={data['max_channel_diff']}"
f", mean_abs={data['mean_abs_channel_diff']:.4f}"
f" [{label}]"
)
elif data.get("blessed"):
print(f" [{scenario_name}] blessed ({data['width']}x{data['height']})")
def run(command: list[str], cwd: pathlib.Path, *, env: dict[str, str] | None = None) -> int:
print("> " + " ".join(command))
completed = subprocess.run(command, cwd=cwd, check=False, env=env)
return completed.returncode
def _selected_build_context(
root: pathlib.Path, mode: str, build_system: str,
) -> tuple[pathlib.Path, str, dict[str, str] | None]:
if sys.platform.startswith("win"):
config = {
"debug": "Debug",
"release": "Release",
"relwithdebinfo": "RelWithDebInfo",
}[mode]
if build_system == "ninja":
return root / f"build-ninja-{mode}", config, _ensure_msvc_env()
return root / "build", config, None
if mode == "relwithdebinfo":
raise ValueError("RelWithDebInfo is currently supported only on Windows in do.py")
return root / "build", "Debug" if mode == "debug" else "Release", None
def build_shortcut_exe(
root: pathlib.Path,
mode: str = "debug",
force_reconfigure: bool = False,
build_system: str = "ninja",
skip_build: bool = False,
) -> tuple[int, pathlib.Path | None, dict[str, str] | None]:
"""Resolve the app for smoke/render shortcuts through the selected pipeline."""
if skip_build:
try:
bd, config, env = _selected_build_context(root, mode, build_system)
except ValueError as error:
print(f"ERROR: {error}", file=sys.stderr)
return 2, None, None
cache_file = bd / "CMakeCache.txt"
if not cache_file.exists():
print(f"\nMissing CMake cache: {cache_file}")
return 1, None, env
cached = _cache_build_type(cache_file)
if cached and cached != config:
print(f"\nBuild cache is {cached}, not requested {config}: {cache_file}")
return 1, None, env
else:
rc, bd, config, env = _configure_and_build(
root, mode, force_reconfigure, build_system
)
if rc != 0:
return rc, None, env
exe = draxul_exe(bd, config)
if not exe.exists():
print(f"\nMissing executable: {exe}")