Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Engine: tools/engine.py fetches and patches seedds/nxnative into engine/
v0lumehi70f0f5b3b1e7
diff --git a/.gitignore b/.gitignoreindex a1326177..d7a39484 100644--- a/.gitignore+++ b/.gitignore@@ -35,3 +35,7 @@ frontend/NX2Apple.app/# the virtual environment the README creates for the Python packages.venv/++# The engine: seedds/nxnative at .upstream-ref plus patches/, made by `python3 tools/engine.py sync` (issue #214). A build product+# like .build/, so git ignores it. The root .ignore un-ignores it for ripgrep-based search, so agents and editors still find it.+/engine/diff --git a/.ignore b/.ignorenew file mode 100644index 00000000..a69ec28e--- /dev/null+++ b/.ignore@@ -0,0 +1,3 @@+# Read by ripgrep (and tools built on it, such as Claude Code's search), not by git: engine/ is in .gitignore because it is+# generated (tools/engine.py sync, issue #214), but its files are the engine's sources and must stay searchable.+!/engine/diff --git a/scripts/patches.py b/scripts/patches.pyold mode 100644new mode 100755index 1ed09de4..6b325681--- a/scripts/patches.py+++ b/scripts/patches.py@@ -1,606 +1,6 @@#!/usr/bin/env python3-"""The fork's patch queue on a pinned upstream (LNPANDY/NX2Apple#123).+"""Moved to tools/patches.py (LNPANDY/NX2Apple#214). This forwarder keeps the old command working until the committed tree goes."""+import os+import runpy-The vendored paths (dm/ scripts/ docs/ ref/ AGENTS.md) are generated, not hand-edited: seedds/nxnative at the commit-in .upstream-ref, plus the patches in patches/ applied in the order of patches/series with `git am -3`. Each patch is a-`git format-patch` file whose message carries a header:-- Upstream-Status: forwarded seedds/nxnative#475 | pending | fork-only | backport <sha>- Reason: <one line>- Issue: <repo>#<n>--Subcommands (Python 3.9+, stdlib and git):- apply [--ref SHA] build the vendored tree from upstream at the ref plus the series (a temporary worktree), regenerate- the generated indexes (GENERATED), copy it into the checkout, and write dm/fork_patches.txt- bump --to SHA move the pin: re-apply the series on SHA, drop the patches that come out empty (upstream has them)- and report them, refresh the rest; on a conflict stop, naming the patch, its Reason and its- Upstream-Status, and leave the conflict in a worktree for a human. --dry changes nothing and- reports every patch that would conflict- export <commit|range> turn local commits on the vendored tree into patches with the header template- absorb [paths...] fold changes made directly to vendored files into the patch that already touches each file (a new- file goes to a patch only when the choice is unambiguous, else name it with --into), then run check- status a table of the patches: Upstream-Status, Reason, age- check the headers are valid, no patch touches the shader chain, the series applies to the pinned ref and- reproduces the vendored tree of the checkout byte for byte (after- the generated indexes are regenerated on it)--Scratch worktrees go under $PATCHES_TMP (or --tmp), else the system temporary folder.-"""-import argparse, fnmatch, os, re, shutil, subprocess, sys, tempfile, time-from pathlib import Path--REPO = Path(__file__).resolve().parent.parent-VENDORED = ('dm', 'scripts', 'docs', 'AGENTS.md', 'ref')-# Inside the vendored paths but not part of the generated tree: the tool, its test, and the list it writes.-OWN = ('scripts/patches.py', 'scripts/tests/test_patches.py', 'dm/fork_patches.txt')-FORK_PATCHES = 'dm/fork_patches.txt'-# Generated files inside the vendored paths: upstream's tests require each to equal what its tool writes from the tree-# (test_docs.py), and the tree differs from upstream's once the series is in, so a patch cannot carry them (they would-# conflict on every bump). apply, bump and check run the tools on the patched tree and commit the result; export and check-# keep patches away from these paths.-GENERATED = (('docs/agents/game-patches.md', 'dm/tools/docs_patches.py'),- ('docs/agents/symptoms.md', 'dm/tools/docs_symptoms.py'))-KINDS = ('forwarded', 'pending', 'fork-only', 'backport')-# The shader chain and the tool pins (AGENTS.md: the DMSH_CHAIN paragraph names them; chain_paths() reads it).-# Used only when AGENTS.md has no such paragraph.-CHAIN_FALLBACK = ('dm/gfx/nvn/dmsh_chain.h', 'dm/gfx/tools/dmsh_*', 'dm/gfx/tools/Program.cs', 'dm/gfx/tools/ios_metal.py',- 'dm/gfx/tools/dmsh_chain.lock', 'dm/gfx/tools/dmsh_xlate_bin*')---class Fail(Exception):- pass---def git(*a, cwd=None, check=True, inp=None, binary=False):- r = subprocess.run(['git', *a], cwd=cwd or REPO, input=inp, capture_output=True, text=not binary)- if check and r.returncode:- raise Fail(f'git {" ".join(a)} failed: {(r.stderr if not binary else r.stderr.decode(errors="replace")).strip()[-1500:]}')- return r---def say(*a):- print(*a, flush=True)---# ---- the series and the headers ------class Patch:- def __init__(self, path):- self.path = path- self.file = path.name- self.name = re.sub(r'^\d+-', '', re.sub(r'\.patch$', '', self.file))- text = path.read_text(encoding='utf-8', errors='replace')- head = text.split('\n---\n', 1)[0]- m = re.search(r'(?m)^Subject: (?:\[PATCH[^\]]*\] )?(.*(?:\n .*)*)', head)- self.subject = self.decode_subject(m.group(1)) if m else ''- self.date = (re.search(r'(?m)^Date: (.*)$', head) or [None, ''])[1]- self.status = self.header(head, 'Upstream-Status')- self.reason = self.header(head, 'Reason')- self.issue = self.header(head, 'Issue')- self.kind = (self.status.split() or [''])[0]- self.files = sorted({f for m in re.finditer(r'(?m)^diff --git a/(\S+) b/(\S+)$', text) for f in m.groups()})-- @staticmethod- def decode_subject(raw):- """format-patch writes a subject with a non-ASCII character as RFC 2047 words (=?UTF-8?q?...?=), git log prints it decoded."""- import email.errors- import email.header- joined = ' '.join(raw.split())- try: return str(email.header.make_header(email.header.decode_header(joined)))- except (email.errors.HeaderParseError, LookupError, UnicodeError): return joined-- @staticmethod- def header(head, key):- m = re.search(r'(?m)^' + key + r': *(.*)$', head)- return m.group(1).strip() if m else ''-- def age_days(self):- import email.utils- try:- return max(0, int((time.time() - email.utils.mktime_tz(email.utils.parsedate_tz(self.date))) // 86400))- except Exception:- return -1-- def problems(self):- out = []- if self.kind not in KINDS:- out.append(f'Upstream-Status must start with one of {", ".join(KINDS)} (is: {self.status or "missing"})')- elif self.kind == 'forwarded' and not re.search(r'#\d+', self.status):- out.append('Upstream-Status: forwarded needs the upstream PR, e.g. forwarded seedds/nxnative#475')- elif self.kind == 'backport' and not re.search(r'\b[0-9a-f]{7,40}\b', self.status):- out.append('Upstream-Status: backport needs the upstream commit')- for key, val in (('Reason', self.reason), ('Issue', self.issue)):- if not val: out.append(f'{key} is missing')- elif val.startswith('TODO'): out.append(f'{key} is still the export template ({val})')- return out---def read_series(root):- s = root / 'patches/series'- if not s.is_file(): raise Fail(f'{s} is missing')- out = []- for line in s.read_text().splitlines():- line = line.split('#', 1)[0].strip()- if line: out.append(line)- return out---def load(root):- pd = root / 'patches'- names = read_series(root)- missing = [n for n in names if not (pd / n).is_file()]- if missing: raise Fail('listed in patches/series but missing: ' + ', '.join(missing))- if len(set(names)) != len(names): raise Fail('patches/series lists a patch twice')- return [Patch(pd / n) for n in names]---def chain_paths(root):- """The globs of the shader chain, read from AGENTS.md's chain paragraph (the one naming DMSH_CHAIN)."""- try: text = (root / 'AGENTS.md').read_text()- except OSError: return list(CHAIN_FALLBACK)- para = next((l for l in text.splitlines() if 'DMSH_CHAIN' in l and 'dm/gfx/tools/dmsh_' in l), None)- found = []- if para:- for tok in re.findall(r'`([^`]+)`', para):- if re.fullmatch(r'dm/gfx/(?:nvn|tools)/[\w./*-]+', tok): found.append(tok)- elif re.fullmatch(r'[\w-]+\.(?:cs|py|lock)', tok) and not tok.startswith('dmsh_'): found.append('dm/gfx/tools/' + tok)- elif tok == 'dmsh_chain.lock': found.append('dm/gfx/tools/' + tok)- m = re.search(r'translator is `([^`]+)`', text)- if m and re.fullmatch(r'dm/gfx/tools/[\w./-]+', m.group(1)): found.append(m.group(1) + '*')- return sorted(set(found)) if len(found) >= 4 else list(CHAIN_FALLBACK)---def chain_hits(files, root):- globs = chain_paths(root)- return sorted(f for f in files if any(fnmatch.fnmatchcase(f, g) for g in globs))---# ---- applying the series in a scratch worktree ------def resolve(ref, root):- r = git('rev-parse', '--verify', '--quiet', f'{ref}^{{commit}}', cwd=root, check=False)- if r.returncode:- raise Fail(f'{ref} is not a commit in this repository: fetch it first (git fetch seedds {ref})')- return r.stdout.strip()---class Scratch:- """A detached worktree of upstream at a commit, removed on exit unless kept."""- def __init__(self, root, sha, tmp=None, keep=False):- self.root, self.sha, self.keep = root, sha, keep- self.base = Path(tempfile.mkdtemp(prefix='patches-', dir=tmp or os.environ.get('PATCHES_TMP') or None))- self.dir = self.base / 'tree'- git('worktree', 'add', '--detach', '-q', str(self.dir), sha, cwd=root)-- def close(self):- if self.keep: return- git('worktree', 'remove', '--force', str(self.dir), cwd=self.root, check=False)- shutil.rmtree(self.base, ignore_errors=True)- git('worktree', 'prune', cwd=self.root, check=False)-- def __enter__(self): return self- def __exit__(self, *e): self.close()---def am(wt, patch):- return git('-c', 'user.name=patches.py', '-c', 'user.email=patches@localhost', '-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false',- 'am', '-3', '--quiet', str(patch.path), cwd=wt, check=False)---def apply_series(wt, patches, stop=True):- """Apply each patch in turn. Returns (applied, landed, conflicts): applied = [(patch, commit)], landed = patches that came- out empty (upstream has them), conflicts = [(patch, message)]. With stop, the first conflict stays in the worktree."""- applied, landed, conflicts = [], [], []- for p in patches:- before = git('rev-parse', 'HEAD', cwd=wt).stdout.strip()- r = am(wt, p)- if r.returncode == 0:- after = git('rev-parse', 'HEAD', cwd=wt).stdout.strip()- if after == before or git('rev-parse', 'HEAD^{tree}', cwd=wt).stdout == git('rev-parse', before + '^{tree}', cwd=wt).stdout:- git('reset', '--hard', '-q', before, cwd=wt) # the merge changed nothing: upstream has this patch- landed.append(p); continue- applied.append((p, after)); continue- unmerged = git('ls-files', '-u', cwd=wt).stdout.strip()- clean = git('diff', '--cached', '--quiet', cwd=wt, check=False).returncode == 0 and git('diff', '--quiet', cwd=wt, check=False).returncode == 0- if not unmerged and clean and 'Patch failed' not in r.stderr and 'patch does not apply' not in r.stderr:- git('am', '--skip', cwd=wt, check=False)- landed.append(p); continue- files = git('diff', '--name-only', '--diff-filter=U', cwd=wt, check=False).stdout.split()- errs = [l for l in (r.stderr + r.stdout).splitlines() if re.match(r'(error|CONFLICT|Patch failed|Applying)', l)]- conflicts.append((p, ('conflicting files: ' + ', '.join(files) + '\n' if files else '') + '\n'.join(errs[-6:])))- if stop: break- git('am', '--abort', cwd=wt, check=False)- return applied, landed, conflicts---def generate(wt):- """Run the generators of GENERATED on the patched tree and commit what they changed (no commit when nothing changed)."""- for out, tool in GENERATED:- if not (wt / tool).is_file(): continue- r = subprocess.run([sys.executable, str(wt / tool)], cwd=wt, capture_output=True, text=True)- if r.returncode:- raise Fail(f'{tool} failed on the patched tree: {(r.stderr.strip().splitlines() or [str(r.returncode)])[-1]}')- if git('status', '--porcelain', '--', *(o for o, _ in GENERATED), cwd=wt).stdout.strip():- git('add', '--', *(o for o, _ in GENERATED), cwd=wt)- git('-c', 'user.name=patches.py', '-c', 'user.email=patches@localhost', '-c', 'commit.gpgsign=false',- 'commit', '-q', '-m', 'Regenerated indexes: ' + ', '.join(o for o, _ in GENERATED), cwd=wt)---def tree_files(wt):- """{path: (mode, blob)} of the vendored paths at HEAD of a worktree, without the tool's own files."""- out = git('ls-tree', '-r', '-z', 'HEAD', '--', *VENDORED, cwd=wt).stdout- files = {}- for rec in out.split('\0'):- if not rec: continue- meta, path = rec.split('\t', 1)- mode, _, blob = meta.split()- if path not in OWN: files[path] = (mode, blob)- return files---def fork_patch_list(patches):- return ''.join(p.name + '\n' for p in patches)---def local_files(root):- """{path: (mode, blob)} of the checkout's working tree under the vendored paths: tracked files that still exist plus- untracked ones git does not ignore, without the tool's own files."""- r = git('ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', *VENDORED, cwd=root).stdout- paths = sorted({p for p in r.split('\0') if p and p not in OWN and (root / p).is_file()})- files = {}- if paths:- blobs = git('hash-object', '--stdin-paths', cwd=root, inp='\n'.join(paths) + '\n').stdout.split()- for p, b in zip(paths, blobs):- files[p] = ('100755' if os.access(root / p, os.X_OK) else '100644', b)- return files---def diff_trees(want, have):- out = []- for p in sorted(set(want) | set(have)):- if p not in have: out.append(f' missing in the checkout: {p}')- elif p not in want: out.append(f' not produced by the series: {p}')- elif want[p] != have[p]:- what = 'mode' if want[p][1] == have[p][1] else 'content'- out.append(f' differs ({what}): {p}')- return out---def install(root, wt, patches):- """Copy the generated vendored tree into the checkout: delete tracked vendored files it no longer has, write the rest."""- want = tree_files(wt)- for p in git('ls-files', '-z', '--', *VENDORED, cwd=root).stdout.split('\0'):- if p and p not in want and p not in OWN and (root / p).exists(): (root / p).unlink()- for p, (mode, blob) in want.items():- dest = root / p- dest.parent.mkdir(parents=True, exist_ok=True)- if dest.is_symlink(): dest.unlink()- dest.write_bytes((wt / p).read_bytes())- dest.chmod(0o755 if mode == '100755' else 0o644)- (root / FORK_PATCHES).write_text(fork_patch_list(patches))---def fix_hint(diff, patches):- """What a failing author runs. diff = the lines of diff_trees (plus the fork_patches.txt line)."""- gen = {o for o, _ in GENERATED}- paths = [m.group(1) for l in diff for m in [re.search(r': (\S+)$', l)] if m and not l.rstrip().endswith('(run patches.py apply)')]- absorbable = [p for p in paths if p not in gen]- lines = ['']- for l in diff:- m = re.search(r': (\S+)$', l)- if not m or l.rstrip().endswith('(run patches.py apply)'): continue- f = m.group(1)- if f in gen: lines.append(f'{f} is generated: run `python3 scripts/patches.py apply`')- else: lines.append(f'{f} differs from pin+patches: run `python3 scripts/patches.py absorb {f}` and commit patches/')- if absorbable:- lines.append('To fold all of them at once: `python3 scripts/patches.py absorb`, then commit patches/ (and dm/fork_patches.txt if it changed).')- lines.append('A new file goes to the patch that owns its folder; if that is ambiguous, absorb stops and asks for `--into <patch>` (see `scripts/patches.py status`).')- lines.append('A change that deserves its own patch (new Upstream-Status, Reason, Issue): commit it, then `python3 scripts/patches.py export <commit>`. See patches/README.md.')- else:- lines.append('Run `python3 scripts/patches.py apply` to rewrite the generated files, then commit. See patches/README.md.')- return '\n'.join(lines)---# ---- subcommands ------def cmd_check(a):- root = a.root- patches = load(root)- bad = []- pd = root / 'patches'- stray = sorted(f.name for f in pd.glob('*.patch') if f.name not in {p.file for p in patches})- if stray: bad.append('patch files not in patches/series: ' + ', '.join(stray))- for p in patches:- for m in p.problems(): bad.append(f'{p.file}: {m}')- gen = sorted(f for f in p.files if f in {o for o, _ in GENERATED})- if gen: bad.append(f'{p.file}: touches generated files ({", ".join(gen)}); apply, bump and check regenerate them, so a patch must not carry them')- hits = chain_hits(p.files, root)- if hits: bad.append(f'{p.file}: touches the shader chain or the tool pins, which patches must not change ({", ".join(hits)}); see patches/README.md, Patch policy')- if bad:- say('patch queue: invalid\n ' + '\n '.join(bad)); return 1- ref = (root / '.upstream-ref').read_text().strip()- sha = resolve(ref, root)- with Scratch(root, sha, a.tmp) as s:- applied, landed, conflicts = apply_series(s.dir, patches)- if conflicts:- p, msg = conflicts[0]- say(f'patch queue: {p.file} does not apply to the pinned upstream {sha[:12]}\n Reason: {p.reason}\n Upstream-Status: {p.status}\n {msg}'); return 1- if landed:- say('patch queue: patches that are empty on the pinned upstream (it has them already; run bump to drop them): ' + ', '.join(p.file for p in landed)); return 1- generate(s.dir)- want = tree_files(s.dir)- diff = diff_trees(want, local_files(root))- expect = fork_patch_list(patches)- have_list = (root / FORK_PATCHES).read_text() if (root / FORK_PATCHES).exists() else None- if have_list != expect: diff.append(f' {FORK_PATCHES} is not the list of the series (run patches.py apply)')- if diff:- say(f'patch queue: the vendored tree is not upstream {sha[:12]} plus the series ({len(diff)} differences):')- say('\n'.join(diff[:40]) + ('\n ...' if len(diff) > 40 else ''))- say(fix_hint(diff, patches))- return 1- say(f'patch queue: ok. {len(patches)} patches apply to upstream {sha[:12]} and give the committed vendored tree ({len(want)} files)')- return 0---def cmd_apply(a):- root = a.root- patches = load(root)- ref = a.ref or (root / '.upstream-ref').read_text().strip()- sha = resolve(ref, root)- with Scratch(root, sha, a.tmp) as s:- applied, landed, conflicts = apply_series(s.dir, patches)- if conflicts:- p, msg = conflicts[0]- raise Fail(f'{p.file} does not apply to {sha[:12]}\n Reason: {p.reason}\n Upstream-Status: {p.status}\n {msg}')- generate(s.dir)- install(root, s.dir, [p for p, _ in applied])- if landed: say('empty at this ref (upstream has them): ' + ', '.join(p.file for p in landed) + ' (patches.py bump drops them)')- say(f'applied {len(applied)} patches to upstream {sha[:12]}; the vendored tree is written')- return 0---def cmd_bump(a):- root = a.root- patches = load(root)- old = (root / '.upstream-ref').read_text().strip() if (root / '.upstream-ref').exists() else '?'- sha = resolve(a.to, root)- keep = not a.dry- s = Scratch(root, sha, a.tmp, keep=keep)- try:- applied, landed, conflicts = apply_series(s.dir, patches, stop=not a.dry)- report(old, sha, applied, landed, conflicts)- if conflicts:- if a.dry:- s.close(); return 1- p = conflicts[0][0]- say(f'\nStopped at {p.file}. The conflict is left in {s.dir}:\n'- f' resolve it there, `git am --continue`, apply the rest with `git am -3 <patches>`, then run\n'- f' scripts/patches.py refresh {s.dir} --to {sha[:12]}')- return 1- if a.dry:- return 0- write_series(root, s.dir, applied, landed, patches)- (root / '.upstream-ref').write_text(sha + '\n')- generate(s.dir)- install(root, s.dir, [p for p, _ in applied])- s.close()- return 0- except BaseException:- s.close()- raise---def report(old, sha, applied, landed, conflicts):- say(f'bump {old[:12]} -> {sha[:12]}')- say(f' applied cleanly ({len(applied)}): ' + (', '.join(p.name for p, _ in applied) or 'none'))- say(f' landed upstream, dropped ({len(landed)}): ' + (', '.join(p.name for p in landed) or 'none'))- say(f' conflicts ({len(conflicts)}):' + ('' if conflicts else ' none'))- for p, msg in conflicts:- say(f' {p.file}\n Reason: {p.reason}\n Upstream-Status: {p.status}')- for l in msg.splitlines(): say(' | ' + l)---def write_series(root, wt, applied, landed, patches):- """Rewrite patches/ from the rebased commits: the kept patches refreshed, the landed ones deleted."""- pd = root / 'patches'- for p, commit in applied:- text = git('format-patch', '--binary', '--zero-commit', '--no-signature', '--no-numbered', '--stdout', '-1', commit, cwd=wt, binary=True).stdout- p.path.write_bytes(text)- for p in landed: p.path.unlink()- keep = {p.file for p, _ in applied}- lines = [l for l in (pd / 'series').read_text().splitlines()]- out = [l for l in lines if l.split('#', 1)[0].strip() == '' or l.split('#', 1)[0].strip() in keep]- (pd / 'series').write_text('\n'.join(out) + '\n')---def cmd_refresh(a):- """After a human resolved a bump: the worktree's commits (upstream..HEAD) become the series."""- root, wt = a.root, Path(a.worktree)- sha = resolve(a.to, root)- old = load(root)- commits = git('rev-list', '--reverse', f'{sha}..HEAD', cwd=wt).stdout.split()- if len(commits) > len(old): raise Fail('more commits than patches')- by_subject = {p.subject: p for p in old}- applied, used = [], set()- for c in commits:- subj = git('log', '-1', '--format=%s', c, cwd=wt).stdout.strip()- p = by_subject.get(subj)- if not p: raise Fail(f'commit "{subj}" matches no patch subject')- applied.append((p, c)); used.add(p.file)- landed = [p for p in old if p.file not in used]- say('landed upstream, dropped: ' + (', '.join(p.name for p in landed) or 'none'))- write_series(root, wt, applied, landed, old)- (root / '.upstream-ref').write_text(sha + '\n')- generate(wt)- install(root, wt, [p for p, _ in applied])- return 0---def slug(s):- return re.sub(r'[^a-z0-9]+', '-', s.lower()).strip('-')[:48].strip('-') or 'patch'---def cmd_export(a):- root = a.root- spec = a.rev if '..' in a.rev else f'{a.rev}^..{a.rev}'- existing = load(root) if (root / 'patches/series').exists() else []- pd = root / 'patches'; pd.mkdir(exist_ok=True)- n = max([int(re.match(r'(\d+)-', p.file).group(1)) for p in existing if re.match(r'(\d+)-', p.file)] or [0])- commits = git('rev-list', '--reverse', spec, cwd=root).stdout.split()- if not commits: raise Fail(f'no commits in {spec}')- series = (pd / 'series').read_text() if (pd / 'series').exists() else ''- if series and not series.endswith('\n'): series += '\n'- made = []- for c in commits:- text = git('format-patch', '--binary', '--zero-commit', '--no-signature', '--no-numbered', '--stdout', f'{c}^..{c}', '--', *VENDORED,- *(f':(exclude){o}' for o in (*OWN, *(g for g, _ in GENERATED))), cwd=root, binary=True).stdout.decode(errors='surrogateescape')- if not re.search(r'(?m)^diff --git ', text):- say(f'skipped {c[:10]}: no change under the vendored paths'); continue- files = sorted({f for m in re.finditer(r'(?m)^diff --git a/(\S+) b/(\S+)$', text) for f in m.groups()})- hits = chain_hits(files, root)- if hits:- raise Fail(f'{c[:10]} touches the shader chain or the tool pins ({", ".join(hits)}): patches must not change them (patches/README.md, Patch policy)')- head, sep, rest = text.partition('\n---\n')- add = []- for key, val in (('Upstream-Status', a.status), ('Reason', a.reason), ('Issue', a.issue)):- if not re.search(r'(?m)^' + key + ':', head): add.append(f'{key}: {val}')- if add: head = head.rstrip('\n') + '\n\n' + '\n'.join(add) + '\n'- text = head + sep + rest- subj = re.search(r'(?m)^Subject: (?:\[PATCH[^\]]*\] )?(.*)$', text).group(1)- n += 1- name = f'{n:04d}-{slug(subj)}.patch'- (pd / name).write_bytes(text.encode(errors='surrogateescape'))- series += name + '\n'; made.append(name)- (pd / 'series').write_text(series)- if made: (root / FORK_PATCHES).write_text(fork_patch_list(load(root))) # the new patch is carried from now on- for m in made: say('wrote patches/' + m)- if made and any('TODO' in x for x in (a.reason, a.issue)):- say('Fill in Reason and Issue in the new patch headers, then run scripts/patches.py check.')- return 0---def resolve_patch(patches, spec):- hits = [i for i, p in enumerate(patches) if spec in (p.name, p.file) or p.file.startswith(spec + '-')]- if len(hits) != 1: raise Fail(f'--into {spec}: {"no such patch" if not hits else "ambiguous"} (patches.py status lists them)')- return hits[0]---def owner_of(path, patches, into):- """Index of the patch that takes a changed file, or a reason string. A file some patch touches goes to the last one that- does (later patches then apply on top of it unchanged); a file no patch touches goes to the one patch that touches files- in its nearest folder, if there is exactly one."""- if into is not None: return into- own = [i for i, p in enumerate(patches) if path in p.files]- if own: return own[-1]- d = os.path.dirname(path)- while d:- near = sorted({i for i, p in enumerate(patches) if any(os.path.dirname(f) == d for f in p.files)})- if len(near) == 1: return near[0]- if near: return 'ambiguous: patches ' + ', '.join(patches[i].name for i in near) + f' all touch {d}/'- d = os.path.dirname(d)- return 'no patch touches its folder'---def cmd_absorb(a):- root = a.root- patches = load(root)- sha = resolve((root / '.upstream-ref').read_text().strip(), root)- into = resolve_patch(patches, a.into) if a.into else None- gen = {o for o, _ in GENERATED}- with Scratch(root, sha, a.tmp) as s:- applied, landed, conflicts = apply_series(s.dir, patches)- if conflicts or landed: raise Fail('the series does not apply cleanly to the pin; run `patches.py check` first')- generate(s.dir)- want = tree_files(s.dir)- have = local_files(root)- changed = [p for p in sorted(set(want) | set(have)) if want.get(p) != have.get(p)]- sel = []- for x in a.paths:- rel = os.path.relpath(os.path.realpath(x), root).replace(os.sep, '/')- if rel == '..' or rel.startswith('../'): raise Fail(f'{x} is outside the checkout')- sel.append('' if rel == '.' else rel)- if '' in sel: sel = [] # "." is the whole tree- if sel: changed = [p for p in changed if any(p == x or p.startswith(x + '/') for x in sel)]- changed = [p for p in changed if p not in gen]- if not changed:- say('absorb: nothing to fold in (the vendored files match pin + series)')- return cmd_check(a)- chain = chain_hits(changed, root)- if chain: raise Fail(f'{", ".join(chain)}: patches must not change the shader chain or the tool pins (patches/README.md, Patch policy)')- plan, unclear = {}, []- for f in changed:- o = owner_of(f, patches, into)- if isinstance(o, str): unclear.append(f' {f}: {o}')- else: plan.setdefault(o, []).append(f)- if unclear:- raise Fail('cannot tell which patch takes:\n' + '\n'.join(unclear) + '\nname it with `absorb --into <patch> <paths>` (patches.py status lists the patches)')- ident = ('-c', 'user.name=patches.py', '-c', 'user.email=patches@localhost', '-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false')- with Scratch(root, sha, a.tmp) as s:- wt, new = s.dir, {}- for i, p in enumerate(patches):- before = git('rev-parse', 'HEAD^{tree}', cwd=wt).stdout- r = am(wt, p)- if r.returncode:- raise Fail(f'{p.file} no longer applies after absorbing into an earlier patch ({(r.stderr or r.stdout).strip()[-300:]}); name a later patch with --into')- if git('rev-parse', 'HEAD^{tree}', cwd=wt).stdout == before:- raise Fail(f'{p.file} would be empty after absorbing into an earlier patch (its change is already there); name that patch with --into. No patch was changed')- if i not in plan: continue- for f in plan[i]:- if f in have:- (wt / f).parent.mkdir(parents=True, exist_ok=True)- (wt / f).write_bytes((root / f).read_bytes()); (wt / f).chmod(0o755 if have[f][0] == '100755' else 0o644)- git('add', '--', f, cwd=wt)- else: git('rm', '-q', '-f', '--', f, cwd=wt)- git(*ident, 'commit', '-q', '--amend', '--no-edit', '--allow-empty', cwd=wt)- if git('diff', '--quiet', 'HEAD^', 'HEAD', cwd=wt, check=False).returncode == 0:- raise Fail(f'absorbing {", ".join(plan[i])} would leave {p.file} empty (a full revert of that patch); delete the patch and its line in patches/series instead. No patch was changed')- new[i] = git('format-patch', '--binary', '--zero-commit', '--no-signature', '--no-numbered', '--stdout', '-1', 'HEAD', cwd=wt, binary=True).stdout- for i, text in new.items():- patches[i].path.write_bytes(text)- say(f'{patches[i].file}: absorbed ' + ', '.join(plan[i]))- return cmd_check(a)---def cmd_status(a):- patches = load(a.root)- rows = [('patch', 'upstream status', 'reason', 'age')]- for p in patches:- age = p.age_days()- rows.append((p.name, p.status, p.reason, f'{age}d' if age >= 0 else '?'))- w = [max(len(r[0]) for r in rows), 42]- for i, r in enumerate(rows):- st = r[1] if len(r[1]) <= 42 else r[1][:39] + '...'- reason = r[2] if len(r[2]) <= 70 else r[2][:67] + '...'- say(f'{r[0]:<{w[0]}} {st:<42} {r[3]:>5} {reason}')- if i == 0: say('-' * (sum(w) + 12))- c = {k: sum(1 for p in patches if p.kind == k) for k in KINDS}- say(f'\n{len(patches)} patches: ' + ', '.join(f'{v} {k}' for k, v in c.items()))- return 0---def main(argv=None):- ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)- ap.add_argument('--repo', default=str(REPO), help='the checkout (default: this script\'s)')- ap.add_argument('--tmp', help='folder for the scratch worktree (default $PATCHES_TMP, else the system temporary folder)')- sub = ap.add_subparsers(dest='cmd', required=True)- s = sub.add_parser('apply'); s.add_argument('--ref', help='upstream commit (default: .upstream-ref)'); s.set_defaults(f=cmd_apply)- s = sub.add_parser('bump'); s.add_argument('--to', required=True, help='the new upstream commit'); s.add_argument('--dry', action='store_true', help='change nothing, report every conflict'); s.set_defaults(f=cmd_bump)- s = sub.add_parser('refresh'); s.add_argument('worktree'); s.add_argument('--to', required=True); s.set_defaults(f=cmd_refresh)- s = sub.add_parser('export'); s.add_argument('rev', help='a commit or a range')- s.add_argument('--status', default='pending'); s.add_argument('--reason', default='TODO: why the fork carries this'); s.add_argument('--issue', default='TODO: LNPANDY/NX2Apple#<n>'); s.set_defaults(f=cmd_export)- s = sub.add_parser('absorb', help='fold direct edits of vendored files into the patches that touch them')- s.add_argument('paths', nargs='*', help='files or folders to fold in (default: every difference)')- s.add_argument('--into', help='the patch that takes new files no patch touches yet (name or number)'); s.set_defaults(f=cmd_absorb)- sub.add_parser('status').set_defaults(f=cmd_status)- sub.add_parser('check').set_defaults(f=cmd_check)- a = ap.parse_args(argv)- a.root = Path(a.repo).resolve()- try:- return a.f(a)- except Fail as e:- print(f'patches.py: {e}', file=sys.stderr)- return 2---if __name__ == '__main__':- sys.exit(main())+runpy.run_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, 'tools', 'patches.py'), run_name='__main__')diff --git a/tools/engine.py b/tools/engine.pynew file mode 100755index 00000000..26665d4f--- /dev/null+++ b/tools/engine.py@@ -0,0 +1,448 @@+#!/usr/bin/env python3+"""The engine in engine/: seedds/nxnative at the pin plus the patch queue, fetched and patched where it is needed+(LNPANDY/NX2Apple#214).++The repository keeps the pin (.upstream-ref) and the patches (patches/series, patches/*.patch). engine/ is a real git+repository, ignored by the outer one: upstream's commit at the pin (a shallow fetch of that one commit), then one commit per+patch (`git am -3`), then one commit with the generated files (the indexes of tools/patches.py's GENERATED and+dm/fork_patches.txt). A stamp in engine/.git records the pin and the series it was built from, so `sync` is a no-op while+neither changed.++Subcommands (Python 3.9+, stdlib and git):+ sync [--seed DIR] [--force] make engine/ match the pin and the series. A no-op when the stamp matches. Refuses to throw+ away commits or changes made in engine/ (export them first, or --force keeps them on a branch)+ stale exit 0 when engine/ matches the pin and the series, 1 when a sync is needed (prints why)+ hook for an agent's session start (.claude/settings.json): sync when stale, print one line, always exit 0+ export [REV] turn commits made in engine/ (default: everything after the last sync) into patches with the+ Upstream-Status / Reason / Issue header, and add them to patches/series+ status the patches (Upstream-Status, Reason, age) and the state of engine/+ check [--tree] headers valid, no patch touches the shader chain or the generated files, the series applies+ cleanly to the pin with no empty patch. --tree also compares the committed vendored tree with+ pin + series, as long as the repository still commits it (step 1 of #214)+ bump --to SHA|main [--dry] move the pin: re-apply the series on the new commit, drop the patches upstream has, write+ patches/ and .upstream-ref (the committed tree is tools/patches.py bump's job while it exists)+ refresh WORKTREE --to SHA after a conflicting bump was resolved by hand in WORKTREE: its commits become the series++The upstream URL is https://github.com/seedds/nxnative.git, or $NX2APPLE_ENGINE_URL. A seed (--seed or $NX2APPLE_ENGINE_SEED)+is a local git repository that holds the pin, such as the engine.git a release app carries: sync fetches from it first and+needs the network only for what the seed lacks. Scratch worktrees go to $PATCHES_TMP (or --tmp), else the system's temporary+folder.+"""+import argparse+import contextlib+import hashlib+import importlib+import io+import os+import re+import subprocess+import sys+import time+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+P = importlib.import_module('patches') # tools/patches.py: the headers, apply_series, generate, the chain rule++REPO = Path(__file__).resolve().parent.parent+UPSTREAM_URL = 'https://github.com/seedds/nxnative.git'+STAMP = 'nx2apple-stamp' # in engine/.git: invisible to `git status` in engine/+BRANCH = 'nx2apple' # the branch sync builds: the pin, the patches, the generated files+GENERATED_SUBJECT = 'NX2Apple: generated files (indexes, dm/fork_patches.txt)'+IDENT = ('-c', 'user.name=tools/engine.py', '-c', 'user.email=engine@localhost', '-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false')++Fail = P.Fail+say = P.say+++def git(*a, cwd, check=True, binary=False):+ return P.git(*a, cwd=cwd, check=check, binary=binary)+++def engine_dir(root):+ return root / 'engine'+++def pin(root):+ f = root / '.upstream-ref'+ if not f.is_file(): raise Fail(f'{f} is missing: this is not an NX2Apple checkout')+ sha = f.read_text().strip()+ if not re.fullmatch(r'[0-9a-f]{40}', sha): raise Fail(f'.upstream-ref must hold a full commit id (is: {sha!r})')+ return sha+++def stamp_key(root):+ """The digest of what engine/ is built from: the pin, and each patch of the series by name and content, in order.+ frontend/Sources/NSPortBuilder/Engine.swift and frontend-qt/nspb_qt/engine.py compute the same, so the launchers can+ tell a stale engine/ without starting Python."""+ h = hashlib.sha256()+ h.update(b'pin ' + pin(root).encode() + b'\n')+ for name in P.read_series(root):+ f = root / 'patches' / name+ if not f.is_file(): raise Fail(f'listed in patches/series but missing: {name}')+ h.update(b'patch ' + name.encode() + b'\n' + hashlib.sha256(f.read_bytes()).hexdigest().encode() + b'\n')+ return h.hexdigest()+++def read_stamp(eng):+ try: text = (eng / '.git' / STAMP).read_text()+ except OSError: return {}+ return dict(l.split(' ', 1) for l in text.splitlines() if ' ' in l)+++def write_stamp(eng, root, head, key=None):+ (eng / '.git' / STAMP).write_text(f'nx2apple-engine 1\npin {pin(root)}\nkey {key or stamp_key(root)}\nhead {head}\n')+++def is_repo(eng):+ return (eng / '.git').is_dir() and git('rev-parse', '--show-toplevel', cwd=eng, check=False).stdout.strip() == str(eng.resolve())+++def head(eng):+ r = git('rev-parse', '--verify', '--quiet', 'HEAD', cwd=eng, check=False)+ return r.stdout.strip() if r.returncode == 0 else ''+++def local_work(eng, st):+ """What sync would throw away: commits after the last sync, and changes to tracked or new files (ignored build products+ such as dm/host/gen are not work and survive a sync)."""+ out = []+ h = head(eng)+ if st.get('head') and h and h != st['head']:+ n = git('rev-list', '--count', f'{st["head"]}..{h}', cwd=eng, check=False).stdout.strip() or '?'+ out.append(f'{n} commit(s) after the last sync (HEAD {h[:12]})')+ dirty = git('status', '--porcelain', cwd=eng, check=False).stdout.splitlines()+ if dirty: out.append(f'{len(dirty)} changed or new file(s), e.g. {dirty[0][3:]}')+ return out+++def why_stale(root):+ """'' when engine/ matches the pin and the series, else the reason in a few words."""+ eng = engine_dir(root)+ if not is_repo(eng): return 'engine/ is missing'+ st = read_stamp(eng)+ if not st: return 'engine/ has no stamp (not made by tools/engine.py sync)'+ if st.get('key') != stamp_key(root):+ return 'the pin moved' if st.get('pin') != pin(root) else 'patches/ changed'+ if st.get('head') != head(eng): return 'engine/ has commits after the last sync'+ return ''+++# ---- getting the pinned commit ----++def have_commit(eng, sha):+ return git('cat-file', '-e', f'{sha}^{{commit}}', cwd=eng, check=False).returncode == 0+++def fetch(eng, sha, seed=None, url=None):+ """Bring the commit into engine/: from the seed first (no network), then from upstream, one commit deep."""+ if have_commit(eng, sha): return 'already here'+ seed = seed or os.environ.get('NX2APPLE_ENGINE_SEED')+ if seed and Path(seed).exists():+ git('fetch', '--quiet', '--no-tags', '--depth', '1', str(Path(seed).resolve()), sha, cwd=eng, check=False)+ if have_commit(eng, sha): return f'from the seed {seed}'+ # The seed is an older pin: fetch it anyway, so the shallow fetch below can send only what changed since.+ git('fetch', '--quiet', '--no-tags', '--depth', '1', str(Path(seed).resolve()), 'HEAD', cwd=eng, check=False)+ url = url or os.environ.get('NX2APPLE_ENGINE_URL') or UPSTREAM_URL+ r = git('fetch', '--quiet', '--no-tags', '--depth', '1', url, sha, cwd=eng, check=False)+ if r.returncode or not have_commit(eng, sha):+ err = (r.stderr or '').strip().splitlines()+ raise Fail(f'cannot fetch {sha[:12]} from {url}: {err[-1] if err else "unknown error"}\n'+ f' Offline? Connect and run `python3 tools/engine.py sync` again, or point --seed at a local copy that has the commit '+ f'(a release app carries one: NX2Apple.app/Contents/Resources/engine.git). Behind a mirror: set NX2APPLE_ENGINE_URL.')+ return f'from {url}'+++def ensure_repo(eng):+ if is_repo(eng): return+ if eng.exists() and any(eng.iterdir()):+ raise Fail(f'{eng} exists but is not a git repository made by tools/engine.py: move it away, then run sync again')+ eng.mkdir(parents=True, exist_ok=True)+ git('init', '--quiet', cwd=eng)+ git('config', 'advice.detachedHead', 'false', cwd=eng)+ git('remote', 'add', 'seedds', UPSTREAM_URL, cwd=eng, check=False) # for `git fetch seedds` and pull requests upstream+++# ---- sync ----++def build(root, eng, patches, sha):+ """Check out the pin on BRANCH (keeping ignored build products), apply the series, commit the generated files."""+ git('checkout', '--quiet', '--force', '-B', BRANCH, sha, cwd=eng)+ git('clean', '--quiet', '-fd', cwd=eng) # untracked files, not ignored ones (dm/host/gen and other build products stay)+ applied, landed, conflicts = P.apply_series(eng, patches)+ if conflicts:+ p, msg = conflicts[0]+ git('am', '--abort', cwd=eng, check=False)+ raise Fail(f'{p.file} does not apply to the pin {sha[:12]}\n Reason: {p.reason}\n Upstream-Status: {p.status}\n {msg}\n'+ f' The series is broken on this pin: see patches/README.md, "Bumping, and what a conflict is".')+ if landed:+ say('empty on the pin (upstream has them, `tools/engine.py bump` drops them): ' + ', '.join(p.file for p in landed))+ for out, tool in P.GENERATED:+ if (eng / tool).is_file():+ r = subprocess.run([sys.executable, str(eng / tool)], cwd=eng, capture_output=True, text=True, check=False)+ if r.returncode: raise Fail(f'{tool} failed on the patched tree: {(r.stderr.strip().splitlines() or [str(r.returncode)])[-1]}')+ (eng / P.FORK_PATCHES).write_text(P.fork_patch_list([p for p, _ in applied]))+ git('add', '--force', '--', P.FORK_PATCHES, *(o for o, _ in P.GENERATED if (eng / o).exists()), cwd=eng)+ git(*IDENT, 'commit', '--quiet', '--allow-empty', '-m', GENERATED_SUBJECT, cwd=eng)+ return applied, landed+++def cmd_sync(a):+ root = a.root+ eng = engine_dir(root)+ reason = why_stale(root)+ if not reason and not a.force:+ if not a.quiet: say(f'engine: up to date (upstream {pin(root)[:12]}, {len(P.read_series(root))} patches) in {eng}')+ return 0+ patches = P.load(root)+ ensure_repo(eng)+ st = read_stamp(eng)+ work = local_work(eng, st) if head(eng) else []+ if work and st and not a.force:+ raise Fail('engine/ has work a sync would throw away: ' + '; '.join(work) + '.\n'+ ' Turn commits into patches with `python3 tools/engine.py export`, then sync. Or keep them on a branch and '+ 'sync anyway: `python3 tools/engine.py sync --force`.')+ if head(eng) and (work or not st):+ keep = f'nx2apple-backup-{time.strftime("%Y%m%d-%H%M%S")}'+ git(*IDENT, 'stash', '--include-untracked', '--quiet', cwd=eng, check=False)+ git('branch', '--force', keep, 'HEAD', cwd=eng, check=False)+ say(f'engine: kept the previous HEAD on branch {keep} (and uncommitted changes in `git -C engine stash list`)')+ sha = pin(root)+ got = fetch(eng, sha, a.seed)+ say(f'engine: building {sha[:12]} + {len(patches)} patches ({reason or "forced"}; upstream commit {got})')+ applied, _ = build(root, eng, patches, sha)+ write_stamp(eng, root, head(eng))+ say(f'engine: ready, {len(applied)} patches on upstream {sha[:12]} in {eng}')+ return 0+++def cmd_stale(a):+ reason = why_stale(a.root)+ if reason:+ say(f'engine: stale ({reason}): run `python3 tools/engine.py sync`'); return 1+ if not a.quiet: say('engine: up to date')+ return 0+++def cmd_hook(a):+ """One line for a session's context, whatever happens: a failed sync must never block the session."""+ buf = io.StringIO()+ try:+ reason = why_stale(a.root)+ if reason:+ with contextlib.redirect_stdout(buf):+ cmd_sync(a)+ n = len(P.read_series(a.root))+ done = f'synced ({reason})' if reason else 'up to date'+ say(f'engine/: {done}, upstream {pin(a.root)[:12]} + {n} patches. The engine guide is engine/AGENTS.md. '+ f'Engine work: commit in engine/, then `python3 tools/engine.py export`.')+ except (Fail, OSError, ValueError, subprocess.SubprocessError) as e: # a failed fetch, a missing git: say it in one line+ msg = ' '.join(str(e).split())[:300]+ say(f'engine/: sync failed ({msg}). Run `python3 tools/engine.py sync` to see why. The committed tree (AGENTS.md, dm/) '+ f'is used until then.' if (a.root / 'AGENTS.md').is_file() else+ f'engine/: sync failed ({msg}). Run `python3 tools/engine.py sync` to see why.')+ return 0+++# ---- export ----++def cmd_export(a):+ root = a.root+ eng = engine_dir(root)+ if not is_repo(eng): raise Fail('engine/ is missing: run `python3 tools/engine.py sync`, commit your change in engine/, then export')+ st = read_stamp(eng)+ rev = a.rev or (f'{st["head"]}..HEAD' if st.get('head') else None)+ if not rev: raise Fail('engine/ has no stamp: name the commits, e.g. `tools/engine.py export HEAD~2..HEAD`')+ spec = rev if '..' in rev else f'{rev}^..{rev}'+ commits = git('rev-list', '--reverse', spec, cwd=eng).stdout.split()+ if not commits: raise Fail(f'no commits in {spec} (commit your change in engine/ first)')+ existing = P.load(root)+ pd = root / 'patches'+ n = max([int(m.group(1)) for p in existing for m in [re.match(r'(\d+)-', p.file)] if m] or [0])+ series = (pd / 'series').read_text()+ if series and not series.endswith('\n'): series += '\n'+ skip = {P.FORK_PATCHES, *(o for o, _ in P.GENERATED)}+ made = []+ for c in commits:+ if git('log', '-1', '--format=%s', c, cwd=eng).stdout.strip() == GENERATED_SUBJECT: continue+ text = git('format-patch', '--binary', '--zero-commit', '--no-signature', '--no-numbered', '--stdout', f'{c}^..{c}', '--', '.',+ *(f':(exclude){o}' for o in sorted(skip)), cwd=eng, binary=True).stdout.decode(errors='surrogateescape')+ if not re.search(r'(?m)^diff --git ', text):+ say(f'skipped {c[:10]}: it changes only generated files'); continue+ files = sorted({f for m in re.finditer(r'(?m)^diff --git a/(\S+) b/(\S+)$', text) for f in m.groups()})+ hits = P.chain_hits(files, eng)+ if hits:+ raise Fail(f'{c[:10]} touches the shader chain or the tool pins ({", ".join(hits)}): patches must not change them (patches/README.md, Patch policy)')+ head_, sep, rest = text.partition('\n---\n')+ add = [f'{k}: {v}' for k, v in (('Upstream-Status', a.status), ('Reason', a.reason), ('Issue', a.issue))+ if not re.search(r'(?m)^' + k + ':', head_)]+ if add: head_ = head_.rstrip('\n') + '\n\n' + '\n'.join(add) + '\n'+ text = head_ + sep + rest+ m = re.search(r'(?m)^Subject: (?:\[PATCH[^\]]*\] )?(.*)$', text)+ subj = m.group(1) if m else c[:10]+ n += 1+ name = f'{n:04d}-{P.slug(subj)}.patch'+ (pd / name).write_bytes(text.encode(errors='surrogateescape'))+ series += name + '\n'; made.append(name)+ (pd / 'series').write_text(series)+ for m in made: say('wrote patches/' + m)+ if made:+ # engine/ already holds these changes: record that, so the next sync rebuilds it from the series instead of refusing+ if st: write_stamp(eng, root, head(eng), key=st.get('key'))+ say('Fill in Reason and Issue in the new headers, then `python3 tools/engine.py check`. `python3 tools/engine.py sync` '+ 'rebuilds engine/ from the series (your commits stay on a backup branch).')+ return 0+++# ---- status, check ----++def cmd_status(a):+ P.cmd_status(a)+ eng = engine_dir(a.root)+ reason = why_stale(a.root)+ if not reason: state = 'up to date'+ else: state = f'stale ({reason}): run `python3 tools/engine.py sync`'+ say(f'engine/: {state}. Pin: upstream {pin(a.root)[:12]}')+ if is_repo(eng):+ work = local_work(eng, read_stamp(eng))+ if work: say('engine/ work not in patches/: ' + '; '.join(work) + ' (`tools/engine.py export`)')+ return 0+++def scratch_root(root):+ """The repository the scratch worktrees branch from: engine/, made (and fetched) on demand."""+ eng = engine_dir(root)+ ensure_repo(eng)+ return eng+++def cmd_check(a):+ root = a.root+ patches = P.load(root)+ bad = []+ pd = root / 'patches'+ stray = sorted(f.name for f in pd.glob('*.patch') if f.name not in {p.file for p in patches})+ if stray: bad.append('patch files not in patches/series: ' + ', '.join(stray))+ eng = scratch_root(root)+ sha = pin(root)+ fetch(eng, sha, a.seed)+ # The chain rule reads AGENTS.md at the pin plus the series; the pin's own copy is close enough for the globs.+ rules = eng if (eng / 'AGENTS.md').is_file() else root+ for p in patches:+ for m in p.problems(): bad.append(f'{p.file}: {m}')+ gen = sorted(f for f in p.files if f in {o for o, _ in P.GENERATED})+ if gen: bad.append(f'{p.file}: touches generated files ({", ".join(gen)}); sync regenerates them, so a patch must not carry them')+ hits = P.chain_hits(p.files, rules)+ if hits: bad.append(f'{p.file}: touches the shader chain or the tool pins, which patches must not change ({", ".join(hits)}); see patches/README.md, Patch policy')+ if bad:+ say('patch queue: invalid\n ' + '\n '.join(bad)); return 1+ with P.Scratch(eng, sha, a.tmp) as s:+ _, landed, conflicts = P.apply_series(s.dir, patches)+ if conflicts:+ p, msg = conflicts[0]+ say(f'patch queue: {p.file} does not apply to the pinned upstream {sha[:12]}\n Reason: {p.reason}\n Upstream-Status: {p.status}\n {msg}'); return 1+ if landed:+ say('patch queue: patches that are empty on the pinned upstream (it has them already; run bump to drop them): ' + ', '.join(p.file for p in landed)); return 1+ if a.tree and any((root / v).exists() for v in P.VENDORED):+ P.generate(s.dir)+ want = P.tree_files(s.dir)+ diff = P.diff_trees(want, P.local_files(root))+ have_list = (root / P.FORK_PATCHES).read_text() if (root / P.FORK_PATCHES).exists() else None+ if have_list != P.fork_patch_list(patches): diff.append(f' {P.FORK_PATCHES} is not the list of the series (run tools/patches.py apply)')+ if diff:+ say(f'patch queue: the committed vendored tree is not upstream {sha[:12]} plus the series ({len(diff)} differences):')+ say('\n'.join(diff[:40]) + ('\n ...' if len(diff) > 40 else ''))+ say(P.fix_hint(diff, patches)); return 1+ say(f'patch queue: ok. {len(patches)} patches apply cleanly to upstream {sha[:12]}, and the committed vendored tree matches ({len(want)} files)')+ return 0+ say(f'patch queue: ok. {len(patches)} patches apply cleanly to upstream {sha[:12]}')+ return 0+++# ---- bump, refresh ----++def resolve_target(eng, to, seed=None):+ if re.fullmatch(r'[0-9a-f]{40}', to): return to+ url = os.environ.get('NX2APPLE_ENGINE_URL') or UPSTREAM_URL+ r = git('ls-remote', url, to, cwd=eng, check=False)+ line = next((l for l in r.stdout.splitlines() if l.endswith((f'refs/heads/{to}', f'\t{to}'))), '')+ if not line: raise Fail(f'{to} is neither a full commit id nor a branch of {url}')+ return line.split()[0]+++def cmd_bump(a):+ root = a.root+ patches = P.load(root)+ eng = scratch_root(root)+ old = pin(root)+ fetch(eng, old, a.seed) # the old pin's blobs let `git am -3` merge three ways+ sha = resolve_target(eng, a.to)+ fetch(eng, sha)+ s = P.Scratch(eng, sha, a.tmp, keep=not a.dry)+ try:+ applied, landed, conflicts = P.apply_series(s.dir, patches, stop=not a.dry)+ P.report(old, sha, applied, landed, conflicts)+ if conflicts:+ if a.dry: s.close(); return 1+ p = conflicts[0][0]+ say(f'\nStopped at {p.file}. The conflict is left in {s.dir}:\n'+ f' resolve it there, `git am --continue`, apply the rest with `git am -3 <patches>`, then run\n'+ f' tools/engine.py refresh {s.dir} --to {sha[:12]}')+ return 1+ if a.dry: return 0+ P.write_series(root, s.dir, applied, landed, patches)+ (root / '.upstream-ref').write_text(sha + '\n')+ s.close()+ say('wrote patches/ and .upstream-ref; `python3 tools/engine.py sync` builds engine/ on the new pin')+ return 0+ except BaseException:+ s.close(); raise+++def cmd_refresh(a):+ root, wt = a.root, Path(a.worktree)+ sha = a.to if re.fullmatch(r'[0-9a-f]{40}', a.to) else git('rev-parse', '--verify', f'{a.to}^{{commit}}', cwd=wt).stdout.strip()+ old = P.load(root)+ commits = git('rev-list', '--reverse', f'{sha}..HEAD', cwd=wt).stdout.split()+ if len(commits) > len(old): raise Fail('more commits than patches')+ by_subject = {p.subject: p for p in old}+ applied, used = [], set()+ for c in commits:+ subj = git('log', '-1', '--format=%s', c, cwd=wt).stdout.strip()+ p = by_subject.get(subj)+ if not p: raise Fail(f'commit "{subj}" matches no patch subject')+ applied.append((p, c)); used.add(p.file)+ landed = [p for p in old if p.file not in used]+ say('landed upstream, dropped: ' + (', '.join(p.name for p in landed) or 'none'))+ P.write_series(root, wt, applied, landed, old)+ (root / '.upstream-ref').write_text(sha + '\n')+ say('wrote patches/ and .upstream-ref; `python3 tools/engine.py sync` builds engine/ on the new pin')+ return 0+++def main(argv=None):+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument('--repo', default=str(REPO), help="the checkout (default: this script's)")+ ap.add_argument('--tmp', help='folder for scratch worktrees (default $PATCHES_TMP, else the system temporary folder)')+ ap.add_argument('--seed', help='a local git repository holding the pin, tried before the network (default $NX2APPLE_ENGINE_SEED)')+ ap.add_argument('-q', '--quiet', action='store_true', help='print nothing when there is nothing to do')+ sub = ap.add_subparsers(dest='cmd', required=True)+ s = sub.add_parser('sync'); s.add_argument('--force', action='store_true', help='rebuild even when up to date; local work goes to a backup branch'); s.set_defaults(f=cmd_sync)+ sub.add_parser('stale').set_defaults(f=cmd_stale)+ s = sub.add_parser('hook'); s.set_defaults(f=cmd_hook, force=False, quiet=True)+ s = sub.add_parser('export'); s.add_argument('rev', nargs='?', help='a commit or a range in engine/ (default: everything after the last sync)')+ s.add_argument('--status', default='pending'); s.add_argument('--reason', default='TODO: why the fork carries this'); s.add_argument('--issue', default='TODO: LNPANDY/NX2Apple#<n>'); s.set_defaults(f=cmd_export)+ sub.add_parser('status').set_defaults(f=cmd_status)+ s = sub.add_parser('check'); s.add_argument('--tree', action='store_true', help='also compare the committed vendored tree (step 1 of #214)'); s.set_defaults(f=cmd_check)+ s = sub.add_parser('bump'); s.add_argument('--to', required=True, help='the new upstream commit, or a branch such as main'); s.add_argument('--dry', action='store_true'); s.set_defaults(f=cmd_bump)+ s = sub.add_parser('refresh'); s.add_argument('worktree'); s.add_argument('--to', required=True); s.set_defaults(f=cmd_refresh)+ a = ap.parse_args(argv)+ a.root = Path(a.repo).resolve()+ try:+ return a.f(a)+ except Fail as e:+ print(f'engine.py: {e}', file=sys.stderr)+ return 2+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tools/patches.py b/tools/patches.pynew file mode 100644index 00000000..a2af28ac--- /dev/null+++ b/tools/patches.py@@ -0,0 +1,609 @@+#!/usr/bin/env python3+"""The fork's patch queue on a pinned upstream (LNPANDY/NX2Apple#123), for the committed vendored tree.++tools/engine.py (LNPANDY/NX2Apple#214) builds the same tree in engine/ instead of committing it and reuses this module.++The vendored paths (dm/ scripts/ docs/ ref/ AGENTS.md) are generated, not hand-edited: seedds/nxnative at the commit+in .upstream-ref, plus the patches in patches/ applied in the order of patches/series with `git am -3`. Each patch is a+`git format-patch` file whose message carries a header:++ Upstream-Status: forwarded seedds/nxnative#475 | pending | fork-only | backport <sha>+ Reason: <one line>+ Issue: <repo>#<n>++Subcommands (Python 3.9+, stdlib and git):+ apply [--ref SHA] build the vendored tree from upstream at the ref plus the series (a temporary worktree), regenerate+ the generated indexes (GENERATED), copy it into the checkout, and write dm/fork_patches.txt+ bump --to SHA move the pin: re-apply the series on SHA, drop the patches that come out empty (upstream has them)+ and report them, refresh the rest; on a conflict stop, naming the patch, its Reason and its+ Upstream-Status, and leave the conflict in a worktree for a human. --dry changes nothing and+ reports every patch that would conflict+ export <commit|range> turn local commits on the vendored tree into patches with the header template+ absorb [paths...] fold changes made directly to vendored files into the patch that already touches each file (a new+ file goes to a patch only when the choice is unambiguous, else name it with --into), then run check+ status a table of the patches: Upstream-Status, Reason, age+ check the headers are valid, no patch touches the shader chain, the series applies to the pinned ref and+ reproduces the vendored tree of the checkout byte for byte (after+ the generated indexes are regenerated on it)++Scratch worktrees go under $PATCHES_TMP (or --tmp), else the system temporary folder.+"""+import argparse, fnmatch, os, re, shutil, subprocess, sys, tempfile, time+from pathlib import Path++REPO = Path(__file__).resolve().parent.parent+VENDORED = ('dm', 'scripts', 'docs', 'AGENTS.md', 'ref')+# Inside the vendored paths but not part of the generated tree: the forwarder that keeps the tool's old path working until the+# committed tree goes (LNPANDY/NX2Apple#214, step 2), and the list the tool writes. The tool itself lives in tools/ since #214.+OWN = ('scripts/patches.py', 'dm/fork_patches.txt')+FORK_PATCHES = 'dm/fork_patches.txt'+# Generated files inside the vendored paths: upstream's tests require each to equal what its tool writes from the tree+# (test_docs.py), and the tree differs from upstream's once the series is in, so a patch cannot carry them (they would+# conflict on every bump). apply, bump and check run the tools on the patched tree and commit the result; export and check+# keep patches away from these paths.+GENERATED = (('docs/agents/game-patches.md', 'dm/tools/docs_patches.py'),+ ('docs/agents/symptoms.md', 'dm/tools/docs_symptoms.py'))+KINDS = ('forwarded', 'pending', 'fork-only', 'backport')+# The shader chain and the tool pins (AGENTS.md: the DMSH_CHAIN paragraph names them; chain_paths() reads it).+# Used only when AGENTS.md has no such paragraph.+CHAIN_FALLBACK = ('dm/gfx/nvn/dmsh_chain.h', 'dm/gfx/tools/dmsh_*', 'dm/gfx/tools/Program.cs', 'dm/gfx/tools/ios_metal.py',+ 'dm/gfx/tools/dmsh_chain.lock', 'dm/gfx/tools/dmsh_xlate_bin*')+++class Fail(Exception):+ pass+++def git(*a, cwd=None, check=True, inp=None, binary=False):+ r = subprocess.run(['git', *a], cwd=cwd or REPO, input=inp, capture_output=True, text=not binary)+ if check and r.returncode:+ raise Fail(f'git {" ".join(a)} failed: {(r.stderr if not binary else r.stderr.decode(errors="replace")).strip()[-1500:]}')+ return r+++def say(*a):+ print(*a, flush=True)+++# ---- the series and the headers ----++class Patch:+ def __init__(self, path):+ self.path = path+ self.file = path.name+ self.name = re.sub(r'^\d+-', '', re.sub(r'\.patch$', '', self.file))+ text = path.read_text(encoding='utf-8', errors='replace')+ head = text.split('\n---\n', 1)[0]+ m = re.search(r'(?m)^Subject: (?:\[PATCH[^\]]*\] )?(.*(?:\n .*)*)', head)+ self.subject = self.decode_subject(m.group(1)) if m else ''+ self.date = (re.search(r'(?m)^Date: (.*)$', head) or [None, ''])[1]+ self.status = self.header(head, 'Upstream-Status')+ self.reason = self.header(head, 'Reason')+ self.issue = self.header(head, 'Issue')+ self.kind = (self.status.split() or [''])[0]+ self.files = sorted({f for m in re.finditer(r'(?m)^diff --git a/(\S+) b/(\S+)$', text) for f in m.groups()})++ @staticmethod+ def decode_subject(raw):+ """format-patch writes a subject with a non-ASCII character as RFC 2047 words (=?UTF-8?q?...?=), git log prints it decoded."""+ import email.errors+ import email.header+ joined = ' '.join(raw.split())+ try: return str(email.header.make_header(email.header.decode_header(joined)))+ except (email.errors.HeaderParseError, LookupError, UnicodeError): return joined++ @staticmethod+ def header(head, key):+ m = re.search(r'(?m)^' + key + r': *(.*)$', head)+ return m.group(1).strip() if m else ''++ def age_days(self):+ import email.utils+ try:+ return max(0, int((time.time() - email.utils.mktime_tz(email.utils.parsedate_tz(self.date))) // 86400))+ except Exception:+ return -1++ def problems(self):+ out = []+ if self.kind not in KINDS:+ out.append(f'Upstream-Status must start with one of {", ".join(KINDS)} (is: {self.status or "missing"})')+ elif self.kind == 'forwarded' and not re.search(r'#\d+', self.status):+ out.append('Upstream-Status: forwarded needs the upstream PR, e.g. forwarded seedds/nxnative#475')+ elif self.kind == 'backport' and not re.search(r'\b[0-9a-f]{7,40}\b', self.status):+ out.append('Upstream-Status: backport needs the upstream commit')+ for key, val in (('Reason', self.reason), ('Issue', self.issue)):+ if not val: out.append(f'{key} is missing')+ elif val.startswith('TODO'): out.append(f'{key} is still the export template ({val})')+ return out+++def read_series(root):+ s = root / 'patches/series'+ if not s.is_file(): raise Fail(f'{s} is missing')+ out = []+ for line in s.read_text().splitlines():+ line = line.split('#', 1)[0].strip()+ if line: out.append(line)+ return out+++def load(root):+ pd = root / 'patches'+ names = read_series(root)+ missing = [n for n in names if not (pd / n).is_file()]+ if missing: raise Fail('listed in patches/series but missing: ' + ', '.join(missing))+ if len(set(names)) != len(names): raise Fail('patches/series lists a patch twice')+ return [Patch(pd / n) for n in names]+++def chain_paths(root):+ """The globs of the shader chain, read from AGENTS.md's chain paragraph (the one naming DMSH_CHAIN)."""+ try: text = (root / 'AGENTS.md').read_text()+ except OSError: return list(CHAIN_FALLBACK)+ para = next((l for l in text.splitlines() if 'DMSH_CHAIN' in l and 'dm/gfx/tools/dmsh_' in l), None)+ found = []+ if para:+ for tok in re.findall(r'`([^`]+)`', para):+ if re.fullmatch(r'dm/gfx/(?:nvn|tools)/[\w./*-]+', tok): found.append(tok)+ elif re.fullmatch(r'[\w-]+\.(?:cs|py|lock)', tok) and not tok.startswith('dmsh_'): found.append('dm/gfx/tools/' + tok)+ elif tok == 'dmsh_chain.lock': found.append('dm/gfx/tools/' + tok)+ m = re.search(r'translator is `([^`]+)`', text)+ if m and re.fullmatch(r'dm/gfx/tools/[\w./-]+', m.group(1)): found.append(m.group(1) + '*')+ return sorted(set(found)) if len(found) >= 4 else list(CHAIN_FALLBACK)+++def chain_hits(files, root):+ globs = chain_paths(root)+ return sorted(f for f in files if any(fnmatch.fnmatchcase(f, g) for g in globs))+++# ---- applying the series in a scratch worktree ----++def resolve(ref, root):+ r = git('rev-parse', '--verify', '--quiet', f'{ref}^{{commit}}', cwd=root, check=False)+ if r.returncode:+ raise Fail(f'{ref} is not a commit in this repository: fetch it first (git fetch seedds {ref})')+ return r.stdout.strip()+++class Scratch:+ """A detached worktree of upstream at a commit, removed on exit unless kept."""+ def __init__(self, root, sha, tmp=None, keep=False):+ self.root, self.sha, self.keep = root, sha, keep+ self.base = Path(tempfile.mkdtemp(prefix='patches-', dir=tmp or os.environ.get('PATCHES_TMP') or None))+ self.dir = self.base / 'tree'+ git('worktree', 'add', '--detach', '-q', str(self.dir), sha, cwd=root)++ def close(self):+ if self.keep: return+ git('worktree', 'remove', '--force', str(self.dir), cwd=self.root, check=False)+ shutil.rmtree(self.base, ignore_errors=True)+ git('worktree', 'prune', cwd=self.root, check=False)++ def __enter__(self): return self+ def __exit__(self, *e): self.close()+++def am(wt, patch):+ return git('-c', 'user.name=patches.py', '-c', 'user.email=patches@localhost', '-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false',+ 'am', '-3', '--quiet', str(patch.path), cwd=wt, check=False)+++def apply_series(wt, patches, stop=True):+ """Apply each patch in turn. Returns (applied, landed, conflicts): applied = [(patch, commit)], landed = patches that came+ out empty (upstream has them), conflicts = [(patch, message)]. With stop, the first conflict stays in the worktree."""+ applied, landed, conflicts = [], [], []+ for p in patches:+ before = git('rev-parse', 'HEAD', cwd=wt).stdout.strip()+ r = am(wt, p)+ if r.returncode == 0:+ after = git('rev-parse', 'HEAD', cwd=wt).stdout.strip()+ if after == before or git('rev-parse', 'HEAD^{tree}', cwd=wt).stdout == git('rev-parse', before + '^{tree}', cwd=wt).stdout:+ git('reset', '--hard', '-q', before, cwd=wt) # the merge changed nothing: upstream has this patch+ landed.append(p); continue+ applied.append((p, after)); continue+ unmerged = git('ls-files', '-u', cwd=wt).stdout.strip()+ clean = git('diff', '--cached', '--quiet', cwd=wt, check=False).returncode == 0 and git('diff', '--quiet', cwd=wt, check=False).returncode == 0+ if not unmerged and clean and 'Patch failed' not in r.stderr and 'patch does not apply' not in r.stderr:+ git('am', '--skip', cwd=wt, check=False)+ landed.append(p); continue+ files = git('diff', '--name-only', '--diff-filter=U', cwd=wt, check=False).stdout.split()+ errs = [l for l in (r.stderr + r.stdout).splitlines() if re.match(r'(error|CONFLICT|Patch failed|Applying)', l)]+ conflicts.append((p, ('conflicting files: ' + ', '.join(files) + '\n' if files else '') + '\n'.join(errs[-6:])))+ if stop: break+ git('am', '--abort', cwd=wt, check=False)+ return applied, landed, conflicts+++def generate(wt):+ """Run the generators of GENERATED on the patched tree and commit what they changed (no commit when nothing changed)."""+ for out, tool in GENERATED:+ if not (wt / tool).is_file(): continue+ r = subprocess.run([sys.executable, str(wt / tool)], cwd=wt, capture_output=True, text=True)+ if r.returncode:+ raise Fail(f'{tool} failed on the patched tree: {(r.stderr.strip().splitlines() or [str(r.returncode)])[-1]}')+ if git('status', '--porcelain', '--', *(o for o, _ in GENERATED), cwd=wt).stdout.strip():+ git('add', '--', *(o for o, _ in GENERATED), cwd=wt)+ git('-c', 'user.name=patches.py', '-c', 'user.email=patches@localhost', '-c', 'commit.gpgsign=false',+ 'commit', '-q', '-m', 'Regenerated indexes: ' + ', '.join(o for o, _ in GENERATED), cwd=wt)+++def tree_files(wt):+ """{path: (mode, blob)} of the vendored paths at HEAD of a worktree, without the tool's own files."""+ out = git('ls-tree', '-r', '-z', 'HEAD', '--', *VENDORED, cwd=wt).stdout+ files = {}+ for rec in out.split('\0'):+ if not rec: continue+ meta, path = rec.split('\t', 1)+ mode, _, blob = meta.split()+ if path not in OWN: files[path] = (mode, blob)+ return files+++def fork_patch_list(patches):+ return ''.join(p.name + '\n' for p in patches)+++def local_files(root):+ """{path: (mode, blob)} of the checkout's working tree under the vendored paths: tracked files that still exist plus+ untracked ones git does not ignore, without the tool's own files."""+ r = git('ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', *VENDORED, cwd=root).stdout+ paths = sorted({p for p in r.split('\0') if p and p not in OWN and (root / p).is_file()})+ files = {}+ if paths:+ blobs = git('hash-object', '--stdin-paths', cwd=root, inp='\n'.join(paths) + '\n').stdout.split()+ for p, b in zip(paths, blobs):+ files[p] = ('100755' if os.access(root / p, os.X_OK) else '100644', b)+ return files+++def diff_trees(want, have):+ out = []+ for p in sorted(set(want) | set(have)):+ if p not in have: out.append(f' missing in the checkout: {p}')+ elif p not in want: out.append(f' not produced by the series: {p}')+ elif want[p] != have[p]:+ what = 'mode' if want[p][1] == have[p][1] else 'content'+ out.append(f' differs ({what}): {p}')+ return out+++def install(root, wt, patches):+ """Copy the generated vendored tree into the checkout: delete tracked vendored files it no longer has, write the rest."""+ want = tree_files(wt)+ for p in git('ls-files', '-z', '--', *VENDORED, cwd=root).stdout.split('\0'):+ if p and p not in want and p not in OWN and (root / p).exists(): (root / p).unlink()+ for p, (mode, blob) in want.items():+ dest = root / p+ dest.parent.mkdir(parents=True, exist_ok=True)+ if dest.is_symlink(): dest.unlink()+ dest.write_bytes((wt / p).read_bytes())+ dest.chmod(0o755 if mode == '100755' else 0o644)+ (root / FORK_PATCHES).write_text(fork_patch_list(patches))+++def fix_hint(diff, patches):+ """What a failing author runs. diff = the lines of diff_trees (plus the fork_patches.txt line)."""+ gen = {o for o, _ in GENERATED}+ paths = [m.group(1) for l in diff for m in [re.search(r': (\S+)$', l)] if m and not l.rstrip().endswith('(run patches.py apply)')]+ absorbable = [p for p in paths if p not in gen]+ lines = ['']+ for l in diff:+ m = re.search(r': (\S+)$', l)+ if not m or l.rstrip().endswith('(run patches.py apply)'): continue+ f = m.group(1)+ if f in gen: lines.append(f'{f} is generated: run `python3 tools/patches.py apply`')+ else: lines.append(f'{f} differs from pin+patches: run `python3 tools/patches.py absorb {f}` and commit patches/')+ if absorbable:+ lines.append('To fold all of them at once: `python3 tools/patches.py absorb`, then commit patches/ (and dm/fork_patches.txt if it changed).')+ lines.append('A new file goes to the patch that owns its folder; if that is ambiguous, absorb stops and asks for `--into <patch>` (see `tools/patches.py status`).')+ lines.append('A change that deserves its own patch (new Upstream-Status, Reason, Issue): commit it, then `python3 tools/patches.py export <commit>`. See patches/README.md.')+ else:+ lines.append('Run `python3 tools/patches.py apply` to rewrite the generated files, then commit. See patches/README.md.')+ return '\n'.join(lines)+++# ---- subcommands ----++def cmd_check(a):+ root = a.root+ patches = load(root)+ bad = []+ pd = root / 'patches'+ stray = sorted(f.name for f in pd.glob('*.patch') if f.name not in {p.file for p in patches})+ if stray: bad.append('patch files not in patches/series: ' + ', '.join(stray))+ for p in patches:+ for m in p.problems(): bad.append(f'{p.file}: {m}')+ gen = sorted(f for f in p.files if f in {o for o, _ in GENERATED})+ if gen: bad.append(f'{p.file}: touches generated files ({", ".join(gen)}); apply, bump and check regenerate them, so a patch must not carry them')+ hits = chain_hits(p.files, root)+ if hits: bad.append(f'{p.file}: touches the shader chain or the tool pins, which patches must not change ({", ".join(hits)}); see patches/README.md, Patch policy')+ if bad:+ say('patch queue: invalid\n ' + '\n '.join(bad)); return 1+ ref = (root / '.upstream-ref').read_text().strip()+ sha = resolve(ref, root)+ with Scratch(root, sha, a.tmp) as s:+ applied, landed, conflicts = apply_series(s.dir, patches)+ if conflicts:+ p, msg = conflicts[0]+ say(f'patch queue: {p.file} does not apply to the pinned upstream {sha[:12]}\n Reason: {p.reason}\n Upstream-Status: {p.status}\n {msg}'); return 1+ if landed:+ say('patch queue: patches that are empty on the pinned upstream (it has them already; run bump to drop them): ' + ', '.join(p.file for p in landed)); return 1+ generate(s.dir)+ want = tree_files(s.dir)+ diff = diff_trees(want, local_files(root))+ expect = fork_patch_list(patches)+ have_list = (root / FORK_PATCHES).read_text() if (root / FORK_PATCHES).exists() else None+ if have_list != expect: diff.append(f' {FORK_PATCHES} is not the list of the series (run patches.py apply)')+ if diff:+ say(f'patch queue: the vendored tree is not upstream {sha[:12]} plus the series ({len(diff)} differences):')+ say('\n'.join(diff[:40]) + ('\n ...' if len(diff) > 40 else ''))+ say(fix_hint(diff, patches))+ return 1+ say(f'patch queue: ok. {len(patches)} patches apply to upstream {sha[:12]} and give the committed vendored tree ({len(want)} files)')+ return 0+++def cmd_apply(a):+ root = a.root+ patches = load(root)+ ref = a.ref or (root / '.upstream-ref').read_text().strip()+ sha = resolve(ref, root)+ with Scratch(root, sha, a.tmp) as s:+ applied, landed, conflicts = apply_series(s.dir, patches)+ if conflicts:+ p, msg = conflicts[0]+ raise Fail(f'{p.file} does not apply to {sha[:12]}\n Reason: {p.reason}\n Upstream-Status: {p.status}\n {msg}')+ generate(s.dir)+ install(root, s.dir, [p for p, _ in applied])+ if landed: say('empty at this ref (upstream has them): ' + ', '.join(p.file for p in landed) + ' (patches.py bump drops them)')+ say(f'applied {len(applied)} patches to upstream {sha[:12]}; the vendored tree is written')+ return 0+++def cmd_bump(a):+ root = a.root+ patches = load(root)+ old = (root / '.upstream-ref').read_text().strip() if (root / '.upstream-ref').exists() else '?'+ sha = resolve(a.to, root)+ keep = not a.dry+ s = Scratch(root, sha, a.tmp, keep=keep)+ try:+ applied, landed, conflicts = apply_series(s.dir, patches, stop=not a.dry)+ report(old, sha, applied, landed, conflicts)+ if conflicts:+ if a.dry:+ s.close(); return 1+ p = conflicts[0][0]+ say(f'\nStopped at {p.file}. The conflict is left in {s.dir}:\n'+ f' resolve it there, `git am --continue`, apply the rest with `git am -3 <patches>`, then run\n'+ f' tools/patches.py refresh {s.dir} --to {sha[:12]}')+ return 1+ if a.dry:+ return 0+ write_series(root, s.dir, applied, landed, patches)+ (root / '.upstream-ref').write_text(sha + '\n')+ generate(s.dir)+ install(root, s.dir, [p for p, _ in applied])+ s.close()+ return 0+ except BaseException:+ s.close()+ raise+++def report(old, sha, applied, landed, conflicts):+ say(f'bump {old[:12]} -> {sha[:12]}')+ say(f' applied cleanly ({len(applied)}): ' + (', '.join(p.name for p, _ in applied) or 'none'))+ say(f' landed upstream, dropped ({len(landed)}): ' + (', '.join(p.name for p in landed) or 'none'))+ say(f' conflicts ({len(conflicts)}):' + ('' if conflicts else ' none'))+ for p, msg in conflicts:+ say(f' {p.file}\n Reason: {p.reason}\n Upstream-Status: {p.status}')+ for l in msg.splitlines(): say(' | ' + l)+++def write_series(root, wt, applied, landed, patches):+ """Rewrite patches/ from the rebased commits: the kept patches refreshed, the landed ones deleted."""+ pd = root / 'patches'+ for p, commit in applied:+ text = git('format-patch', '--binary', '--zero-commit', '--no-signature', '--no-numbered', '--stdout', '-1', commit, cwd=wt, binary=True).stdout+ p.path.write_bytes(text)+ for p in landed: p.path.unlink()+ keep = {p.file for p, _ in applied}+ lines = [l for l in (pd / 'series').read_text().splitlines()]+ out = [l for l in lines if l.split('#', 1)[0].strip() == '' or l.split('#', 1)[0].strip() in keep]+ (pd / 'series').write_text('\n'.join(out) + '\n')+++def cmd_refresh(a):+ """After a human resolved a bump: the worktree's commits (upstream..HEAD) become the series."""+ root, wt = a.root, Path(a.worktree)+ sha = resolve(a.to, root)+ old = load(root)+ commits = git('rev-list', '--reverse', f'{sha}..HEAD', cwd=wt).stdout.split()+ if len(commits) > len(old): raise Fail('more commits than patches')+ by_subject = {p.subject: p for p in old}+ applied, used = [], set()+ for c in commits:+ subj = git('log', '-1', '--format=%s', c, cwd=wt).stdout.strip()+ p = by_subject.get(subj)+ if not p: raise Fail(f'commit "{subj}" matches no patch subject')+ applied.append((p, c)); used.add(p.file)+ landed = [p for p in old if p.file not in used]+ say('landed upstream, dropped: ' + (', '.join(p.name for p in landed) or 'none'))+ write_series(root, wt, applied, landed, old)+ (root / '.upstream-ref').write_text(sha + '\n')+ generate(wt)+ install(root, wt, [p for p, _ in applied])+ return 0+++def slug(s):+ return re.sub(r'[^a-z0-9]+', '-', s.lower()).strip('-')[:48].strip('-') or 'patch'+++def cmd_export(a):+ root = a.root+ spec = a.rev if '..' in a.rev else f'{a.rev}^..{a.rev}'+ existing = load(root) if (root / 'patches/series').exists() else []+ pd = root / 'patches'; pd.mkdir(exist_ok=True)+ n = max([int(re.match(r'(\d+)-', p.file).group(1)) for p in existing if re.match(r'(\d+)-', p.file)] or [0])+ commits = git('rev-list', '--reverse', spec, cwd=root).stdout.split()+ if not commits: raise Fail(f'no commits in {spec}')+ series = (pd / 'series').read_text() if (pd / 'series').exists() else ''+ if series and not series.endswith('\n'): series += '\n'+ made = []+ for c in commits:+ text = git('format-patch', '--binary', '--zero-commit', '--no-signature', '--no-numbered', '--stdout', f'{c}^..{c}', '--', *VENDORED,+ *(f':(exclude){o}' for o in (*OWN, *(g for g, _ in GENERATED))), cwd=root, binary=True).stdout.decode(errors='surrogateescape')+ if not re.search(r'(?m)^diff --git ', text):+ say(f'skipped {c[:10]}: no change under the vendored paths'); continue+ files = sorted({f for m in re.finditer(r'(?m)^diff --git a/(\S+) b/(\S+)$', text) for f in m.groups()})+ hits = chain_hits(files, root)+ if hits:+ raise Fail(f'{c[:10]} touches the shader chain or the tool pins ({", ".join(hits)}): patches must not change them (patches/README.md, Patch policy)')+ head, sep, rest = text.partition('\n---\n')+ add = []+ for key, val in (('Upstream-Status', a.status), ('Reason', a.reason), ('Issue', a.issue)):+ if not re.search(r'(?m)^' + key + ':', head): add.append(f'{key}: {val}')+ if add: head = head.rstrip('\n') + '\n\n' + '\n'.join(add) + '\n'+ text = head + sep + rest+ subj = re.search(r'(?m)^Subject: (?:\[PATCH[^\]]*\] )?(.*)$', text).group(1)+ n += 1+ name = f'{n:04d}-{slug(subj)}.patch'+ (pd / name).write_bytes(text.encode(errors='surrogateescape'))+ series += name + '\n'; made.append(name)+ (pd / 'series').write_text(series)+ if made: (root / FORK_PATCHES).write_text(fork_patch_list(load(root))) # the new patch is carried from now on+ for m in made: say('wrote patches/' + m)+ if made and any('TODO' in x for x in (a.reason, a.issue)):+ say('Fill in Reason and Issue in the new patch headers, then run tools/patches.py check.')+ return 0+++def resolve_patch(patches, spec):+ hits = [i for i, p in enumerate(patches) if spec in (p.name, p.file) or p.file.startswith(spec + '-')]+ if len(hits) != 1: raise Fail(f'--into {spec}: {"no such patch" if not hits else "ambiguous"} (patches.py status lists them)')+ return hits[0]+++def owner_of(path, patches, into):+ """Index of the patch that takes a changed file, or a reason string. A file some patch touches goes to the last one that+ does (later patches then apply on top of it unchanged); a file no patch touches goes to the one patch that touches files+ in its nearest folder, if there is exactly one."""+ if into is not None: return into+ own = [i for i, p in enumerate(patches) if path in p.files]+ if own: return own[-1]+ d = os.path.dirname(path)+ while d:+ near = sorted({i for i, p in enumerate(patches) if any(os.path.dirname(f) == d for f in p.files)})+ if len(near) == 1: return near[0]+ if near: return 'ambiguous: patches ' + ', '.join(patches[i].name for i in near) + f' all touch {d}/'+ d = os.path.dirname(d)+ return 'no patch touches its folder'+++def cmd_absorb(a):+ root = a.root+ patches = load(root)+ sha = resolve((root / '.upstream-ref').read_text().strip(), root)+ into = resolve_patch(patches, a.into) if a.into else None+ gen = {o for o, _ in GENERATED}+ with Scratch(root, sha, a.tmp) as s:+ applied, landed, conflicts = apply_series(s.dir, patches)+ if conflicts or landed: raise Fail('the series does not apply cleanly to the pin; run `patches.py check` first')+ generate(s.dir)+ want = tree_files(s.dir)+ have = local_files(root)+ changed = [p for p in sorted(set(want) | set(have)) if want.get(p) != have.get(p)]+ sel = []+ for x in a.paths:+ rel = os.path.relpath(os.path.realpath(x), root).replace(os.sep, '/')+ if rel == '..' or rel.startswith('../'): raise Fail(f'{x} is outside the checkout')+ sel.append('' if rel == '.' else rel)+ if '' in sel: sel = [] # "." is the whole tree+ if sel: changed = [p for p in changed if any(p == x or p.startswith(x + '/') for x in sel)]+ changed = [p for p in changed if p not in gen]+ if not changed:+ say('absorb: nothing to fold in (the vendored files match pin + series)')+ return cmd_check(a)+ chain = chain_hits(changed, root)+ if chain: raise Fail(f'{", ".join(chain)}: patches must not change the shader chain or the tool pins (patches/README.md, Patch policy)')+ plan, unclear = {}, []+ for f in changed:+ o = owner_of(f, patches, into)+ if isinstance(o, str): unclear.append(f' {f}: {o}')+ else: plan.setdefault(o, []).append(f)+ if unclear:+ raise Fail('cannot tell which patch takes:\n' + '\n'.join(unclear) + '\nname it with `absorb --into <patch> <paths>` (patches.py status lists the patches)')+ ident = ('-c', 'user.name=patches.py', '-c', 'user.email=patches@localhost', '-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false')+ with Scratch(root, sha, a.tmp) as s:+ wt, new = s.dir, {}+ for i, p in enumerate(patches):+ before = git('rev-parse', 'HEAD^{tree}', cwd=wt).stdout+ r = am(wt, p)+ if r.returncode:+ raise Fail(f'{p.file} no longer applies after absorbing into an earlier patch ({(r.stderr or r.stdout).strip()[-300:]}); name a later patch with --into')+ if git('rev-parse', 'HEAD^{tree}', cwd=wt).stdout == before:+ raise Fail(f'{p.file} would be empty after absorbing into an earlier patch (its change is already there); name that patch with --into. No patch was changed')+ if i not in plan: continue+ for f in plan[i]:+ if f in have:+ (wt / f).parent.mkdir(parents=True, exist_ok=True)+ (wt / f).write_bytes((root / f).read_bytes()); (wt / f).chmod(0o755 if have[f][0] == '100755' else 0o644)+ git('add', '--', f, cwd=wt)+ else: git('rm', '-q', '-f', '--', f, cwd=wt)+ git(*ident, 'commit', '-q', '--amend', '--no-edit', '--allow-empty', cwd=wt)+ if git('diff', '--quiet', 'HEAD^', 'HEAD', cwd=wt, check=False).returncode == 0:+ raise Fail(f'absorbing {", ".join(plan[i])} would leave {p.file} empty (a full revert of that patch); delete the patch and its line in patches/series instead. No patch was changed')+ new[i] = git('format-patch', '--binary', '--zero-commit', '--no-signature', '--no-numbered', '--stdout', '-1', 'HEAD', cwd=wt, binary=True).stdout+ for i, text in new.items():+ patches[i].path.write_bytes(text)+ say(f'{patches[i].file}: absorbed ' + ', '.join(plan[i]))+ return cmd_check(a)+++def cmd_status(a):+ patches = load(a.root)+ rows = [('patch', 'upstream status', 'reason', 'age')]+ for p in patches:+ age = p.age_days()+ rows.append((p.name, p.status, p.reason, f'{age}d' if age >= 0 else '?'))+ w = [max(len(r[0]) for r in rows), 42]+ for i, r in enumerate(rows):+ st = r[1] if len(r[1]) <= 42 else r[1][:39] + '...'+ reason = r[2] if len(r[2]) <= 70 else r[2][:67] + '...'+ say(f'{r[0]:<{w[0]}} {st:<42} {r[3]:>5} {reason}')+ if i == 0: say('-' * (sum(w) + 12))+ c = {k: sum(1 for p in patches if p.kind == k) for k in KINDS}+ say(f'\n{len(patches)} patches: ' + ', '.join(f'{v} {k}' for k, v in c.items()))+ return 0+++def main(argv=None):+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument('--repo', default=str(REPO), help='the checkout (default: this script\'s)')+ ap.add_argument('--tmp', help='folder for the scratch worktree (default $PATCHES_TMP, else the system temporary folder)')+ sub = ap.add_subparsers(dest='cmd', required=True)+ s = sub.add_parser('apply'); s.add_argument('--ref', help='upstream commit (default: .upstream-ref)'); s.set_defaults(f=cmd_apply)+ s = sub.add_parser('bump'); s.add_argument('--to', required=True, help='the new upstream commit'); s.add_argument('--dry', action='store_true', help='change nothing, report every conflict'); s.set_defaults(f=cmd_bump)+ s = sub.add_parser('refresh'); s.add_argument('worktree'); s.add_argument('--to', required=True); s.set_defaults(f=cmd_refresh)+ s = sub.add_parser('export'); s.add_argument('rev', help='a commit or a range')+ s.add_argument('--status', default='pending'); s.add_argument('--reason', default='TODO: why the fork carries this'); s.add_argument('--issue', default='TODO: LNPANDY/NX2Apple#<n>'); s.set_defaults(f=cmd_export)+ s = sub.add_parser('absorb', help='fold direct edits of vendored files into the patches that touch them')+ s.add_argument('paths', nargs='*', help='files or folders to fold in (default: every difference)')+ s.add_argument('--into', help='the patch that takes new files no patch touches yet (name or number)'); s.set_defaults(f=cmd_absorb)+ sub.add_parser('status').set_defaults(f=cmd_status)+ sub.add_parser('check').set_defaults(f=cmd_check)+ a = ap.parse_args(argv)+ a.root = Path(a.repo).resolve()+ try:+ return a.f(a)+ except Fail as e:+ print(f'patches.py: {e}', file=sys.stderr)+ return 2+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tools/tests/test_engine.py b/tools/tests/test_engine.pynew file mode 100644index 00000000..141d8536--- /dev/null+++ b/tools/tests/test_engine.py@@ -0,0 +1,265 @@+"""tools/engine.py on fixture repositories (LNPANDY/NX2Apple#214): sync builds engine/ from the pin and the series, one commit per+patch, and is a no-op while nothing changed; work made in engine/ is never thrown away; export turns it into a patch; offline and+broken cases name the fix; check and bump work on engine/; ripgrep still searches engine/. No network: upstream is a local+repository, reached through NX2APPLE_ENGINE_URL."""+import importlib+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]+TOOLS = REPO / 'tools'+SRC = REPO / 'engine' if (REPO / 'engine/AGENTS.md').is_file() else REPO+sys.path.insert(0, str(TOOLS))+E = importlib.import_module('engine')++BASE_ENV = dict(os.environ, GIT_AUTHOR_NAME='t', GIT_AUTHOR_EMAIL='[email protected]', GIT_COMMITTER_NAME='t', GIT_COMMITTER_EMAIL='[email protected]',+ GIT_CONFIG_GLOBAL='/dev/null', GIT_CONFIG_SYSTEM='/dev/null')+BASE_ENV.pop('NX2APPLE_ENGINE_SEED', None)++HEADER = 'Upstream-Status: forwarded seedds/nxnative#475\nReason: the fork needs line 2\nIssue: LNPANDY/NX2Apple#1\n'+++def git(cwd, *a, check=True):+ r = subprocess.run(['git', '-c', 'commit.gpgsign=false', *a], cwd=cwd, capture_output=True, text=True, env=BASE_ENV, check=False)+ if check and r.returncode: raise AssertionError(f'git {a}: {r.stderr}')+ return r.stdout.strip()+++class Fixture(unittest.TestCase):+ """up/: upstream with one commit. repo/: the fork (tools/, .upstream-ref, patches/ with one patch made from a commit on up)."""+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix='test-engine-'))+ self.addCleanup(shutil.rmtree, self.tmp, True)+ self.up = self.tmp / 'up'; self.up.mkdir()+ git(self.up, 'init', '-q', '-b', 'main')+ self.wu('dm/a.c', 'line1\nline2\nline3\nline4\nline5\nline6\nline7\n')+ self.wu('dm/b.c', 'b1\nb2\n')+ self.wu('.gitignore', 'dm/host/gen/\n')+ shutil.copy(SRC / 'AGENTS.md', self.up / 'AGENTS.md')+ git(self.up, 'add', '-A'); git(self.up, 'commit', '-q', '-m', 'upstream 1')+ self.up1 = git(self.up, 'rev-parse', 'HEAD')+ self.r = self.tmp / 'repo'; self.r.mkdir()+ git(self.r, 'init', '-q', '-b', 'main')+ (self.r / 'tools').mkdir()+ for f in ('engine.py', 'patches.py'): shutil.copy(TOOLS / f, self.r / 'tools' / f)+ shutil.copy(REPO / '.ignore', self.r / '.ignore')+ (self.r / '.gitignore').write_text('/engine/\n__pycache__/\n')+ (self.r / '.upstream-ref').write_text(self.up1 + '\n')+ (self.r / 'patches').mkdir()+ self.add_patch('0001-line-2.patch', 'dm/a.c', 'line1\nline2 fork\nline3\nline4\nline5\nline6\nline7\n', 'Make line 2 the fork\'s')+ git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', 'fork')+ self.env = dict(BASE_ENV, NX2APPLE_ENGINE_URL=str(self.up), PATCHES_TMP=str(self.tmp))+ self.eng = self.r / 'engine'++ def wu(self, path, text, root=None):+ f = (root or self.up) / path; f.parent.mkdir(parents=True, exist_ok=True); f.write_text(text)++ def add_patch(self, name, path, text, subject, header=HEADER, base=None):+ """A patch made on a scratch clone of upstream at base (default: the pin), appended to the series."""+ wt = self.tmp / 'mk'+ shutil.rmtree(wt, True)+ git(self.tmp, 'clone', '-q', str(self.up), str(wt))+ git(wt, 'checkout', '-q', base or self.up1)+ self.wu(path, text, wt)+ git(wt, 'add', '-A'); git(wt, 'commit', '-q', '-m', f'{subject}\n\n{header}')+ patch = git(wt, 'format-patch', '--zero-commit', '--no-signature', '--stdout', '-1', 'HEAD') + '\n'+ (self.r / 'patches' / name).write_text(patch)+ s = self.r / 'patches/series'+ s.write_text((s.read_text() if s.exists() else '# order\n') + name + '\n')++ def tool(self, *a, expect=0, env=None):+ r = subprocess.run([sys.executable, str(self.r / 'tools/engine.py'), *a], cwd=self.r, capture_output=True, text=True, env=env or self.env, check=False)+ if expect is not None: self.assertEqual(r.returncode, expect, r.stdout + r.stderr)+ return r.stdout + r.stderr++ def up_commit(self, path, text, msg):+ self.wu(path, text); git(self.up, 'add', '-A'); git(self.up, 'commit', '-q', '-m', msg)+ return git(self.up, 'rev-parse', 'HEAD')+++class Sync(Fixture):+ def test_sync_builds_the_pin_plus_one_commit_per_patch_and_the_generated_files(self):+ out = self.tool('sync')+ self.assertIn('ready, 1 patches', out)+ self.assertEqual((self.eng / 'dm/a.c').read_text().splitlines()[1], 'line2 fork')+ log = git(self.eng, 'log', '--format=%s').splitlines()+ self.assertEqual(log, [E.GENERATED_SUBJECT, "Make line 2 the fork's", 'upstream 1'])+ self.assertEqual((self.eng / 'dm/fork_patches.txt').read_text(), 'line-2\n')+ self.assertEqual(git(self.eng, 'rev-parse', '--abbrev-ref', 'HEAD'), 'nx2apple')+ self.assertEqual(git(self.eng, 'status', '--porcelain'), '')++ def test_a_second_sync_is_a_no_op_and_quiet_prints_nothing(self):+ self.tool('sync')+ before = git(self.eng, 'rev-parse', 'HEAD')+ self.assertIn('up to date', self.tool('sync'))+ self.assertEqual(self.tool('--quiet', 'sync'), '')+ self.assertEqual(before, git(self.eng, 'rev-parse', 'HEAD'))+ self.tool('stale', expect=0)++ def test_the_outer_repository_does_not_see_engine(self):+ self.tool('sync')+ self.assertEqual(git(self.r, 'status', '--porcelain'), '')++ def test_a_changed_series_or_pin_makes_it_stale_and_sync_rebuilds(self):+ self.tool('sync')+ self.add_patch('0002-b.patch', 'dm/b.c', 'b1\nb2 fork\n', 'Change b2', header=HEADER.replace('#1', '#2'))+ self.assertIn('patches/ changed', self.tool('stale', expect=1))+ self.tool('sync')+ self.assertEqual((self.eng / 'dm/b.c').read_text(), 'b1\nb2 fork\n')+ up2 = self.up_commit('dm/c.c', 'c\n', 'upstream 2')+ (self.r / '.upstream-ref').write_text(up2 + '\n')+ self.assertIn('the pin moved', self.tool('stale', expect=1))+ self.tool('sync')+ self.assertTrue((self.eng / 'dm/c.c').is_file())+ self.assertEqual(git(self.eng, 'log', '--format=%s').splitlines()[-1], 'upstream 2')++ def test_ignored_build_products_survive_a_rebuild(self):+ self.tool('sync')+ self.wu('dm/host/gen/cache.o', 'x', self.eng)+ self.add_patch('0002-b.patch', 'dm/b.c', 'b1\nb2 fork\n', 'Change b2', header=HEADER.replace('#1', '#2'))+ self.tool('sync')+ self.assertTrue((self.eng / 'dm/host/gen/cache.o').is_file())++ def test_a_patch_that_does_not_apply_names_itself_and_its_reason(self):+ self.add_patch('0002-conflict.patch', 'dm/a.c', 'other\n', 'Conflicting', header=HEADER.replace('the fork needs line 2', 'a reason to show'))+ out = self.tool('sync', expect=2)+ self.assertIn('0002-conflict.patch does not apply', out); self.assertIn('a reason to show', out)+ self.assertFalse((self.eng / '.git' / 'rebase-apply').exists())++ def test_offline_names_the_fix_and_a_seed_needs_no_network(self):+ offline = dict(self.env, NX2APPLE_ENGINE_URL=str(self.tmp / 'nowhere'))+ out = self.tool('sync', expect=2, env=offline)+ self.assertIn('cannot fetch', out); self.assertIn('Offline?', out); self.assertIn('--seed', out)+ seed = self.tmp / 'seed.git'+ git(self.tmp, 'clone', '-q', '--bare', '--depth', '1', 'file://' + str(self.up), str(seed))+ out = self.tool('--seed', str(seed), 'sync', env=offline)+ self.assertIn('from the seed', out)+ self.tool('stale')+++class Hook(Fixture):+ def test_the_session_hook_syncs_and_prints_one_line(self):+ out = self.tool('hook')+ self.assertEqual(len(out.strip().splitlines()), 1, out); self.assertIn('synced (engine/ is missing)', out)+ self.assertTrue((self.eng / 'dm/a.c').is_file())+ out = self.tool('hook')+ self.assertEqual(len(out.strip().splitlines()), 1, out); self.assertIn('up to date', out)++ def test_a_failed_sync_never_fails_the_hook(self):+ out = self.tool('hook', expect=0, env=dict(self.env, NX2APPLE_ENGINE_URL=str(self.tmp / 'nowhere')))+ self.assertEqual(len(out.strip().splitlines()), 1, out); self.assertIn('sync failed', out)+++class LocalWork(Fixture):+ def commit_in_engine(self, path='dm/b.c', text='b1\nb2 engine\n', msg='Change b2 in engine'):+ self.wu(path, text, self.eng); git(self.eng, 'add', '-A'); git(self.eng, 'commit', '-q', '-m', msg)++ def test_sync_refuses_to_drop_a_commit_and_names_export(self):+ self.tool('sync')+ self.commit_in_engine()+ self.add_patch('0002-b.patch', 'dm/b.c', 'b1\nb2 fork\n', 'Unrelated', header=HEADER.replace('#1', '#2'))+ out = self.tool('sync', expect=2)+ self.assertIn('export', out); self.assertIn('1 commit(s)', out)+ self.assertEqual((self.eng / 'dm/b.c').read_text(), 'b1\nb2 engine\n')++ def test_sync_refuses_to_drop_an_uncommitted_change(self):+ self.tool('sync')+ self.wu('dm/b.c', 'dirty\n', self.eng)+ self.add_patch('0002-b.patch', 'dm/b.c', 'b1\nb2 fork\n', 'Unrelated', header=HEADER.replace('#1', '#2'))+ self.assertIn('changed or new file', self.tool('sync', expect=2))++ def test_force_keeps_the_work_on_a_backup_branch(self):+ self.tool('sync')+ self.commit_in_engine()+ out = self.tool('sync', '--force')+ self.assertIn('nx2apple-backup-', out)+ branch = next(b.strip() for b in git(self.eng, 'branch', '--format=%(refname:short)').splitlines() if b.startswith('nx2apple-backup-'))+ self.assertEqual(git(self.eng, 'log', '-1', '--format=%s', branch), 'Change b2 in engine')+ self.assertEqual((self.eng / 'dm/b.c').read_text(), 'b1\nb2\n')++ def test_export_writes_the_header_and_the_next_sync_rebuilds_with_it(self):+ self.tool('sync')+ self.commit_in_engine()+ out = self.tool('export', '--reason', 'r', '--issue', 'LNPANDY/NX2Apple#9')+ self.assertIn('wrote patches/0002-change-b2-in-engine.patch', out)+ text = (self.r / 'patches/0002-change-b2-in-engine.patch').read_text()+ for k in ('Upstream-Status: pending', 'Reason: r', 'Issue: LNPANDY/NX2Apple#9', 'Subject: [PATCH] Change b2 in engine'): self.assertIn(k, text)+ self.assertNotIn('fork_patches.txt', text)+ self.assertIn('0002-change-b2-in-engine.patch', (self.r / 'patches/series').read_text())+ self.tool('sync')+ self.assertEqual((self.eng / 'dm/b.c').read_text(), 'b1\nb2 engine\n')+ self.assertEqual((self.eng / 'dm/fork_patches.txt').read_text(), 'line-2\nchange-b2-in-engine\n')+ self.assertIn('ok.', self.tool('check'))++ def test_export_refuses_the_shader_chain(self):+ self.tool('sync')+ self.commit_in_engine('dm/gfx/nvn/dmsh_chain.h', 'x\n', 'Touch the chain')+ out = self.tool('export', expect=2)+ self.assertIn('shader chain', out)+ self.assertFalse((self.r / 'patches/0002-touch-the-chain.patch').exists())+++class CheckAndBump(Fixture):+ def test_check_passes_and_rejects_an_incomplete_header(self):+ self.assertIn('apply cleanly', self.tool('check'))+ self.add_patch('0002-b.patch', 'dm/b.c', 'b1\nb2 fork\n', 'No header', header='Upstream-Status: pending\n')+ out = self.tool('check', expect=1)+ self.assertIn('0002-b.patch: Reason is missing', out)++ def test_check_tree_compares_a_committed_vendored_tree(self):+ self.tool('sync')+ for v in ('dm', 'AGENTS.md'):+ src = self.eng / v+ (shutil.copytree if src.is_dir() else shutil.copy)(src, self.r / v)+ self.assertIn('committed vendored tree matches', self.tool('check', '--tree'))+ (self.r / 'dm/b.c').write_text('edited\n')+ out = self.tool('check', '--tree', expect=1)+ self.assertIn('dm/b.c', out); self.assertIn('absorb', out)++ def test_bump_drops_a_patch_upstream_took_and_moves_the_pin(self):+ self.tool('sync')+ up2 = self.up_commit('dm/a.c', 'line1\nline2 fork\nline3\nline4\nline5\nline6\nline7\n', 'upstream takes line 2')+ self.assertIn('landed upstream, dropped (1): line-2', self.tool('bump', '--dry', '--to', up2))+ self.assertEqual((self.r / '.upstream-ref').read_text().strip(), self.up1)+ self.tool('bump', '--to', 'main')+ self.assertEqual((self.r / '.upstream-ref').read_text().strip(), up2)+ self.assertFalse((self.r / 'patches/0001-line-2.patch').exists())+ self.tool('sync')+ self.assertEqual((self.eng / 'dm/fork_patches.txt').read_text(), '')+++class Search(unittest.TestCase):+ def test_the_repository_ignores_engine_for_git_but_not_for_ripgrep(self):+ self.assertIn('/engine/', (REPO / '.gitignore').read_text().splitlines())+ self.assertIn('!/engine/', (REPO / '.ignore').read_text().splitlines())++ @unittest.skipUnless(shutil.which('rg'), 'ripgrep is not installed')+ def test_a_search_from_the_root_finds_a_file_under_engine(self):+ tmp = Path(tempfile.mkdtemp(prefix='test-engine-rg-'))+ self.addCleanup(shutil.rmtree, tmp, True)+ git(tmp, 'init', '-q')+ shutil.copy(REPO / '.gitignore', tmp / '.gitignore'); shutil.copy(REPO / '.ignore', tmp / '.ignore')+ (tmp / 'engine/dm').mkdir(parents=True); (tmp / 'engine/dm/needle.c').write_text('engine_needle_7f3\n')+ self.assertEqual(git(tmp, 'status', '--porcelain', '--untracked-files=all').count('engine/'), 0)+ r = subprocess.run(['rg', '-l', 'engine_needle_7f3'], cwd=tmp, capture_output=True, text=True, check=False)+ self.assertEqual(r.stdout.strip(), 'engine/dm/needle.c', r.stderr)+++class StampKey(Fixture):+ def test_the_qt_front_end_computes_the_same_key(self):+ sys.path.insert(0, str(REPO / 'frontend-qt'))+ qt_engine = importlib.import_module('nspb_qt.engine')+ self.tool('sync')+ self.assertEqual(qt_engine.stamp_key(self.r), E.stamp_key(self.r))+ self.assertEqual(qt_engine.engine_root(str(self.r)), str(self.eng))+ self.add_patch('0002-b.patch', 'dm/b.c', 'b1\nb2 fork\n', 'Change b2', header=HEADER.replace('#1', '#2'))+ self.assertTrue(qt_engine.is_stale(str(self.r)))+++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/tests/test_patches.py b/tools/tests/test_patches.pysimilarity index 94%rename from scripts/tests/test_patches.pyrename to tools/tests/test_patches.pyindex 0b1b5ddc..b463b6d2 100644--- a/scripts/tests/test_patches.py+++ b/tools/tests/test_patches.py@@ -1,11 +1,13 @@-"""scripts/patches.py on a fixture repository: the series reproduces the vendored tree, a patch that upstream took drops on a bump,+"""tools/patches.py on a fixture repository: the series reproduces the vendored tree, a patch that upstream took drops on a bump,a conflict names its patch, export writes the header, a patch that touches the shader chain is rejected, and the list of carriedpatches is generated, and the generated indexes are regenerated on the patched tree. No game files, no network: upstream is a branch of the fixture."""import importlib.util, os, shutil, subprocess, sys, tempfile, unittestfrom pathlib import PathREPO = Path(__file__).resolve().parents[2]-TOOL = REPO / 'scripts/patches.py'+TOOL = REPO / 'tools/patches.py'+# The engine sources the tests read: engine/ once tools/engine.py sync made it (LNPANDY/NX2Apple#214), else the committed tree+SRC = REPO / 'engine' if (REPO / 'engine/AGENTS.md').is_file() else REPOspec = importlib.util.spec_from_file_location('patches_tool', TOOL)P = importlib.util.module_from_spec(spec); spec.loader.exec_module(P)@@ -29,12 +31,12 @@ class Fixture(unittest.TestCase):self.w('dm/a.c', 'line1\nline2\nline3\nline4\nline5\nline6\nline7\n')self.w('dm/b.c', 'b1\nb2\n')self.w('docs/x.md', 'x\n')- shutil.copy(REPO / 'AGENTS.md', self.r / 'AGENTS.md')+ shutil.copy(SRC / 'AGENTS.md', self.r / 'AGENTS.md')git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', 'upstream 1')self.up1 = git(self.r, 'rev-parse', 'HEAD')git(self.r, 'branch', 'up')- # the tool lives in the fork's scripts/, which is vendored but not part of the generated tree- (self.r / 'scripts').mkdir(); shutil.copy(TOOL, self.r / 'scripts/patches.py')+ # the tool lives in the fork's tools/, outside the vendored paths+ (self.r / 'tools').mkdir(); shutil.copy(TOOL, self.r / 'tools/patches.py')self.w('dm/a.c', 'line1\nline2 fork\nline3\nline4\nline5\nline6\nline7\n')git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', 'Make line 2 the fork\'s\n\nWhy: a test.')self.run_tool('export', 'HEAD', '--status', 'forwarded seedds/nxnative#475', '--reason', 'the fork needs line 2', '--issue', 'LNPANDY/NX2Apple#1')@@ -46,7 +48,7 @@ class Fixture(unittest.TestCase):f = self.r / path; f.parent.mkdir(parents=True, exist_ok=True); f.write_text(text)def run_tool(self, *a, expect=0):- r = subprocess.run([sys.executable, str(self.r / 'scripts/patches.py'), '--tmp', str(self.tmp), *a], cwd=self.r, capture_output=True, text=True, env=ENV)+ r = subprocess.run([sys.executable, str(self.r / 'tools/patches.py'), '--tmp', str(self.tmp), *a], cwd=self.r, capture_output=True, text=True, env=ENV)if expect is not None: self.assertEqual(r.returncode, expect, r.stdout + r.stderr)return r.stdout + r.stderr@@ -71,7 +73,7 @@ class ApplyAndCheck(Fixture):def test_a_hand_edit_of_a_vendored_file_fails_check_and_apply_restores_it(self):self.w('dm/b.c', 'b1\nb2 edited\n')out = self.run_tool('check', expect=1)- self.assertIn('dm/b.c', out); self.assertIn('run `python3 scripts/patches.py absorb dm/b.c` and commit patches/', out)+ self.assertIn('dm/b.c', out); self.assertIn('run `python3 tools/patches.py absorb dm/b.c` and commit patches/', out)self.run_tool('apply')self.assertEqual((self.r / 'dm/b.c').read_text(), 'b1\nb2\n')self.run_tool('check')@@ -224,7 +226,7 @@ class Absorb(Fixture):for n in range(8): self.w(f'dm/n{n}.c', 'n\n')out = self.run_tool('check', expect=1)self.assertNotIn('...', out)- self.assertIn('`python3 scripts/patches.py absorb`', out)+ self.assertIn('`python3 tools/patches.py absorb`', out)def test_a_full_revert_that_empties_a_patch_is_refused_and_changes_nothing(self):self.w('dm/a.c', 'line1\nline2\nline3\nline4\nline5\nline6\nline7\n')@@ -324,8 +326,8 @@ class ForkPatchList(Fixture):def test_the_mac_app_stamps_the_list_into_info_plist(self):"""pack_app.py's DMForkPatches is dm/fork_patches.txt, comma-separated, and empty without the file"""- sys.path.insert(0, str(REPO / 'dm/tools'))- spec = importlib.util.spec_from_file_location('pack_app_under_test', REPO / 'dm/mac/pack_app.py')+ sys.path.insert(0, str(SRC / 'dm/tools'))+ spec = importlib.util.spec_from_file_location('pack_app_under_test', SRC / 'dm/mac/pack_app.py')mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)fake = self.tmp / 'dm/mac'; fake.mkdir(parents=True)mod.__file__ = str(fake / 'pack_app.py')@@ -337,9 +339,9 @@ class ForkPatchList(Fixture):def test_the_first_log_line_and_the_ios_key_are_in_the_sources(self):"""a read of the sources, not a run: the iOS app and the Mac launcher write the line, project.yml carries the key"""- self.assertIn('"fork patches: %s\\n"', (REPO / 'dm/ios/Sources/main.m').read_text())- self.assertIn('"fork patches: %s\\n"', (REPO / 'dm/mac/launcher.c').read_text())- self.assertIn('DMForkPatches: ${DM_FORK_PATCHES}', (REPO / 'dm/ios/project.yml').read_text())+ self.assertIn('"fork patches: %s\\n"', (SRC / 'dm/ios/Sources/main.m').read_text())+ self.assertIn('"fork patches: %s\\n"', (SRC / 'dm/mac/launcher.c').read_text())+ self.assertIn('DMForkPatches: ${DM_FORK_PATCHES}', (SRC / 'dm/ios/project.yml').read_text())class GeneratedIndexes(Fixture):@@ -381,14 +383,14 @@ class HostTestRules(unittest.TestCase):def test_sdk16_tests_keep_runtime_profile_linkage_after_refresh(self):r = subprocess.run(['make', '-n', '-B', 'GAME=010015100B514000', 'build/t_language', 'build/t_shared_font'],- cwd=REPO / 'dm/host/tests', capture_output=True, text=True)+ cwd=SRC / 'dm/host/tests', capture_output=True, text=True)self.assertEqual(r.returncode, 0, r.stdout + r.stderr)for name in ('t_language', 't_shared_font'):command = next(line for line in r.stdout.splitlines() if f'-o build/{name} ' in line)self.assertIn(f'{name}.c ../hle_profile.c', command)if name == 't_language':self.assertIn('-fsanitize=address,undefined', command)- rules = (REPO / 'dm/host/tests/Makefile').read_text().splitlines()+ rules = (SRC / 'dm/host/tests/Makefile').read_text().splitlines()prerequisites = ' '.join(line for line in rules if line.startswith('run:'))for name in ('t_language', 't_input_map', 't_launcher_contract'):self.assertIn(f'$(B)/{name}', prerequisites)