-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge.py
More file actions
582 lines (490 loc) · 17.4 KB
/
bridge.py
File metadata and controls
582 lines (490 loc) · 17.4 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
#!/usr/bin/env python3
"""
SafeSerial - Universal CLI (bridge.py)
A single entry point for all project tasks: building, testing, verifying, and visualizing.
Usage:
python bridge.py build # Build C++, Python, Node
python bridge.py test verify # Run reliability verification (defaults to C++ target)
python bridge.py test chaos # Run interactive chaos visualizer (Live UI)
python bridge.py test unit # Run C++ unit tests
python bridge.py viz # Generate charts from test data
python bridge.py clean # Clean all artifacts
# Advanced Verification
python scripts/verify_reliability.py --target node # Verify Node.js bindings specificially
"""
import argparse
import os
import re
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path
# --- Configuration ---
SCRIPT_DIR = Path(__file__).parent.resolve()
PROJECT_ROOT = SCRIPT_DIR
BUILD_DIR = PROJECT_ROOT / "build"
NODE_DIR = PROJECT_ROOT / "bindings" / "node"
PYTHON_BINDING_DIR = PROJECT_ROOT / "bindings" / "python"
SCRIPTS_DIR = PROJECT_ROOT / "scripts"
# --- Colors ---
GREEN = "\033[92m" if sys.platform != "win32" or os.environ.get("TERM") else ""
YELLOW = "\033[93m" if sys.platform != "win32" or os.environ.get("TERM") else ""
RED = "\033[91m" if sys.platform != "win32" or os.environ.get("TERM") else ""
BLUE = "\033[94m" if sys.platform != "win32" or os.environ.get("TERM") else ""
NC = "\033[0m" if sys.platform != "win32" or os.environ.get("TERM") else ""
def log(msg: str):
print(f"{GREEN}[BRIDGE]{NC} {msg}")
def warn(msg: str):
print(f"{YELLOW}[WARN]{NC} {msg}")
def error(msg: str):
print(f"{RED}[ERROR]{NC} {msg}")
sys.exit(1)
def info(msg: str):
print(f"{BLUE}[INFO]{NC} {msg}")
def get_cpu_count() -> int:
try:
return os.cpu_count() or 4
except:
return 4
def run(
cmd: list[str], cwd: Path = PROJECT_ROOT, check: bool = True, title: str = None
) -> bool:
"""Run a command with optional title logging."""
if title:
info(title)
cmd_str = " ".join(cmd)
# print(f"DEBUG: Executing '{cmd_str}' in {cwd}") # Verbose debug
try:
subprocess.run(cmd, cwd=cwd, check=check)
return True
except subprocess.CalledProcessError as e:
if check:
error(f"Command failed: {cmd_str}\n{e}")
return False
except FileNotFoundError:
warn(f"Command not found: {cmd[0]}")
return False
except KeyboardInterrupt:
print("\nInterrupted.")
sys.exit(130)
def uv_run(args: list[str], cwd: Path = PROJECT_ROOT):
"""Run a command using 'uv run' within the python binding project context."""
uv = shutil.which("uv")
if not uv:
error("'uv' is required but not found in PATH.")
cmd = [uv, "run", "--project", str(PYTHON_BINDING_DIR)] + args
run(cmd, cwd=cwd, check=True)
# --- Tasks ---
def task_build(args):
"""Build everything."""
log("Building C++ Library...")
BUILD_DIR.mkdir(exist_ok=True)
# C++ CMake
cmake_args = ["cmake", ".."]
sanitizers = os.environ.get("SAFESERIAL_SANITIZERS", "").strip()
if sanitizers:
cmake_args.append(f"-DSAFESERIAL_SANITIZERS={sanitizers}")
coverage = os.environ.get("SAFESERIAL_COVERAGE", "").strip()
if coverage:
cmake_args.append(f"-DSAFESERIAL_COVERAGE={coverage}")
fuzzing = os.environ.get("SAFESERIAL_ENABLE_FUZZING", "").strip()
if fuzzing:
cmake_args.append(f"-DSAFESERIAL_ENABLE_FUZZING={fuzzing}")
if not run(cmake_args, cwd=BUILD_DIR, title="Configuring CMake"):
error("CMake configure failed")
# C++ Build
if sys.platform == "win32":
run(
[
"cmake",
"--build",
".",
"--config",
"Release",
"-j",
str(get_cpu_count()),
],
cwd=BUILD_DIR,
title="Compiling C++",
)
else:
run(["make", f"-j{get_cpu_count()}"], cwd=BUILD_DIR, title="Compiling C++")
# Node Bindings
if NODE_DIR.exists() and (NODE_DIR / "package.json").exists():
log("Building Node.js Bindings...")
npm = "npm.cmd" if sys.platform == "win32" else "npm"
run(
[npm, "install"],
cwd=NODE_DIR,
check=False,
title="Installing Node Dependencies",
)
run(
[npm, "run", "build"],
cwd=NODE_DIR,
check=False,
title="Building Node Addon",
)
else:
warn("Node bindings skipped (not found)")
# Python Bindings
log("Building Python Environment...")
prep_sdist = PYTHON_BINDING_DIR / "scripts" / "prepare_sdist.py"
run(
[sys.executable, str(prep_sdist)],
cwd=PROJECT_ROOT,
title="Preparing Python sdist sources",
)
uv = shutil.which("uv")
if not uv:
error("'uv' is required but not found in PATH.")
run([uv, "sync"], cwd=PYTHON_BINDING_DIR, title="Syncing Python Environment")
log("Build Complete!")
def task_test(args):
"""Run tests."""
target = args.target
artifacts_dir = PROJECT_ROOT / "docs" / "traceability" / "artifacts" / "latest"
def run_logged(cmd: list[str], log_path: Path, cwd: Path, title: str, check: bool):
info(title)
log_path.parent.mkdir(parents=True, exist_ok=True)
with open(log_path, "w") as log_file:
start = datetime.utcnow().isoformat() + "Z"
log_file.write(f"=== START {start} ===\n")
try:
proc = subprocess.Popen(
cmd,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
assert proc.stdout is not None
for line in proc.stdout:
ts = datetime.utcnow().isoformat() + "Z"
log_file.write(f"[{ts}] {line}")
proc.wait()
end = datetime.utcnow().isoformat() + "Z"
log_file.write(f"=== END {end} (exit {proc.returncode}) ===\n")
if check and proc.returncode != 0:
error(f"Command failed: {' '.join(cmd)}")
return proc.returncode == 0
except subprocess.CalledProcessError as e:
if check:
error(f"Command failed: {' '.join(cmd)}\n{e}")
return False
except FileNotFoundError:
warn(f"Command not found: {cmd[0]}")
return False
except KeyboardInterrupt:
print("\nInterrupted.")
sys.exit(130)
# Unit Tests
if target == "unit" or target == "all":
log("=== Unit Tests ===")
artifacts_dir.mkdir(parents=True, exist_ok=True)
# 1. C++
ctest = shutil.which("ctest")
if ctest:
run_logged(
[ctest, "--output-on-failure"],
artifacts_dir / "ctest.log",
BUILD_DIR,
"C++ Core Tests",
True,
)
else:
warn("ctest not found")
# 2. Python
log("Python Tests...")
pytest_log = artifacts_dir / "pytest.log"
pytest_junit = artifacts_dir / "pytest-junit.xml"
uv_run(
[
"python",
"-m",
"pytest",
"--log-file",
str(pytest_log),
"--log-file-level",
"INFO",
"--log-format",
"%(asctime)s %(levelname)s %(name)s %(message)s",
"--log-date-format",
"%Y-%m-%dT%H:%M:%S",
"--junitxml",
str(pytest_junit),
],
cwd=PYTHON_BINDING_DIR,
)
# 3. Node.js
if NODE_DIR.exists():
log("Node.js Tests...")
npm = "npm.cmd" if sys.platform == "win32" else "npm"
run_logged(
[npm, "test"],
artifacts_dir / "node-test.log",
NODE_DIR,
"Node.js Tests",
False,
)
# Reliability/System Tests
if target == "verify" or target == "all":
print()
log("=== System Verification ===")
print("Running Reliability Verification Suite (ISO Claim)...")
script = SCRIPTS_DIR / "verify_reliability.py"
# Using uv with matplotlib for plotting
uv_cmd = ["--with", "matplotlib", "python", str(script)]
uv_run(uv_cmd, cwd=PROJECT_ROOT)
viz_report = (
PROJECT_ROOT
/ "docs"
/ "traceability"
/ "artifacts"
/ "latest"
/ "verify_reliability_report.md"
)
viz = SCRIPTS_DIR / "visualize_results.py"
uv_run(
["--with", "matplotlib", "python", str(viz), str(viz_report)],
cwd=PROJECT_ROOT,
)
diagram = SCRIPTS_DIR / "generate_diagram.py"
uv_run(["--with", "matplotlib", "python", str(diagram)], cwd=PROJECT_ROOT)
linker = SCRIPTS_DIR / "link_test_ids.py"
run(
[sys.executable, str(linker)],
cwd=PROJECT_ROOT,
title="Linking TestIDs",
)
traceability = SCRIPTS_DIR / "validate_traceability.py"
run(
[sys.executable, str(traceability)],
cwd=PROJECT_ROOT,
title="Validating Traceability",
)
artifacts = SCRIPTS_DIR / "collect_artifacts.py"
run(
[sys.executable, str(artifacts)],
cwd=PROJECT_ROOT,
title="Collecting Verification Artifacts",
)
if target == "chaos":
log("Launching Interactive Chaos Visualizer...")
script = SCRIPTS_DIR / "chaos_visual.py"
# Pass through any extra args to the visualizer
extra_args = args.extra_args if hasattr(args, "extra_args") else []
cmd = ["--with", "rich", "python", str(script)] + extra_args
uv_run(cmd, cwd=PROJECT_ROOT)
if target == "coverage":
log("=== Coverage ===")
run(["bash", str(SCRIPTS_DIR / "run_coverage.sh")], cwd=PROJECT_ROOT)
if target == "fuzz":
log("=== Fuzzing ===")
run(["bash", str(SCRIPTS_DIR / "run_fuzz.sh")], cwd=PROJECT_ROOT)
def task_viz(args):
"""Generate reports/charts."""
log("Running Visualization...")
script = SCRIPTS_DIR / "visualize_results.py"
report_file = (
PROJECT_ROOT
/ "docs"
/ "traceability"
/ "artifacts"
/ "latest"
/ "verify_reliability_report.md"
)
if not report_file.exists():
warn(
"No verify_reliability_report.md found. Run 'bridge.py test verify' first."
)
# We pass the log file path if needed, but the script defaults to test_report.md logic
# Actually the script takes the report file as arg 1
cmd = ["--with", "matplotlib", "python", str(script), str(report_file)]
uv_run(cmd, cwd=PROJECT_ROOT)
def task_clean(args):
"""Clean artifacts."""
log("Cleaning Project...")
dirs = [
BUILD_DIR,
NODE_DIR / "build",
NODE_DIR / "node_modules",
PROJECT_ROOT / ".pytest_cache",
PROJECT_ROOT / "__pycache__",
]
files = [
PROJECT_ROOT / "test_report.md",
PROJECT_ROOT / "combined.log",
PROJECT_ROOT / "chaos_monkey.log",
PROJECT_ROOT / "test_timeline.png",
PROJECT_ROOT / "reliability_plot.png",
PROJECT_ROOT / "docs" / "test_report.md",
PROJECT_ROOT / "docs" / "test_timeline.png",
PROJECT_ROOT / "docs" / "reliability_plot.png",
]
for d in dirs:
if d.exists():
shutil.rmtree(d, ignore_errors=True)
info(f"Removed {d}")
for f in files:
if f.exists():
f.unlink()
info(f"Removed {f}")
log("Clean Complete.")
def task_publish(args):
"""Publish packages to PyPI and NPM."""
target = args.target
uv = shutil.which("uv")
if not uv:
error("'uv' is required but not found in PATH.")
# Python
if target == "python" or target == "all":
log("Publishing Python Bindings...")
# Clean dist
dist_dir = PYTHON_BINDING_DIR / "dist"
if dist_dir.exists():
shutil.rmtree(dist_dir)
prep_sdist = PYTHON_BINDING_DIR / "scripts" / "prepare_sdist.py"
run(
[sys.executable, str(prep_sdist)],
cwd=PROJECT_ROOT,
title="Preparing Python sdist sources",
)
# Build sdist and wheel
# Note: 'uv build' must be run directly, not via 'uv run'
run([uv, "build"], cwd=PYTHON_BINDING_DIR, title="Building Python Package")
# Publish
log("Uploading to PyPI...")
# Note: Requires UV_PUBLISH_TOKEN or interactive login
run([uv, "publish"], cwd=PYTHON_BINDING_DIR, title="Publishing to PyPI")
# Node
if target == "node" or target == "all":
if NODE_DIR.exists():
log("Publishing Node.js Bindings...")
npm = "npm.cmd" if sys.platform == "win32" else "npm"
# Access public is usually required for scoped packages (@org/pkg)
# Requires npm login beforehand
run(
[npm, "publish", "--access", "public"],
cwd=NODE_DIR,
title="NPM Publish",
)
else:
warn("Node bindings not found, skipping publish")
log("Publish Complete!")
def task_bump(args):
"""Bump package versions (major/minor/patch)."""
part = args.part
def bump_version(version: str) -> str:
major, minor, patch = [int(x) for x in version.split(".")]
if part == "major":
major += 1
minor = 0
patch = 0
elif part == "minor":
minor += 1
patch = 0
else:
patch += 1
return f"{major}.{minor}.{patch}"
# Python version
pyproject = PYTHON_BINDING_DIR / "pyproject.toml"
py_text = pyproject.read_text()
py_match = re.search(r'^version\s*=\s*"([0-9]+\.[0-9]+\.[0-9]+)"', py_text, re.M)
if not py_match:
error("Could not find Python version in pyproject.toml")
py_version = py_match.group(1)
py_next = bump_version(py_version)
py_text = re.sub(
r'^version\s*=\s*"[0-9]+\.[0-9]+\.[0-9]+"',
f'version = "{py_next}"',
py_text,
flags=re.M,
)
pyproject.write_text(py_text)
# uv.lock is a resolver output; do not edit it here.
# Node version
package_json = NODE_DIR / "package.json"
package_text = package_json.read_text()
pkg_match = re.search(r'"version"\s*:\s*"([0-9]+\.[0-9]+\.[0-9]+)"', package_text)
if not pkg_match:
error("Could not find Node version in package.json")
node_version = pkg_match.group(1)
node_next = bump_version(node_version)
package_text = re.sub(
r'"version"\s*:\s*"[0-9]+\.[0-9]+\.[0-9]+"',
f'"version": "{node_next}"',
package_text,
count=1,
)
package_json.write_text(package_text)
package_lock = NODE_DIR / "package-lock.json"
lock_text = package_lock.read_text()
lock_text = re.sub(
r'"version"\s*:\s*"[0-9]+\.[0-9]+\.[0-9]+"',
f'"version": "{node_next}"',
lock_text,
count=2,
)
package_lock.write_text(lock_text)
log(f"Bumped Python to {py_next} and Node to {node_next}")
log("Run `uv lock` in bindings/python to refresh uv.lock if needed.")
# --- Main CLI ---
def main():
parser = argparse.ArgumentParser(
description="DataBridge Universal Tool (bridge.py)"
)
subparsers = parser.add_subparsers(dest="command", help="Command to execute")
# Build
parser_build = subparsers.add_parser(
"build", help="Build all components (C++, Node, Python env)"
)
# Test
parser_test = subparsers.add_parser("test", help="Run tests")
parser_test.add_argument(
"target",
choices=["unit", "verify", "chaos", "coverage", "fuzz", "all"],
default="all",
nargs="?",
help="Test target: unit (C++), verify (Automated Suite), chaos (Interactive UI)",
)
parser_test.add_argument(
"extra_args",
nargs=argparse.REMAINDER,
help="Arguments passed to underlying tool (e.g. for chaos)",
)
# Viz
parser_viz = subparsers.add_parser("viz", help="Generate result visualizations")
# Clean
parser_clean = subparsers.add_parser("clean", help="Clean build artifacts")
# Publish
parser_pub = subparsers.add_parser("publish", help="Publish packages to PyPI/NPM")
parser_pub.add_argument(
"target",
choices=["python", "node", "all"],
default="all",
nargs="?",
help="Target registry",
)
# Bump
parser_bump = subparsers.add_parser("bump", help="Bump package versions")
parser_bump.add_argument("part", choices=["major", "minor", "patch"])
args = parser.parse_args()
if args.command == "build":
task_build(args)
elif args.command == "test":
task_test(args)
elif args.command == "viz":
task_viz(args)
elif args.command == "clean":
task_clean(args)
elif args.command == "publish":
task_publish(args)
elif args.command == "bump":
task_bump(args)
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()