Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

patches.py absorb for direct edits to vendored files, and a check that says what to run

v0lumehi45e3ab301e83
diff --git a/.github/workflows/pr-scope.yml b/.github/workflows/pr-scope.yml
index ae959b74..b794f54c 100644
--- a/.github/workflows/pr-scope.yml
+++ b/.github/workflows/pr-scope.yml
@@ -29,4 +29,8 @@ jobs:
git remote add seedds https://github.com/seedds/nxnative.git
git fetch --no-tags seedds "$(cat .upstream-ref)"
- name: The series reproduces the vendored tree
- run: python3 scripts/patches.py check
+ run: |
+ python3 scripts/patches.py check || {
+ echo "::error title=Patch queue::Patch queue out of sync: vendored files differ from pin + patches. Fix: python3 scripts/patches.py absorb <the files listed above> (a new file may need --into <patch>), then commit patches/. See patches/README.md."
+ exit 1
+ }
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 83abb5ec..6863a42b 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -144,7 +144,11 @@ jobs:
git fetch --no-tags seedds main
git fetch --no-tags seedds "$(cat .upstream-ref)"
- name: Patch queue check
- run: python scripts/patches.py check
+ run: |
+ python scripts/patches.py check || {
+ echo "::error title=Patch queue::Patch queue out of sync: vendored files differ from pin + patches. Fix: python3 scripts/patches.py absorb <the files listed above> (a new file may need --into <patch>), then commit patches/. See patches/README.md."
+ exit 1
+ }
- name: Patch queue tests
run: python -m unittest -v scripts/tests/test_patches.py
- name: Dry bump to seedds main (report only)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 61b3c4d6..2a13d017 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -22,7 +22,7 @@ Pick a form: **Game problem**, **Build problem** or **Launcher problem or idea**
- One change per PR, off `main`. Commit messages say what changed and why, in plain English, as `git log` does.
- Fill in the PR template: what and why, what was checked, screenshots for UI changes.
- **`frontend/` and `frontend-qt/` are the fork's own:** change them freely. Run `cd frontend && swift test`; for a UI change also capture the views for visual QA (`NX_LAUNCHER_CAPTURE_DIR`, see [frontend/README.md](frontend/README.md#verification)).
-- **`dm/`, `scripts/`, `docs/`, `ref/` and `AGENTS.md` are upstream plus the patch queue.** They are generated: seedds/nxnative at the commit in `.upstream-ref` with the patches in `patches/` applied, so a direct edit fails `scripts/patches.py check` (the `pr-scope` and `patch-queue` jobs) and would be lost on the next bump. Commit the change, turn it into a patch with `scripts/patches.py export <commit>`, fill in its header (`Upstream-Status`, `Reason`, `Issue`), and send the same change to seedds/nxnative so the patch can go: [patches/README.md](patches/README.md) walks through it and states the patch policy (what a patch may and may not change). Files under `.github/` and in the repository root that are not in that list (this file, `CLAUDE.md`, the README) are the fork's.
+- **`dm/`, `scripts/`, `docs/`, `ref/` and `AGENTS.md` are upstream plus the patch queue.** They are generated: seedds/nxnative at the commit in `.upstream-ref` with the patches in `patches/` applied, so a direct edit fails `scripts/patches.py check` (the `pr-scope` and `patch-queue` jobs) and would be lost on the next bump. The failure names the command: `python3 scripts/patches.py absorb <files>` folds a direct edit into the patch that already touches the file (a new file may need `--into <patch>`); commit `patches/` with it. For a change that needs a patch of its own, commit the change, turn it into a patch with `scripts/patches.py export <commit>`, fill in its header (`Upstream-Status`, `Reason`, `Issue`), and send the same change to seedds/nxnative so the patch can go: [patches/README.md](patches/README.md) walks through it and states the patch policy (what a patch may and may not change). Files under `.github/` and in the repository root that are not in that list (this file, `CLAUDE.md`, the README) are the fork's.
## For AI agents and other tools
diff --git a/patches/README.md b/patches/README.md
index c044488d..c3e1720e 100644
--- a/patches/README.md
+++ b/patches/README.md
@@ -32,12 +32,26 @@ python3 scripts/patches.py apply # rebuild the vendored tree from t
python3 scripts/patches.py bump --to <sha> # move the pin (the nightly job does this)
python3 scripts/patches.py bump --dry --to <sha> # which patches would conflict, changing nothing
python3 scripts/patches.py export <commit> # a local commit becomes a patch
+python3 scripts/patches.py absorb [paths] # direct edits of vendored files fold into the patches that touch them
```
`apply` and `bump` need the upstream commit in the local repository (`git fetch seedds`, the remote
`https://github.com/seedds/nxnative.git`). Scratch worktrees go to `$PATCHES_TMP` (or `--tmp`), else the system's temporary folder.
`dm/fork_patches.txt` is generated by `apply` and `bump` (one patch name per line); do not edit it.
+## You edited a vendored file directly (check fails)
+
+`check` names every file that differs from pin + patches and the command to run, e.g. `docs/x.md differs from pin+patches: run
+`python3 scripts/patches.py absorb docs/x.md` and commit patches/`. `absorb [paths...]` takes the difference between the
+vendored files of your checkout (working tree or already committed) and pin + series, and folds each file into the patch that
+already touches it (the last one, when several do), keeping that patch's header. Then it runs `check`. Commit `patches/`.
+
+- A new file goes to a patch only when that is unambiguous: the one patch that touches files in the file's nearest folder.
+ Otherwise `absorb` stops, writes nothing, and asks for `--into <patch>` (a name from `status`, or its number).
+- `paths` limit what is folded in (files or folders); without them every difference is.
+- It refuses the shader chain and the tool pins (Patch policy), and leaves the generated indexes to `apply`.
+- For a change that needs its own `Upstream-Status`, use `export` below instead.
+
## Carrying a quick fix, and sending it upstream
1. Branch off `main`. Make the fix as an ordinary commit in the vendored files, with a message that says what and why.
diff --git a/scripts/patches.py b/scripts/patches.py
index 46184d0b..23222b8e 100644
--- a/scripts/patches.py
+++ b/scripts/patches.py
@@ -17,6 +17,8 @@ Subcommands (Python 3.9+, stdlib and git):
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
@@ -269,6 +271,27 @@ def install(root, wt, patches):
(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(f'To fold all of them at once: `python3 scripts/patches.py absorb {" ".join(absorbable[:6])}{" ..." if len(absorbable) > 6 else ""}`, 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):
@@ -304,7 +327,7 @@ def cmd_check(a):
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('A fix to a vendored file belongs in a patch: commit it, then `scripts/patches.py export <commit>` (patches/README.md).')
+ 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
@@ -447,6 +470,78 @@ def cmd_export(a):
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 = [x.rstrip('/') for x in a.paths]
+ 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):
+ 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 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)
+ 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')]
@@ -474,6 +569,9 @@ def main(argv=None):
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)
diff --git a/scripts/tests/test_patches.py b/scripts/tests/test_patches.py
index 2cf8b781..b519ff7d 100644
--- a/scripts/tests/test_patches.py
+++ b/scripts/tests/test_patches.py
@@ -71,7 +71,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('patches.py export', out)
+ self.assertIn('dm/b.c', out); self.assertIn('run `python3 scripts/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')
@@ -138,6 +138,79 @@ class Bump(Fixture):
git(self.r, 'worktree', 'remove', '--force', wt)
+class Absorb(Fixture):
+ def export_second(self):
+ """A second patch, on dm/b.c, so that dm/ has two owners."""
+ self.w('dm/b.c', 'b1\nb2 fork\n'); git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', 'Fork b2')
+ self.run_tool('export', 'HEAD', '--reason', 'r', '--issue', 'LNPANDY/NX2Apple#2')
+ git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', 'patches 2')
+
+ def test_an_edit_of_a_file_a_patch_touches_goes_into_that_patch(self):
+ self.w('dm/a.c', 'line1\nline2 fork\nline3\nline4\nline5\nline6\nline7 more\n')
+ self.run_tool('check', expect=1)
+ out = self.run_tool('absorb')
+ self.assertIn('absorbed dm/a.c', out); self.assertIn('patch queue: ok', out)
+ self.assertIn('+line7 more', self.patch.read_text())
+ self.assertIn('Reason: the fork needs line 2', self.patch.read_text()) # the header survives
+ self.run_tool('check')
+
+ def test_absorb_works_on_a_committed_edit_too(self):
+ self.w('dm/a.c', 'line1\nline2 fork\nline3\nline4\nline5\nline6\nline7 more\n'); git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', 'direct')
+ self.run_tool('check', expect=1)
+ self.run_tool('absorb', 'dm/a.c')
+ self.run_tool('check')
+
+ def test_a_file_goes_to_the_last_patch_that_touches_it(self):
+ self.export_second()
+ self.w('dm/b.c', 'b1\nb2 fork\nb3\n')
+ self.run_tool('absorb')
+ self.assertIn('+b3', (self.r / 'patches/0002-fork-b2.patch').read_text())
+ self.assertNotIn('+b3', self.patch.read_text())
+
+ def test_a_new_file_next_to_a_patched_one_goes_to_its_patch(self):
+ self.w('dm/new.c', 'n\n')
+ self.assertIn('dm/new.c', self.run_tool('absorb'))
+ self.assertIn('+++ b/dm/new.c', self.patch.read_text())
+ self.run_tool('check')
+
+ def test_a_new_file_in_an_untouched_folder_stops_and_asks_for_into(self):
+ self.w('docs/y.md', 'y\n')
+ out = self.run_tool('absorb', expect=2)
+ self.assertIn('docs/y.md', out); self.assertIn('--into <patch>', out)
+ self.assertNotIn('docs/y.md', self.patch.read_text()) # nothing was written
+ self.run_tool('absorb', '--into', 'make-line-2-the-fork-s', 'docs/y.md')
+ self.assertIn('+++ b/docs/y.md', self.patch.read_text())
+ self.run_tool('check')
+
+ def test_a_new_file_in_a_folder_two_patches_touch_is_ambiguous(self):
+ self.export_second()
+ self.w('dm/c.c', 'c\n')
+ out = self.run_tool('absorb', expect=2)
+ self.assertIn('ambiguous', out); self.assertIn('fork-b2', out); self.assertIn('make-line-2-the-fork-s', out)
+ self.run_tool('absorb', '--into', 'fork-b2', 'dm/c.c')
+ self.assertIn('+++ b/dm/c.c', (self.r / 'patches/0002-fork-b2.patch').read_text())
+
+ def test_paths_limit_what_is_folded_in(self):
+ self.w('dm/a.c', 'line1\nline2 fork\nline3\nline4\nline5\nline6\nline7 more\n'); self.w('dm/b.c', 'b1\nb2 edited\n')
+ out = self.run_tool('absorb', 'dm/a.c', expect=1) # dm/b.c is still a difference, so the closing check fails
+ self.assertIn('absorbed dm/a.c', out); self.assertNotIn('absorbed dm/b.c', out)
+ self.assertIn('absorb dm/b.c', out)
+
+ def test_a_deleted_file_is_removed_by_its_patch(self):
+ self.w('dm/new.c', 'n\n'); self.run_tool('absorb')
+ (self.r / 'dm/new.c').unlink()
+ self.run_tool('absorb')
+ self.assertNotIn('dm/new.c', self.patch.read_text())
+ self.run_tool('check')
+
+ def test_nothing_to_absorb_just_checks(self):
+ self.assertIn('nothing to fold in', self.run_tool('absorb'))
+
+ def test_the_shader_chain_is_refused(self):
+ self.w('dm/gfx/nvn/dmsh_chain.h', 'x\n')
+ self.assertIn('shader chain', self.run_tool('absorb', expect=2))
+
+
class Export(Fixture):
def commit_edit(self, msg, path='dm/b.c', text='b1\nb2 changed\n'):
self.w(path, text); git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', msg)