Repository navigation
Expand file tree
/
Copy pathbuild-support.py
More file actions
693 lines (623 loc) · 36 KB
/
Copy pathbuild-support.py
File metadata and controls
693 lines (623 loc) · 36 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
#!/usr/bin/env python3
"""Stable outputs and provenance for native build tools; compilation stays theirs."""
import argparse
import fnmatch
import hashlib
import json
import os
from pathlib import Path
import platform
import plistlib
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time
ROOT = Path(__file__).resolve().parent.parent
STATE = ROOT / "target/build-state"
DESKTOP_RUNTIME_CRATES = ("agent-runtime", "ai-provider", "application", "gateway")
MOBILE_BINDINGS = {
("ios", "iphonesimulator"): ("aarch64-apple-ios-sim", "remote"),
("ios", "iphoneos"): ("aarch64-apple-ios", "remote"),
("android", "default"): ("aarch64-linux-android", "remote"),
("android", "diagnostics"): ("aarch64-linux-android", "remote-diagnostics"),
}
sys.path.insert(0, str(Path(__file__).resolve().parent))
def digest(path):
value = hashlib.sha256()
with Path(path).open("rb") as source:
for part in iter(lambda: source.read(1024 * 1024), b""):
value.update(part)
return value.hexdigest()
def write(path, data):
path = Path(path)
if path.is_file() and path.read_bytes() == data:
return False
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix=".velune-write-", dir=path.parent)
try:
with os.fdopen(fd, "wb") as output:
output.write(data)
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
return True
def copy(source, destination):
source, destination = Path(source), Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
if source.is_symlink():
target = os.readlink(source)
if destination.is_symlink() and os.readlink(destination) == target:
return False
if destination.exists() and destination.is_dir() and not destination.is_symlink():
shutil.rmtree(destination)
else:
destination.unlink(missing_ok=True)
destination.symlink_to(target, target_is_directory=source.is_dir())
return True
if destination.is_symlink():
destination.unlink()
if destination.is_file() and source.stat().st_size == destination.stat().st_size and digest(source) == digest(destination):
# Copying executable permissions must not change the content timestamp.
os.chmod(destination, source.stat().st_mode & 0o777)
return False
fd, temporary = tempfile.mkstemp(prefix=".velune-copy-", dir=destination.parent)
os.close(fd)
try:
shutil.copy2(source, temporary)
os.replace(temporary, destination)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
return True
def sync(source, destination, prune=False, includes=()):
source, destination = Path(source), Path(destination)
if not source.is_dir():
raise ValueError(f"同步来源不是目录:{source}")
if destination.is_symlink():
raise ValueError(f"拒绝写入符号链接目录:{destination}")
destination.mkdir(parents=True, exist_ok=True)
selected = lambda name: not includes or any(fnmatch.fnmatch(name, pattern) for pattern in includes)
wanted = set()
for directory, folders, files in os.walk(source, followlinks=False):
base = Path(directory)
links = [name for name in folders if (base / name).is_symlink()]
folders[:] = [name for name in folders if name not in links]
for name in files + links:
relative = (base / name).relative_to(source)
if selected(relative.as_posix()):
wanted.add(relative.as_posix())
copy(base / name, destination / relative)
if prune:
for directory, folders, files in os.walk(destination, topdown=False, followlinks=False):
base = Path(directory)
for name in files + [name for name in folders if (base / name).is_symlink()]:
path = base / name
relative = path.relative_to(destination).as_posix()
if selected(relative) and relative not in wanted:
path.unlink()
for name in folders:
path = base / name
if not path.is_symlink() and not any(path.iterdir()):
path.rmdir()
def stage_runtime_scripts(destination, prune=False):
package = ROOT / "packages/agent-runtime"
names = (package / "resource-scripts.txt").read_text().splitlines()
destination = Path(destination)
for name in names:
copy(package / "resources" / name, destination / name)
if prune:
staged_names = {os.path.normcase(name) for name in names}
for old in destination.glob("*.mjs"):
if os.path.normcase(old.name) not in staged_names and (old.is_file() or old.is_symlink()):
old.unlink()
def ensure_bindgen():
subprocess.run(["cargo", "build", "--locked", "--target-dir", "target/build-tools", "-p", "velune-build-tools", "--bin", "velune-bindgen", "-j", os.environ.get("CARGO_BUILD_JOBS", "2")], cwd=ROOT, check=True)
return ROOT / "target/build-tools/debug" / ("velune-bindgen.exe" if os.name == "nt" else "velune-bindgen")
def binding_inputs(library, language, generator):
return {
"library": digest(library), "language": language,
"generator": digest(generator), "support": digest(__file__),
"config": {str(p.relative_to(ROOT)): digest(p) for p in sorted((ROOT / "packages").glob("*/uniffi.toml"))},
}
def generated_valid(directory, stamp):
return (bool(stamp.get("files"))
and all((directory / name).is_file() and digest(directory / name) == value for name, value in stamp["files"].items())
and all(Path(name).is_file() and digest(name) == value for name, value in stamp.get("artifacts", {}).items()))
def is_git_checkout():
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"], cwd=ROOT,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
)
return result.returncode == 0 and Path(result.stdout.strip()).resolve() == ROOT.resolve()
def load_stamp(directory):
try:
value = json.loads((directory / ".velune-bindings.json").read_text())
if not isinstance(value, dict) or not isinstance(value.get("files"), dict):
return {}
if any(Path(name).is_absolute() or ".." in Path(name).parts for name in value["files"]):
return {}
return value
except (OSError, ValueError, TypeError):
return {}
def bindings(args, verify=False):
directory, library = Path(args.out_dir).resolve(), Path(args.library).resolve()
old = load_stamp(directory)
if verify:
# Verification must not prepare or compile any tool, especially for
# --skip-native consumers. Its recorded producer remains explicit.
generator = Path(args.generator or old.get("generator_path", ""))
if not generator.is_file():
raise ValueError("绑定生成工具不可用,请先执行原生构建")
else:
generator = Path(args.generator).resolve() if args.generator else ensure_bindgen()
inputs = binding_inputs(library, args.language, generator)
artifacts = {str(Path(name).resolve()): digest(name) for name in (args.artifact or [])}
requested_pair_matches = args.artifact is None or old.get("artifacts", {}) == artifacts
if old.get("inputs") == inputs and requested_pair_matches and generated_valid(directory, old):
print(f"绑定保持:{directory}")
return
if verify:
raise ValueError("原生库/绑定不是当前配套产物,请先执行原生构建")
directory.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".velune-bindgen-", dir=directory.parent) as temporary:
command = [str(generator)]
if args.language != "cs":
command += ["generate", "--language", args.language]
command += ["--library", str(library), "--out-dir", temporary, "--no-format"]
subprocess.run(command, cwd=ROOT, check=True)
produced = {p.relative_to(temporary).as_posix(): digest(p) for p in Path(temporary).rglob("*") if p.is_file()}
if not produced:
raise ValueError("绑定生成器没有产生文件")
# Only the generator's own prior files are removed. Platform-owned
# module maps and licence files in the same directory are independent.
for name in old.get("files", {}):
if name not in produced:
(directory / name).unlink(missing_ok=True)
sync(temporary, directory)
stamp = {"inputs": inputs, "generator_path": str(generator.resolve()), "files": produced, "artifacts": artifacts}
write(directory / ".velune-bindings.json", (json.dumps(stamp, sort_keys=True, indent=2) + "\n").encode())
print(f"绑定已更新:{directory}")
def source_inputs(platform):
paths = ["Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "version.txt", "LICENSE", ".cargo", "packages", "tools", "third-party", f"app/{platform}",
"scripts/build-support.py", "scripts/build_lock.py", "scripts/android-licenses.py", "app/android/licenses", "scripts/version.py"]
if platform in ("macos", "windows"):
paths += ["THIRD_PARTY_NOTICES.md", "scripts/install-runtime-support.sh", "scripts/install-xurl.py"]
if platform == "macos":
paths = ["app/mac" if p == "app/macos" else p for p in paths]
paths += ["Package.swift", "Package.resolved", "assets", "scripts/build-macos.sh", "scripts/macos_identity.py", "scripts/render-app-icon.swift",
"scripts/install-hapi-tunwg.sh", "scripts/hapi-relay-supervisor.c", "scripts/install-xurl.sh"]
elif platform == "windows":
paths += ["global.json", ".gitattributes", "assets", "app/mac/Licenses", "scripts/build-windows.ps1", "scripts/render-windows-icon.ps1",
"scripts/dotnet-licenses.py", "scripts/install-xurl.ps1"]
elif platform == "ios":
paths += ["app/mac/Licenses", "app/mac/ClientTelemetry.swift", "app/mac/TelemetryExporters.swift", "app/mac/TelemetrySettings.swift", "app/mac/RemoteNetworkSettings.swift", "scripts/build-ios.sh", "scripts/build-ios-native.sh"]
elif platform == "android":
paths += ["scripts/build-android.sh", "scripts/build-android-native.sh"]
return paths
def is_build_input(platform, relative):
filename = relative.rsplit("/", 1)[-1]
if (filename in ("README.md", "AGENTS.md", "AGENTS.local.md")
or relative in ("app/windows/PARITY.md", "app/windows/TDD.md")):
return False
# Cargo still resolves workspace manifests, and bindgen fingerprints the
# workspace's UniFFI settings, even for a remote-only native consumer.
return (platform not in ("ios", "android") or filename in ("Cargo.toml", "uniffi.toml")
or not relative.startswith(tuple(f"packages/{crate}/" for crate in DESKTOP_RUNTIME_CRATES)))
def check_remote_bindings():
forbidden = {f"velune-{crate}" for crate in DESKTOP_RUNTIME_CRATES}
remote = ["-p", "velune-bindings", "--no-default-features", "--features"]
configurations = [
("remote host", [*remote, "remote"]),
("bindgen host", ["-p", "velune-build-tools"]),
*((f"{platform} {variant}", [*remote, features, "--target", target])
for (platform, variant), (target, features) in MOBILE_BINDINGS.items()),
]
for name, args in configurations:
tree = subprocess.check_output(["cargo", "tree", "--locked", "-e", "normal,build",
"--prefix", "none", *args], cwd=ROOT, text=True)
included = forbidden & {line.split()[0] for line in tree.splitlines() if line.strip()}
if included:
raise ValueError(f"{name} 引入了桌面运行时 crate:{', '.join(sorted(included))}")
print(f"{name}:通过桌面运行时依赖检查")
def source_snapshot(platform):
paths = source_inputs(platform)
if is_git_checkout():
output = subprocess.check_output(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", *paths], cwd=ROOT)
selected = [os.fsdecode(name) for name in sorted(set(output.split(b"\0")) - {b""})]
else:
paths += ["SOURCE-ARCHIVE.json", "android-sources", "swift-sources", "npm-sources"]
selected = []
for entry in paths:
path = ROOT / entry
if path.is_symlink() or path.is_file():
selected.append(entry)
elif path.is_dir():
for directory, folders, files in os.walk(path, followlinks=False):
base = Path(directory)
relative_base = base.relative_to(ROOT).as_posix()
prefix = "" if relative_base == "." else relative_base + "/"
folders[:] = [name for name in folders if not ignored_source_path(prefix + name)]
links = [name for name in folders if (base / name).is_symlink()]
folders[:] = [name for name in folders if name not in links]
selected.extend((base / name).relative_to(ROOT).as_posix() for name in files + links)
snapshot = {}
for key in sorted(set(selected)):
path = ROOT / key
if not is_build_input(platform, key):
continue
if path.is_symlink():
info = path.lstat()
snapshot[key] = [os.readlink(path), info.st_mtime_ns, info.st_ino]
elif path.is_file():
info = path.stat()
# Content alone misses a temporary edit restored during compile.
snapshot[key] = [digest(path), info.st_mtime_ns, info.st_size, info.st_ino]
else:
snapshot[key] = ["missing"]
# Provenance includes relevant effective compiler settings, never secrets.
for key in ("RUSTFLAGS", "CARGO_ENCODED_RUSTFLAGS", "RUSTC_WRAPPER", "RUSTC_WORKSPACE_WRAPPER", "CARGO_PROFILE_DEV_DEBUG", "CARGO_PROFILE_DEV_OPT_LEVEL", "CARGO_PROFILE_DEV_INCREMENTAL", "GO", "CC", "SDKROOT", "MACOSX_DEPLOYMENT_TARGET", "IPHONEOS_DEPLOYMENT_TARGET", "ANDROID_NDK_HOME", "VELUNE_RELAYKIT_CC", "VELUNE_BUILD_NUMBER", "VELUNE_REQUIRE_ANDROID_RELEASE_SIGNING"):
snapshot["env:" + key] = hashlib.sha256(os.environ.get(key, "").encode()).hexdigest()
signing_names = ("ANDROID_RELEASE_KEYSTORE_PATH", "ANDROID_RELEASE_STORE_PASSWORD", "ANDROID_RELEASE_KEY_ALIAS", "ANDROID_RELEASE_KEY_PASSWORD")
signing_active = all(os.environ.get(name) for name in signing_names)
snapshot["env:ANDROID_RELEASE_SIGNING_ACTIVE"] = hashlib.sha256(str(signing_active).lower().encode()).hexdigest()
return snapshot
SOURCE_OUTPUT_PATHS = (
".git", "target", ".build", ".swiftpm", "DerivedData", "dist",
"app/android/.gradle", "app/android/build", "app/android/.kotlin", "app/android/app/build",
"app/windows/bin", "app/windows/obj",
"app/ios/xcuserdata", "app/ios/Velune.xcodeproj/xcuserdata",
"app/ios/Velune.xcodeproj/project.xcworkspace/xcuserdata",
"packages/agent-runtime/runtime-support/node_modules",
)
def ignored_source_path(relative):
return any(relative == path or relative.startswith(path + "/") for path in SOURCE_OUTPUT_PATHS)
def archive_source_tree_digest(root=ROOT):
value = hashlib.sha256()
root = Path(root)
paths = []
for directory, folders, files in os.walk(root, topdown=True, followlinks=False):
base = Path(directory)
relative_base = base.relative_to(root).as_posix()
prefix = "" if relative_base == "." else relative_base + "/"
links = [name for name in folders if (base / name).is_symlink()]
folders[:] = [name for name in folders if not ignored_source_path(prefix + name) and name not in links]
paths.extend(base / name for name in links + folders + files)
for path in sorted(paths, key=lambda item: item.relative_to(root).as_posix()):
relative = path.relative_to(root).as_posix()
if relative == "SOURCE-ARCHIVE.json" or ignored_source_path(relative):
continue
value.update(relative.encode() + b"\0")
if path.is_symlink():
value.update(b"L" + os.readlink(path).encode())
elif path.is_file():
value.update(b"F")
with path.open("rb") as source:
for block in iter(lambda: source.read(1024 * 1024), b""):
value.update(block)
elif path.is_dir():
value.update(b"D")
return value.hexdigest()
def source_provenance():
if is_git_checkout():
return {
"source_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),
"dirty": bool(subprocess.check_output(["git", "status", "--porcelain"], cwd=ROOT, text=True)),
"source_tag": None,
}
try:
metadata = json.loads((ROOT / "SOURCE-ARCHIVE.json").read_text())
commit = metadata["source_commit"]
expected_tree = metadata["source_tree_sha256"]
except (OSError, KeyError, TypeError, json.JSONDecodeError) as error:
raise ValueError("source provenance requires a Git checkout or a complete SOURCE-ARCHIVE.json") from error
if not isinstance(commit, str) or not re.fullmatch(r"[0-9a-f]{40}", commit):
raise ValueError("SOURCE-ARCHIVE.json contains an invalid source_commit")
if not isinstance(expected_tree, str) or not re.fullmatch(r"[0-9a-f]{64}", expected_tree):
raise ValueError("SOURCE-ARCHIVE.json contains an invalid source_tree_sha256")
return {"source_commit": commit, "dirty": archive_source_tree_digest() != expected_tree, "source_tag": metadata.get("source_tag")}
def snapshot_identity(snapshot):
return hashlib.sha256(json.dumps(snapshot, sort_keys=True).encode()).hexdigest()
def source_identity(platform):
return snapshot_identity(source_snapshot(platform))
def artifact_identity(platform, profile, command, purpose="development"):
native_profile = "debug" if profile == "dev" else "release"
ios_sdk = "iphoneos" if "iphoneos" in command or os.environ.get("PLATFORM_NAME") == "iphoneos" else "iphonesimulator"
ios_target, _ = MOBILE_BINDINGS["ios", ios_sdk]
configuration = "Debug" if profile == "dev" else "Release"
if platform == "macos":
from macos_identity import app_bundle_path
bundle = app_bundle_path(ROOT, profile, purpose)
info_path = bundle / "Contents/Info.plist"
paths = [f"target/host-rust/{native_profile}/libvelune_bindings.dylib",
str(info_path.relative_to(ROOT)),
str((bundle / "Contents/Frameworks/libvelune_bindings.dylib").relative_to(ROOT)),
str((bundle / "Contents/Resources/build-manifest.json").relative_to(ROOT)),
str((bundle.parent / "binary-sha256.txt").relative_to(ROOT))]
if info_path.is_file():
executable = plistlib.loads(info_path.read_bytes()).get("CFBundleExecutable")
if isinstance(executable, str) and executable and Path(executable).name == executable:
paths.append(str((bundle / "Contents/MacOS" / executable).relative_to(ROOT)))
elif platform == "android":
apk, output_metadata = android_apk_output(profile)
paths = ["target/android-native/arm64-v8a/libvelune_bindings.so", str(apk.relative_to(ROOT)), str(output_metadata.relative_to(ROOT))]
elif platform == "windows":
app = "target/windows-dev/Velune" if profile == "dev" else "target/windows/Velune"
paths = [f"target/host-rust/{native_profile}/velune_bindings.dll",
f"{app}/Velune.exe", f"{app}/Velune.dll"]
else:
# Xcode Debug's launcher can be unchanged while the Swift library changes.
bundle = f"target/ios/Build/Products/{configuration}-{ios_sdk}/Velune.app"
paths = [f"target/cross-rust/{ios_target}/{native_profile}/libvelune_bindings.a",
f"{bundle}/Velune", f"{bundle}/Velune.debug.dylib"]
return {p: digest(ROOT / p) for p in paths if (ROOT / p).is_file()}
def verify_macos_signature(bundle):
result = subprocess.run(["/usr/bin/codesign", "--verify", "--deep", "--strict", str(bundle)],
capture_output=True, text=True)
if result.returncode:
raise ValueError(f"Mac 开发包签名校验失败:{result.stderr.strip()}")
def verify_macos_development_outputs(profile, receipt):
from macos_identity import app_bundle_path, identity, validate_bundle
bundle = app_bundle_path(ROOT, profile)
context = validate_bundle(bundle, purpose="development")
if context != identity(ROOT, "development")["context"]:
raise ValueError("Mac 开发包属于其他工作树")
artifacts = artifact_identity("macos", profile, receipt["command"])
executable = str((bundle / "Contents/MacOS" / context["executable"]).relative_to(ROOT))
bindings = str((bundle / "Contents/Frameworks/libvelune_bindings.dylib").relative_to(ROOT))
manifest_path = bundle / "Contents/Resources/build-manifest.json"
if not {executable, bindings, str(manifest_path.relative_to(ROOT))} <= artifacts.keys() or artifacts != receipt["artifacts"]:
raise ValueError("Mac 开发包产物与构建回执不符,请重新请求构建")
manifest = json.loads(manifest_path.read_text())
provenance = source_provenance()
if (manifest["execution_context"] != context or manifest["profile"] != profile
or manifest["purpose"] != "development"
or any(manifest[key] != provenance[key] for key in ("source_commit", "dirty"))):
raise ValueError("Mac 开发包的构建来源与当前工作树不符,请重新请求构建")
verify_macos_signature(bundle)
build = {
"app": str(bundle),
"executableSHA256": artifacts[executable],
"bindingsSHA256": artifacts[bindings],
}
return build, manifest
def verify_macos_build(profile):
from build_lock import FileLock
receipt_path = STATE / "results" / f"macos-{profile}-development-success.json"
with FileLock(STATE / "locks/macos.lock"):
source = source_identity("macos")
receipt = json.loads(receipt_path.read_text())
if receipt["exit_code"] != 0 or not receipt["current"] or receipt["input_after"] != source:
raise ValueError("Mac 构建回执与当前输入不符,请重新请求构建")
build, manifest = verify_macos_development_outputs(profile, receipt)
if source_identity("macos") != source:
raise ValueError("核验期间 Mac 源码已变化,请重新请求构建")
return dict(build, source=manifest["source_commit"], buildReceipt=str(receipt_path))
def android_apk_output(profile, root=None, require_signing=None):
if profile not in ("dev", "release"):
raise ValueError("Android APK output profile must be dev or release")
root = ROOT if root is None else Path(root)
if require_signing is None:
signing_names = ("ANDROID_RELEASE_KEYSTORE_PATH", "ANDROID_RELEASE_STORE_PASSWORD", "ANDROID_RELEASE_KEY_ALIAS", "ANDROID_RELEASE_KEY_PASSWORD")
release_signing = (os.environ.get("VELUNE_REQUIRE_ANDROID_RELEASE_SIGNING") == "true"
or all(os.environ.get(name) for name in signing_names))
else:
release_signing = require_signing
variant = "debug" if profile == "dev" else "release"
output_metadata = root / "app/android/app/build/outputs/apk" / variant / "output-metadata.json"
try:
metadata = json.loads(output_metadata.read_text())
elements = metadata["elements"]
if metadata.get("variantName") != variant or len(elements) != 1:
raise ValueError("Android output-metadata must describe exactly one expected variant output")
output_name = elements[0]["outputFile"]
except (OSError, KeyError, TypeError, json.JSONDecodeError) as error:
raise ValueError(f"missing or invalid Android output metadata: {output_metadata}") from error
expected_name = "app-debug.apk" if profile == "dev" else (
"app-release.apk" if release_signing else "app-release-unsigned.apk"
)
if output_name != expected_name:
raise ValueError(
f"Android output metadata names {output_name!r}, expected {expected_name!r} "
"for the active signing mode"
)
apk = output_metadata.parent / output_name
if not apk.is_file() or not apk.stat().st_size:
raise ValueError(f"Android output metadata points to a missing or empty APK: {apk}")
return apk, output_metadata
def macos_dev_inputs(args, environment):
"""Only reuse the standard local build with managed dependencies."""
if ((args.platform, args.profile, args.purpose) != ("macos", "dev", "development") or not args.reuse_macos_dev
or sys.platform != "darwin" or environment.get("CI")
or (environment.get("VELUNE_CODESIGN_IDENTITY") or "-") != "-"):
return None
overrides = ("CC", "CXX", "CPPFLAGS", "CFLAGS", "CXXFLAGS", "LDFLAGS", "GO", "SDKROOT",
"CPATH", "LIBRARY_PATH", "TOOLCHAINS", "SWIFT_EXEC", "MACOSX_DEPLOYMENT_TARGET",
"CARGO_ENCODED_RUSTFLAGS", "BASH_ENV")
prefixes = ("CARGO_BUILD_", "CARGO_PROFILE_", "CARGO_TARGET_", "CARGO_SOURCE_", "RUSTFLAGS",
"RUSTC", "CC_", "CXX_", "CGO_", "GOFLAGS", "GOROOT", "GOENV", "DYLD_", "SWIFTPM_")
if any(value and name != "CARGO_BUILD_JOBS" and (name in overrides or name.startswith(prefixes))
for name, value in environment.items()):
return None
try:
if not is_git_checkout():
return None
home = Path.home()
cargo_home = Path(environment.get("CARGO_HOME") or home / ".cargo")
if any((directory / name).exists() for directory in
[cargo_home, *(parent / ".cargo" for parent in ROOT.parents)] for name in ("config", "config.toml")):
return None
if (home / "Library/Application Support/go/env").exists():
return None
swift_configs = (ROOT / ".swiftpm/configuration", home / ".swiftpm/configuration",
home / "Library/org.swift.swiftpm/configuration")
if any((directory / name).exists() for directory in swift_configs for name in ("mirrors.json", "registries.json")):
return None
swift_state = ROOT / ".build/workspace-state.json"
if swift_state.is_file():
dependencies = json.loads(swift_state.read_text())["object"]["dependencies"]
if any(item["state"]["name"] != "sourceControlCheckout" for item in dependencies):
return None
runtime = ROOT / "target/runtime-support"
modules = runtime / "node_modules"
if (not (modules / "huihua").is_dir()
or not os.access(runtime / "xurl/bin/xurl", os.X_OK)):
return None
inputs = {**source_provenance(), "sdk": subprocess.check_output(
["xcrun", "--sdk", "macosx", "--show-sdk-build-version"], text=True, stderr=subprocess.DEVNULL,
).strip()}
for name in ("PATH", "CARGO_BUILD_JOBS", "CARGO_HOME", "RUSTUP_HOME", "RUSTUP_TOOLCHAIN", "DEVELOPER_DIR"):
inputs["env:" + name] = environment.get(name, "")
for name in ("cargo", "rustc", "go", "swift", "xcrun", "xcodebuild", "codesign"):
executable = shutil.which(name, path=environment.get("PATH"))
if executable is None:
return None
path = Path(executable).resolve(strict=True)
info = path.stat()
inputs["tool:" + name] = [str(path), info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns]
# Hapi is authenticated against the tracked catalog by the producer.
# Hash only the prepared runtime inputs that can otherwise change in place.
runtime_files = [runtime / name for name in ("THIRD_PARTY_NOTICES.md", "xurl/bin/xurl", "xurl/REVISION", "xurl/LICENSE")]
def raise_walk_error(error):
raise error
for directory, folders, files in os.walk(modules, onerror=raise_walk_error):
base = Path(directory)
if any((base / name).is_symlink() for name in folders):
return None
runtime_files.extend(base / name for name in files)
if modules.resolve() != modules or runtime.resolve() != runtime:
return None
for path in runtime_files:
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or path.resolve() != path:
return None
inputs[str(path.relative_to(runtime))] = [digest(path), info.st_mode, info.st_ctime_ns]
return snapshot_identity(inputs)
except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError):
return None
def macos_dev_toolchain_matches(manifest):
if manifest["architecture"] != platform.machine() or manifest["macos"] != platform.mac_ver()[0]:
return False
for key, argv in (("rust", ["rustc", "--version"]), ("go", ["go", "version"]),
("swift", ["xcrun", "swiftc", "--version"]), ("xcode", ["xcodebuild", "-version"])):
if subprocess.check_output(argv, text=True, stderr=subprocess.DEVNULL).strip() != manifest[key]:
return False
return True
def reusable_macos_dev(success_path, command, source, extra_inputs):
try:
record = json.loads(success_path.read_text())
if (record.get("macos_dev_inputs") != extra_inputs or record.get("command") != command
or record.get("exit_code") != 0 or not record.get("current")
or record.get("input_before") != source or record.get("input_after") != source):
return None
_, manifest = verify_macos_development_outputs("dev", record)
if macos_dev_toolchain_matches(manifest):
return record
except (OSError, ValueError, AttributeError, KeyError, TypeError, subprocess.CalledProcessError):
pass
return None
def run(args):
from build_lock import FileLock
if args.purpose != "development" and args.platform != "macos":
raise ValueError("--purpose 仅用于 Mac 构建")
command = args.command
if command and command[0] == "--":
command = command[1:]
if not command:
raise ValueError("run需要构建命令")
with FileLock(STATE / "locks" / f"{args.platform}.lock"):
started = time.time()
before_snapshot = source_snapshot(args.platform)
before = snapshot_identity(before_snapshot)
environment = {**os.environ, "VELUNE_BUILD_MANAGED": args.platform}
environment.setdefault("CARGO_BUILD_JOBS", "2")
purpose_suffix = "-" + args.purpose if args.platform == "macos" else ""
path = STATE / "results" / f"{args.platform}-{args.profile}{purpose_suffix}.json"
success_path = path.with_name(path.stem + "-success.json")
extra_inputs = macos_dev_inputs(args, environment)
if extra_inputs is not None and not args.rebuild:
old = reusable_macos_dev(success_path, command, before, extra_inputs)
if (old is not None and source_identity(args.platform) == before
and macos_dev_inputs(args, environment) == extra_inputs):
from macos_identity import app_bundle_path
reused = dict(old, reused=True, duration_seconds=round(time.time() - started, 3))
write(path, (json.dumps(reused, indent=2, ensure_ascii=False) + "\n").encode())
print(f"已复用当前 Mac 开发包:{app_bundle_path(ROOT, 'dev')}")
return 0
result = subprocess.run(command, cwd=ROOT, env=environment)
after_snapshot = source_snapshot(args.platform)
after = snapshot_identity(after_snapshot)
code = result.returncode
if code == 0 and before != after:
code = 3
print("构建期间输入已变化;产物保留,本次不作为当前源码的通过结果。请重新请求构建。", file=sys.stderr)
extra_after = macos_dev_inputs(args, environment) if code == 0 and extra_inputs is not None else None
if code == 0 and extra_inputs is not None and extra_after != extra_inputs:
code = 3
print("构建期间本地工具链或运行时输入已变化,请重新请求构建。", file=sys.stderr)
record = {"platform": args.platform, "profile": args.profile, "command": command,
"input_before": before, "input_after": after, "current": before == after and extra_inputs == extra_after,
"exit_code": code, "duration_seconds": round(time.time() - started, 3),
"artifacts": artifact_identity(args.platform, args.profile, command, args.purpose),
"changed_inputs": sorted(name for name in before_snapshot.keys() | after_snapshot.keys() if before_snapshot.get(name) != after_snapshot.get(name))}
if args.platform == "macos":
record["purpose"] = args.purpose
if code == 0 and extra_inputs is not None:
record["macos_dev_inputs"] = extra_inputs
data = (json.dumps(record, indent=2, ensure_ascii=False) + "\n").encode()
write(path, data)
if code == 0:
write(success_path, data)
return code
def main():
parser = argparse.ArgumentParser(description=__doc__)
actions = parser.add_subparsers(dest="action", required=True)
p = actions.add_parser("copy"); p.add_argument("source"); p.add_argument("destination")
p = actions.add_parser("sync"); p.add_argument("source"); p.add_argument("destination"); p.add_argument("--prune", action="store_true"); p.add_argument("--include", action="append", default=[])
p = actions.add_parser("stage-runtime-scripts")
p.add_argument("destination")
p.add_argument("--prune", action="store_true")
p = actions.add_parser("write"); p.add_argument("path")
actions.add_parser("source-provenance")
actions.add_parser("check-remote-bindings")
p = actions.add_parser("mobile-bindings-config")
p.add_argument("platform", choices=("ios", "android"))
p.add_argument("variant")
p = actions.add_parser("verify-macos-build"); p.add_argument("--profile", choices=("dev", "release"), default="dev")
for name in ("bindgen", "verify-bindings"):
p = actions.add_parser(name); p.add_argument("--library", required=True); p.add_argument("--language", choices=("swift", "kotlin", "python", "cs"), required=True); p.add_argument("--generator"); p.add_argument("--out-dir", required=True); p.add_argument("--artifact", action="append")
p = actions.add_parser("run")
p.add_argument("--platform", choices=("macos", "ios", "android", "windows"), required=True)
p.add_argument("--profile", choices=("dev", "release"), required=True)
p.add_argument("--purpose", choices=("development", "daily"), default="development")
p.add_argument("--reuse-macos-dev", action="store_true")
p.add_argument("--rebuild", action="store_true")
p.add_argument("command", nargs=argparse.REMAINDER)
args = parser.parse_args()
try:
if args.action == "copy": copy(args.source, args.destination)
elif args.action == "sync": sync(args.source, args.destination, args.prune, args.include)
elif args.action == "stage-runtime-scripts": stage_runtime_scripts(args.destination, args.prune)
elif args.action == "write": write(args.path, sys.stdin.buffer.read())
elif args.action == "source-provenance": print(json.dumps(source_provenance(), sort_keys=True))
elif args.action == "check-remote-bindings": check_remote_bindings()
elif args.action == "mobile-bindings-config":
config = MOBILE_BINDINGS.get((args.platform, args.variant))
if not config:
raise ValueError(f"没有 {args.platform} {args.variant} 的移动端绑定配置")
print(*config, sep="\t")
elif args.action == "verify-macos-build": print(json.dumps(verify_macos_build(args.profile)))
elif args.action in ("bindgen", "verify-bindings"): bindings(args, args.action == "verify-bindings")
elif args.action == "run": return run(args)
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
print(f"构建失败:{error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
# Redirected Windows streams can otherwise use a legacy code page.
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
sys.exit(main())