-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
666 lines (549 loc) · 26.1 KB
/
Copy pathengine.py
File metadata and controls
666 lines (549 loc) · 26.1 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
#!/usr/bin/env python3
"""flutter-plezy engine patch-series toolchain - one cross-platform CLI.
Replaces the old per-platform shell/PowerShell script families. The same
commands drive the tvOS series on macOS and the Windows (DComp) series on
Windows; the host OS selects sensible defaults (patch platform, build set)
while every choice stays overridable with --platform.
Usage:
python engine.py fetch <version>
python engine.py apply <version> [--platform tvos|windows]
python engine.py build <version> <variant>
python engine.py regenerate <version> [--platform tvos|windows]
python engine.py package <version> [--platform tvos|windows]
The per-version build logic lives in versions/<version>/build.py (loaded on
demand); the generic gn -> ninja -> promote pipeline lives here in
Ctx.build_variant so each version file stays a thin variant table.
DO NOT hand-edit versions/*/patches/*.patch - they are generated by
`regenerate`. See CLAUDE.md for the maintainer workflow.
"""
from __future__ import annotations
import argparse
import importlib.util
import os
import shutil
import subprocess
import sys
import tarfile
import zipfile
from pathlib import Path
# --------------------------------------------------------------------------
# Host platform detection
# --------------------------------------------------------------------------
def host_platform() -> str:
"""Normalize sys.platform to the tokens the rest of this script uses."""
if sys.platform == "darwin":
return "darwin"
if sys.platform.startswith("win"):
return "win32"
if sys.platform.startswith("linux"):
return "linux"
return sys.platform
# Which patch series a host edits/builds by default. tvOS only builds on macOS
# (Apple SDKs); the Windows embedder only builds on Windows (VS + WinSDK).
DEFAULT_PATCH_PLATFORM = {"darwin": "tvos", "win32": "windows"}
# Components that may carry a patch series, in apply/regenerate order. Each maps
# to a checkout under the synced sources tree. Missing dirs are skipped, so a
# series that only patches the engine (e.g. windows) just no-ops the rest.
COMPONENTS = ("engine", "dart", "skia", "perfetto")
# --------------------------------------------------------------------------
# Context: paths, sdk.lock, subprocess helpers, the build pipeline
# --------------------------------------------------------------------------
class CommandError(Exception):
"""Raised for expected, user-facing failures (printed without a traceback)."""
class Ctx:
def __init__(self, repo_root: Path, version: str, platform: str):
self.repo_root = repo_root
self.version = version
self.platform = platform # host platform: darwin | win32 | linux
self.sources_root = repo_root / "sources"
self.out_root = repo_root / "out"
# ---- paths -----------------------------------------------------------
# gclient with name="." syncs the Flutter monorepo straight into here; the
# monorepo root is itself a git repo and is where engine patches apply.
def monorepo_root(self) -> Path:
return self.sources_root / self.version
# gn's repo root (engine/src), with flutter/ nested inside. Build cwd.
def engine_gn_root(self) -> Path:
return self.monorepo_root() / "engine" / "src"
# The engine source git repo (engine/src/flutter).
def flutter_dir(self) -> Path:
return self.engine_gn_root() / "flutter"
def dart_dir(self) -> Path:
return self.flutter_dir() / "third_party" / "dart"
def skia_dir(self) -> Path:
return self.flutter_dir() / "third_party" / "skia"
def perfetto_dir(self) -> Path:
return self.dart_dir() / "third_party" / "perfetto" / "src"
def component_dir(self, component: str) -> Path:
return {
"engine": self.monorepo_root(),
"dart": self.dart_dir(),
"skia": self.skia_dir(),
"perfetto": self.perfetto_dir(),
}[component]
def patches_dir(self, patch_platform: str, component: str) -> Path:
return self.repo_root / "versions" / self.version / "patches" / patch_platform / component
def out_dir(self, variant: str) -> Path:
return self.out_root / self.version / variant
# ---- sdk.lock --------------------------------------------------------
def load_sdk_lock(self) -> dict[str, str]:
"""Parse versions/<v>/sdk.lock (bash-sourceable KEY=VALUE) into a dict."""
lock = self.repo_root / "versions" / self.version / "sdk.lock"
if not lock.is_file():
raise CommandError(f"no sdk.lock at {lock}")
out: dict[str, str] = {}
for raw in lock.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
key = key.strip()
if not key or not key[0].isalpha() and key[0] != "_":
continue
# Strip surrounding quotes, mirroring how the shell `source` would
# treat these simple assignments. (sdk.lock has no inline comments.)
out[key] = value.strip().strip("'\"")
return out
def engine_base_ref(self, lock: dict[str, str]) -> str:
return lock.get("ENGINE_COMMIT") or lock["ENGINE_REF"]
# ---- subprocess ------------------------------------------------------
def log(self, msg: str) -> None:
print(msg, flush=True)
def die(self, msg: str):
"""Raise a user-facing error (printed without a traceback)."""
raise CommandError(msg)
def run(self, cmd, cwd: Path | None = None, check: bool = True,
env: dict | None = None, quiet: bool = False) -> int:
"""Run a command with inherited stdio. Raises CommandError on failure.
quiet=True discards the command's stderr (for best-effort calls like
`git am --abort` whose noise on a no-op would otherwise alarm the user).
"""
argv = [str(c) for c in cmd]
try:
proc = subprocess.run(
argv, cwd=str(cwd) if cwd else None, env=env,
stderr=subprocess.DEVNULL if quiet else None)
except FileNotFoundError:
raise CommandError(f"command not found: {argv[0]} (is it installed and on PATH?)")
if check and proc.returncode != 0:
raise CommandError(
f"command failed (exit {proc.returncode}): {' '.join(argv)}")
return proc.returncode
def capture(self, cmd, cwd: Path | None = None):
"""Run a command capturing stdout. Returns (returncode, stdout)."""
argv = [str(c) for c in cmd]
try:
proc = subprocess.run(argv, cwd=str(cwd) if cwd else None,
capture_output=True, text=True)
except FileNotFoundError:
raise CommandError(f"command not found: {argv[0]} (is it installed and on PATH?)")
return proc.returncode, proc.stdout
# ---- depot_tools -----------------------------------------------------
def ensure_depot_tools(self, clone_if_missing: bool = True) -> None:
"""Put depot_tools on PATH (cloning into ./depot_tools if needed) and set
the env Windows engine builds require. depot_tools bootstraps its own
pinned git/python on first use, so the user's git config can't corrupt
the checkout (line endings etc.)."""
if self.platform == "win32":
# Use the locally installed Visual Studio, not Google's toolchain.
os.environ["DEPOT_TOOLS_WIN_TOOLCHAIN"] = "0"
if shutil.which("gclient"):
return
dt = self.repo_root / "depot_tools"
if not dt.is_dir():
if not clone_if_missing:
return
self.log(f"[depot_tools] not on PATH - cloning into {dt}")
self.run(["git", "clone", "--depth", "1",
"https://chromium.googlesource.com/chromium/tools/depot_tools.git",
dt])
os.environ["PATH"] = str(dt) + os.pathsep + os.environ.get("PATH", "")
def launch(self, program: str) -> list[str]:
"""Resolve a program (e.g. depot_tools' gclient / python3 shims) to a
subprocess argv prefix. subprocess.run executes .bat/.cmd shims itself
and quotes arguments correctly, so no `cmd /c` wrapper is needed — and a
wrapper would actually mis-parse paths/args containing spaces."""
return [shutil.which(program) or program]
# ---- the generic build pipeline -------------------------------------
def build_variant(self, variant: str, *, gn_flags, ninja_targets,
verify_sdk_hash: bool = False, promote="all") -> None:
"""gn -> (optional verify_sdk_hash patch) -> ninja -> promote artifacts.
Driven entirely by the per-variant config in versions/<v>/build.py, so
the tvOS and Windows flows share one implementation.
"""
engine_src = self.engine_gn_root()
if not (engine_src / "flutter").is_dir():
raise CommandError(
f"engine source missing at {engine_src / 'flutter'} - run `fetch` first")
self.ensure_depot_tools()
out_dir = self.out_dir(variant)
out_dir.parent.mkdir(parents=True, exist_ok=True)
gn_tool = engine_src / "flutter" / "tools" / "gn"
# macOS runs the gn wrapper via its shebang; Windows drives it with
# python3 (matching the engine's own CI builder).
if self.platform == "win32":
gn_cmd = self.launch("python3") + [gn_tool, *gn_flags]
else:
gn_cmd = [gn_tool, *gn_flags]
self.log(f"[gn] {engine_src} -> {' '.join(gn_flags)}")
self.run(gn_cmd, cwd=engine_src)
gn_out = self._locate_gn_out(engine_src, variant)
gn_out_rel = os.path.relpath(gn_out, engine_src)
self.log(f"[gn] output dir: {gn_out_rel}")
if verify_sdk_hash:
# Our patched Dart has a different SDK hash than the prebuilt
# dart-sdk snapshot expects; without this the VM refuses to load
# kernels compiled against the patched SDK. gn's Flutter wrapper
# overwrites args.gn, so append + re-run the real gn binary.
args_gn = gn_out / "args.gn"
text = args_gn.read_text(encoding="utf-8")
if "verify_sdk_hash = false" not in text:
if text and not text.endswith("\n"):
text += "\n"
args_gn.write_text(text + "verify_sdk_hash = false\n", encoding="utf-8")
self.run([engine_src / "flutter" / "third_party" / "gn" / "gn",
"gen", gn_out_rel], cwd=engine_src)
self.log(f"[ninja] -C {gn_out_rel} {' '.join(ninja_targets)}")
self.run(["ninja", "-C", gn_out_rel, *ninja_targets], cwd=engine_src)
self._promote(gn_out, out_dir, promote)
self.log("")
self.log(f"Built {variant} -> {out_dir}")
def _locate_gn_out(self, engine_src: Path, variant: str) -> Path:
"""Find the out/ dir gn just populated. Prefer out/<variant> (the Windows
gn wrapper names the dir from the variant); otherwise take the most
recently written dir and require it to carry an args.gn — erroring if gn
produced nothing, rather than silently building a stale older dir."""
out_parent = engine_src / "out"
named = out_parent / variant
if (named / "args.gn").is_file():
return named
dirs = [d for d in out_parent.iterdir() if d.is_dir()] if out_parent.is_dir() else []
if not dirs:
raise CommandError(f"couldn't locate gn output dir under {out_parent}")
newest = max(dirs, key=lambda d: d.stat().st_mtime)
if not (newest / "args.gn").is_file():
raise CommandError(f"newest gn output dir {newest} has no args.gn - did gn fail?")
return newest
def _promote(self, gn_out: Path, out_dir: Path, promote) -> None:
"""Copy the built artifacts to the canonical out/<version>/<variant>/ so
`package` finds them regardless of how gn named its output dir."""
if out_dir.exists():
shutil.rmtree(out_dir)
out_dir.mkdir(parents=True)
if promote == "all":
# tvOS ships the whole gn out dir. rsync is fastest where available
# (macOS); fall back to a pure-Python copy otherwise.
if shutil.which("rsync"):
self.run(["rsync", "-a", "--delete", f"{gn_out}/", f"{out_dir}/"])
else:
shutil.rmtree(out_dir)
shutil.copytree(gn_out, out_dir, symlinks=True)
return
# Windows promotes only the consumer-facing items (the full out dir is
# tens of GB). Each entry may be a file or a directory.
for item in promote:
src = gn_out / item
if not src.exists():
continue
dst = out_dir / item
dst.parent.mkdir(parents=True, exist_ok=True)
if src.is_dir():
shutil.copytree(src, dst, symlinks=True)
else:
shutil.copy2(src, dst)
# --------------------------------------------------------------------------
# Commands
# --------------------------------------------------------------------------
GCLIENT_TEMPLATE = """\
solutions = [
{{
"managed": False,
"name": ".",
"url": "{url}",
"deps_file": "DEPS",
"custom_deps": {{}},
"safesync_url": "",
}},
]
"""
def cmd_fetch(ctx: Ctx, args) -> None:
"""gclient-sync the Flutter monorepo + engine deps into sources/<version>/."""
lock = ctx.load_sdk_lock()
ctx.ensure_depot_tools()
src_root = ctx.monorepo_root()
src_root.mkdir(parents=True, exist_ok=True)
gclient_file = src_root / ".gclient"
if not gclient_file.exists():
ctx.log(f"[gclient] writing {gclient_file}")
gclient_file.write_text(GCLIENT_TEMPLATE.format(url=lock["ENGINE_REPO"]),
encoding="utf-8")
rev = ctx.engine_base_ref(lock)
ctx.log(f"[gclient] syncing {src_root} at {rev}")
ctx.run(ctx.launch("gclient") + ["sync", "--revision", f".@{rev}",
"--no-history", "--with_tags"], cwd=src_root)
ctx.log("")
ctx.log(f"Sources synced into {src_root}")
ctx.log(f"Next: python engine.py apply {ctx.version}")
def cmd_apply(ctx: Ctx, args) -> None:
"""git-am a platform's patch series onto the synced source trees."""
ctx.load_sdk_lock() # validate version exists
patch_platform = resolve_patch_platform(ctx, args)
ctx.log(f"[apply] platform: {patch_platform}")
applied_any = False
for component in COMPONENTS:
patches = ctx.patches_dir(patch_platform, component)
cwd = ctx.component_dir(component)
applied_any |= _apply_at(ctx, component, patches, cwd)
if not applied_any:
ctx.log(f"[apply] no patch series found for platform '{patch_platform}'")
ctx.log("")
ctx.log(f"Patches applied. Ready to build: python engine.py build {ctx.version} <variant>")
def _apply_at(ctx: Ctx, label: str, patches: Path, cwd: Path) -> bool:
if not (cwd / ".git").is_dir():
raise CommandError(
f"[{label}] {cwd} is not a git repo - has `fetch` been run?")
if not patches.is_dir():
ctx.log(f"[{label}] no patches dir at {patches} - skipping")
return False
files = sorted(patches.glob("*.patch"))
if not files:
ctx.log(f"[{label}] no .patch files in {patches} - skipping")
return False
ctx.log(f"[{label}] applying {len(files)} patches to {cwd}")
# Best-effort: clear any stale am state. Silence the no-op's stderr noise.
ctx.run(["git", "am", "--abort"], cwd=cwd, check=False, quiet=True)
rc = ctx.run(["git", "am", "--3way", *files], cwd=cwd, check=False)
if rc != 0:
raise CommandError(
f"[{label}] git am failed - resolve in {cwd} then 'git am --continue'")
return True
def cmd_regenerate(ctx: Ctx, args) -> None:
"""git-format-patch the current source state back into the patch series.
Captures everything between the pinned base and HEAD, so regenerate a
platform's series ONLY from a tree with that platform's patches applied.
"""
lock = ctx.load_sdk_lock()
patch_platform = resolve_patch_platform(ctx, args)
ctx.log(f"[regen] platform: {patch_platform}")
bases = {
"engine": ctx.engine_base_ref(lock),
"dart": lock.get("DART_COMMIT"),
"skia": lock.get("SKIA_COMMIT"),
"perfetto": lock.get("PERFETTO_COMMIT"),
}
for component in COMPONENTS:
_regen(ctx, component, bases[component], ctx.component_dir(component),
ctx.patches_dir(patch_platform, component))
ctx.log("")
ctx.log(f"Patches regenerated. Review: git -C {ctx.repo_root} diff versions/{ctx.version}/patches/")
def _regen(ctx: Ctx, label: str, base_ref: str | None, cwd: Path, out: Path) -> None:
if not (cwd / ".git").is_dir():
ctx.log(f"[{label}] no sources at {cwd} - skipping")
return
if not base_ref:
ctx.log(f"[{label}] no base ref in sdk.lock - skipping")
return
rc, _ = ctx.capture(["git", "cat-file", "-e", base_ref], cwd=cwd)
if rc != 0:
raise CommandError(
f"[{label}] base ref '{base_ref}' unknown in {cwd}. Has sdk.lock drifted from DEPS?")
rc, status = ctx.capture(["git", "status", "--porcelain"], cwd=cwd)
if status.strip():
raise CommandError(
f"[{label}] {cwd} has uncommitted changes. Commit them in the source repo first.")
ctx.log(f"[{label}] regenerating patches from {base_ref}..HEAD in {cwd}")
if out.exists():
shutil.rmtree(out)
out.mkdir(parents=True)
ctx.run(["git", "format-patch", "--no-stat", "--no-signature",
f"{base_ref}..HEAD", "-o", out], cwd=cwd)
produced = sorted(out.glob("*.patch"))
if not produced:
ctx.log(f"[{label}] no patches produced - source is identical to base")
try:
out.rmdir()
except OSError:
pass
else:
ctx.log(f"[{label}] wrote {len(produced)} patches")
def cmd_build(ctx: Ctx, args) -> None:
"""Build one engine variant via the version's build.py variant table.
depot_tools is set up inside build_variant (after the variant resolves), so
a mistyped variant fails fast without a depot_tools clone.
"""
ctx.load_sdk_lock() # validate version exists
build_mod = load_build_module(ctx)
build_mod.build(ctx, args.variant)
def cmd_package(ctx: Ctx, args) -> None:
"""Bundle the release artifacts for a platform (tvOS tarball / Windows zip)."""
patch_platform = resolve_patch_platform(ctx, args)
if patch_platform == "tvos":
_package_tvos(ctx)
elif patch_platform == "windows":
_package_windows(ctx)
else:
raise CommandError(f"no packaging defined for platform '{patch_platform}'")
# tvOS: a minimal tarball with only what consumer apps need. Nested under
# out/<variant>/... so consumers extract anywhere and point FLUTTER_LOCAL_ENGINE
# at the extract dir.
TVOS_PACKAGE_ITEMS = (
# Simulator (dev iteration)
"tvos_debug_sim_unopt_arm64/Flutter.framework",
"tvos_debug_sim_unopt_arm64/gen/flutter/lib/snapshot/vm_isolate_snapshot.bin",
"tvos_debug_sim_unopt_arm64/gen/flutter/lib/snapshot/isolate_snapshot.bin",
# Device AOT
"tvos_release/Flutter.framework",
"tvos_release/artifacts_arm64/gen_snapshot_arm64",
"tvos_release/gen/flutter/lib/snapshot/vm_isolate_snapshot.bin",
"tvos_release/gen/flutter/lib/snapshot/isolate_snapshot.bin",
# Host tools to compile kernels + AOT snapshots on macOS.
"host_release/dart-sdk/bin/dart",
"host_release/dart-sdk/bin/dartaotruntime",
"host_release/dart-sdk/bin/snapshots/frontend_server_aot.dart.snapshot",
"host_release/dart-sdk/lib",
"host_release/dart-sdk/include",
"host_release/dart-sdk/version",
"host_release/flutter_patched_sdk",
"host_release/clang_arm64/gen_snapshot",
)
def _package_tvos(ctx: Ctx) -> None:
out_version = ctx.out_root / ctx.version
pkg_dir = ctx.out_root / "packages"
tarball = pkg_dir / f"flutter-tvos-{ctx.version}.tar.gz"
missing = [item for item in TVOS_PACKAGE_ITEMS if not (out_version / item).exists()]
if missing:
raise CommandError(
"missing build outputs - run build for all variants first:\n "
+ "\n ".join(missing))
pkg_dir.mkdir(parents=True, exist_ok=True)
if tarball.exists():
tarball.unlink()
ctx.log(f"Packaging -> {tarball}")
with tarfile.open(tarball, "w:gz") as tf:
for item in TVOS_PACKAGE_ITEMS:
tf.add(out_version / item, arcname=f"out/{item}")
ctx.log(f"Wrote {human_size(tarball.stat().st_size)} -> {tarball}")
ctx.log(f"Done. Upload with: gh release create v{ctx.version} {tarball}")
# Windows: the cache-layout flutter zips for each host variant, repacked into a
# single zip consumers extract over bin/cache/artifacts/engine/windows-x64{,-release}/.
WINDOWS_PACKAGE_ITEMS = (
("host_debug", "windows-x64"),
("host_release", "windows-x64-release"),
)
def _package_windows(ctx: Ctx) -> None:
out_version = ctx.out_root / ctx.version
pkg_dir = ctx.out_root / "packages"
stage = pkg_dir / f"stage-windows-{ctx.version}"
zip_path = pkg_dir / f"flutter-plezy-windows-{ctx.version}.zip"
if stage.exists():
shutil.rmtree(stage)
stage.mkdir(parents=True)
missing = []
for variant, cache_dir in WINDOWS_PACKAGE_ITEMS:
archive_root = out_version / variant / "zip_archives"
flutter_zip = next(archive_root.rglob("windows-x64-flutter.zip"), None) \
if archive_root.is_dir() else None
if flutter_zip is None:
missing.append(f"{variant}: zip_archives/.../windows-x64-flutter.zip")
continue
dst = stage / cache_dir
dst.mkdir(parents=True)
with zipfile.ZipFile(flutter_zip) as zf:
zf.extractall(dst)
if missing:
shutil.rmtree(stage, ignore_errors=True)
raise CommandError(
"missing build outputs - run build for these variants first:\n "
+ "\n ".join(missing))
if zip_path.exists():
zip_path.unlink()
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
for path in sorted(stage.rglob("*")):
if path.is_file():
zf.write(path, arcname=str(path.relative_to(stage)))
shutil.rmtree(stage, ignore_errors=True)
ctx.log(f"Wrote {human_size(zip_path.stat().st_size)} -> {zip_path}")
ctx.log(f"Done. Upload with: gh release create windows-v{ctx.version} {zip_path}")
# --------------------------------------------------------------------------
# Helpers shared by commands
# --------------------------------------------------------------------------
def resolve_patch_platform(ctx: Ctx, args) -> str:
"""Pick the patch series: explicit --platform wins, else default by host."""
if getattr(args, "platform", None):
return args.platform
default = DEFAULT_PATCH_PLATFORM.get(ctx.platform)
if default is None:
raise CommandError(
f"no default patch platform for host '{ctx.platform}' - pass --platform tvos|windows")
return default
def load_build_module(ctx: Ctx):
"""Import versions/<version>/build.py as a module."""
build_py = ctx.repo_root / "versions" / ctx.version / "build.py"
if not build_py.is_file():
raise CommandError(f"no build.py for version {ctx.version} at {build_py}")
spec = importlib.util.spec_from_file_location(
f"engine_build_{ctx.version.replace('.', '_')}", build_py)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if not hasattr(module, "build"):
raise CommandError(f"{build_py} does not define build(ctx, variant)")
return module
def human_size(num: float) -> str:
for unit in ("B", "KB", "MB", "GB", "TB"):
if num < 1024 or unit == "TB":
return f"{num:.1f}{unit}" if unit != "B" else f"{int(num)}B"
num /= 1024
return f"{num:.1f}TB"
# --------------------------------------------------------------------------
# Entry point
# --------------------------------------------------------------------------
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="engine.py",
description="flutter-plezy engine patch-series toolchain (cross-platform).")
sub = parser.add_subparsers(dest="command", required=True)
def add_platform(p):
p.add_argument("--platform", choices=["tvos", "windows"],
help="patch series to act on (default: by host OS)")
p = sub.add_parser("fetch", help="gclient-sync upstream into sources/<version>/")
p.add_argument("version")
p.set_defaults(func=cmd_fetch)
p = sub.add_parser("apply", help="git-am a patch series onto the sources")
p.add_argument("version")
add_platform(p)
p.set_defaults(func=cmd_apply)
p = sub.add_parser("regenerate", help="git-format-patch sources back into the series")
p.add_argument("version")
add_platform(p)
p.set_defaults(func=cmd_regenerate)
p = sub.add_parser("build", help="build one engine variant")
p.add_argument("version")
p.add_argument("variant")
p.set_defaults(func=cmd_build)
p = sub.add_parser("package", help="bundle release artifacts")
p.add_argument("version")
add_platform(p)
p.set_defaults(func=cmd_package)
return parser
def main(argv=None) -> int:
# Windows consoles default to a legacy code page; keep stray non-ASCII in a
# path from crashing output instead of printing an error.
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(errors="backslashreplace")
except (AttributeError, ValueError):
pass
args = build_parser().parse_args(argv)
repo_root = Path(__file__).resolve().parent
ctx = Ctx(repo_root, args.version, host_platform())
try:
args.func(ctx, args)
except CommandError as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
except KeyboardInterrupt:
print("\ninterrupted", file=sys.stderr)
return 130
return 0
if __name__ == "__main__":
sys.exit(main())