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
Git hooks: run the checks before a commit and a push, and block a push to main in Claude Code
v0lumehic67d8111ebd8
diff --git a/.claude/settings.json b/.claude/settings.jsonindex 3d61d567..39268dda 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -11,6 +11,18 @@}]}+ ],+ "PreToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": "python3 \"$CLAUDE_PROJECT_DIR/tools/claude_guard.py\"",+ "timeout": 10+ }+ ]+ }]}}diff --git a/.githooks/pre-commit b/.githooks/pre-commitnew file mode 100755index 00000000..15a0d4db--- /dev/null+++ b/.githooks/pre-commit@@ -0,0 +1,3 @@+#!/bin/sh+# Runs the patch queue check when patches/ or .upstream-ref is staged. The logic is in tools/githooks.py.+exec python3 "$(dirname "$0")/../tools/githooks.py" pre-commitdiff --git a/.githooks/pre-push b/.githooks/pre-pushnew file mode 100755index 00000000..9d1264f6--- /dev/null+++ b/.githooks/pre-push@@ -0,0 +1,3 @@+#!/bin/sh+# Runs the checks that match what is pushed. The logic is in tools/githooks.py. Install: git config core.hooksPath .githooks+exec python3 "$(dirname "$0")/../tools/githooks.py" pre-pushdiff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex d407d366..b8ecdc07 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -2,6 +2,7 @@Read [AGENTS.md](../AGENTS.md) (the fork's, at the root) and [CONTRIBUTING.md](../CONTRIBUTING.md) first, and they win over this file.+- First, in your checkout, run `git config core.hooksPath .githooks`. The hooks run the checks before a commit and a push. Keep them installed, never use `--no-verify`, and never push to `main`: every change goes through a PR.- `frontend/` and `frontend-qt/` are this fork's own: change them directly. `cd frontend && swift test` is the check.- The engine (`dm/`, `scripts/`, `docs/`, `ref/`) is not in this repository: it is seedds/nxnative at `.upstream-ref` plus `patches/`, built into `engine/` by `python3 tools/engine.py sync`. Do not add files under those paths in a PR (the `pr-scope` check fails it). A change to the engine is a pull request to seedds/nxnative first, and a patch in `patches/` (a commit in `engine/`, then `python3 tools/engine.py export`) only while the fork has to carry it.- Never touch the shader translation chain (`dm/gfx/tools/dmsh_*`, `dm/gfx/nvn/dmsh_chain.h`, `dmsh_chain.lock`, the translator).diff --git a/AGENTS.md b/AGENTS.mdindex 77f3a732..4c1f5c43 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -2,6 +2,7 @@This is the fork's guide. The engine has its own, upstream's: [engine/AGENTS.md](engine/AGENTS.md) (after `python3 tools/engine.py sync`, or [seedds/nxnative's AGENTS.md](https://github.com/seedds/nxnative/blob/main/AGENTS.md)). Read this file first, the engine's for any work in `engine/`.+- **Install the git hooks first.** In every clone and worktree, before any other work, run `git config core.hooksPath .githooks`. `python3 tools/engine.py sync`, `check` and `export` and the Claude Code session start do it when it is unset. Keep the hooks installed. Never use `--no-verify` on `git commit` or `git push`. Never push to `main` directly, every change goes through a PR, patches included.- **Layout.** NX2Apple is the launcher and the glue around [seedds/nxnative](https://github.com/seedds/nxnative), which runs Nintendo Switch games natively on Apple platforms. This repository commits: `frontend/` (the Mac launcher, SwiftUI), `frontend-qt/` (the Qt front end), `frontend-ios/` (the iPhone shell), `tools/` (`engine.py`, `patches.py`, `release_manifest.py` and their tests), `patches/` (the series), `.upstream-ref` (the nxnative commit we build on), `.github/` (CI, forms, triage), the player and developer pages (`README*.md`, `GAMES*.md`, `BUILDING*.md`, `CONTRIBUTING*.md`, `CHANGELOG*.md`). The engine (`dm/`, `scripts/`, `docs/`, `ref/`) is **not** here: it is nxnative at the pin plus `patches/`, built into `engine/` by `python3 tools/engine.py sync`. `engine/` is a real git repository that this one ignores. A root `.ignore` keeps it visible to ripgrep.- **Commit with your own git identity, never upstream's.** Use the identity configured for your clone, or your own name and email. `engine/AGENTS.md` ends with a `git -c user.name=seedds -c user.email=…` line because it is written for seedds/nxnative, where seedds is the maintainer. Do not copy it here: it makes fork commits, and the `From:` line of patches made with `tools/engine.py export`, show upstream's author. Commit only when asked.- **Here first, upstream in parallel.** A fix to the engine, to a game profile or to upstream's docs may land here first, as a patch. The same change goes to seedds/nxnative as a pull request in parallel, from a branch off their main (`git -C engine fetch seedds`, `engine/` has the remote). If you cannot open that pull request, a maintainer sends it. A patch here is a bridge until upstream has it, and the next bump drops it once the change is in. [patches/README.md](patches/README.md#here-first-upstream-in-parallel) has the rule and the `Upstream-Status` values.@@ -9,5 +10,5 @@ This is the fork's guide. The engine has its own, upstream's: [engine/AGENTS.md]- **Never add engine files to this repository.** Files under `dm/`, `scripts/`, `docs/` and `ref/` at the root are ignored by `.gitignore`, and the `pr-scope` check fails a PR that adds them. A direct edit of engine files is lost on the next sync.- **Issues and pull requests.** Follow [CONTRIBUTING.md](CONTRIBUTING.md), section "For AI agents and other tools", and the forms and the PR template in `.github/`. Fix or feature: every fix goes through a PR and merges when CI is green, unless a maintainer's "changes requested" review is unanswered (a plain review comment does not block, and @LNPANDY decides only when the maintainers disagree), a maintainer's own feature after 48 hours (a feature from outside never merges by waiting, a maintainer has to agree, try the app and review the code), a patch is renumbered by whoever merges it, releases and version bumps are the owner's. Never attach or commit keys, game files or data extracted from a game.- **Merging with admin rights.** An admin merge never goes over a red check. That holds even when @LNPANDY overrides an objection. If a re-review is slow, the other maintainer pings the reviewer and does not merge with admin rights.-- **Checks.** `cd frontend && swift build && swift test` for the Mac launcher (its tests read `engine/`, so sync first), `python3 -m unittest discover -s frontend-qt/tests` for the Qt front end (and `python3 frontend-qt/gen_localization.py` leaves `frontend-qt/nspb_qt/localization.py` unchanged), `python3 -m unittest discover tools/tests` for the tools. The engine's own tests run in `engine/` as `tests.yml` does.+- **Checks.** `cd frontend && swift build && swift test` for the Mac launcher (its tests read `engine/`, so sync first), `python3 -m unittest discover -s frontend-qt/tests` for the Qt front end (and `python3 frontend-qt/gen_localization.py` leaves `frontend-qt/nspb_qt/localization.py` unchanged), `python3 -m unittest discover tools/tests` for the tools. The engine's own tests run in `engine/` as `tests.yml` does. The pre-commit hook runs `python3 tools/engine.py check` when `patches/` or `.upstream-ref` is staged. The pre-push hook runs the checks above for the files the push changes, `tools/githooks.py` has the list. Fix the failure, do not bypass the hook.- **Language and text.** Everything is in English except the Chinese pages (`*.zh-CN.md`) and the launcher's strings. No semicolons in UI strings, READMEs and docs.diff --git a/CLAUDE.md b/CLAUDE.mdindex 90316bd4..72912728 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,5 +1,6 @@# Notes for Claude+- First step in every clone or worktree: `git config core.hooksPath .githooks` (the SessionStart hook does it when unset). Never use `--no-verify`, never push to `main`: a PreToolUse hook in `.claude/settings.json` blocks both. See AGENTS.md.- Read [AGENTS.md](AGENTS.md) first: this repository's layout and rules. For engine work read [engine/AGENTS.md](engine/AGENTS.md) too, upstream's guide from seedds/nxnative at the pin. `engine/` is made by `python3 tools/engine.py sync` (the SessionStart hook in `.claude/settings.json` runs it).- For an issue or a pull request, follow [CONTRIBUTING.md](CONTRIBUTING.md), section "For AI agents and other tools", and the templates in `.github/`.- A PR that changes the launcher needs before and after screenshots: see "For AI agents and other tools" in CONTRIBUTING.md for how to capture them and attach them with `gh pr create --attach`.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a31b09db..641105e0 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -35,6 +35,7 @@ missing piece.## A pull request+- Before any work in a clone or worktree, run `git config core.hooksPath .githooks`. The hooks run the checks for what you commit and push (`python3 tools/engine.py check` for `patches/`, the tests for the code you changed, see `tools/githooks.py`). `tools/engine.py sync`, `check` and `export` install the hooks when they are not. Keep them installed and never use `--no-verify`. Never push to `main` directly.- 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.- A PR that changes anything visible in the launcher attaches before and after screenshots to the PR, under Screenshots. Show every view the PR changes, in each language it touches. A PR without them is not reviewed. A PR with no visible change writes "None, no visible change".diff --git a/tools/claude_guard.py b/tools/claude_guard.pynew file mode 100755index 00000000..7317d147--- /dev/null+++ b/tools/claude_guard.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+"""Claude Code PreToolUse hook for the Bash tool (.claude/settings.json). Reads the call as JSON on stdin and exits 2, with the reason+on stderr, for a `git push` to main or master and for `--no-verify` on `git commit` and `git push`. Exit 0 lets the call go on."""+import json+import os+import re+import shlex+import subprocess+import sys++PROTECTED = ('main', 'master')+WRAPPERS = ('sudo', 'env', 'command', 'time', 'nohup', 'exec')+PUSH_ARG_FLAGS = ('-o', '--push-option', '--receive-pack', '--exec', '--repo') # options that take the next word as their value+GIT_ARG_FLAGS = ('-C', '-c', '--git-dir', '--work-tree', '--namespace')+SHELLS = ('sh', 'bash', 'zsh')++NO_PR = 'Patches and code go through a PR: push a branch and open a pull request. Nothing is pushed to main or master directly.'+NO_VERIFY = 'The pre-commit and pre-push hooks stay on. Fix what they report instead of using --no-verify.'+++def segments(command):+ """The commands in a shell line as word lists, split at ; && || | & and newlines. None when the line does not parse."""+ lex = shlex.shlex(command, posix=True, punctuation_chars=';&|()\n')+ lex.whitespace_split, lex.whitespace = True, ' \t\r'+ try:+ words = list(lex)+ except ValueError:+ return None+ out, cur = [], []+ for w in words:+ if w and set(w) <= set(';&|()\n'):+ if cur: out.append(cur)+ cur = []+ else:+ cur.append(w)+ return out + ([cur] if cur else [])+++def git_call(words):+ """(global options, subcommand, its arguments) for a segment that runs git, else None."""+ i = 0+ while i < len(words) and (words[i] in WRAPPERS or re.fullmatch(r'\w+=.*', words[i])): i += 1+ if i >= len(words) or os.path.basename(words[i]) != 'git': return None+ i += 1+ opts = []+ while i < len(words) and words[i].startswith('-'):+ opts.append(words[i])+ if words[i] in GIT_ARG_FLAGS and i + 1 < len(words):+ i += 1+ opts.append(words[i])+ i += 1+ return (opts, words[i], words[i + 1:]) if i < len(words) else None+++def current_branch(cwd, opts):+ if '-C' in opts: cwd = os.path.join(cwd, opts[opts.index('-C') + 1])+ r = subprocess.run(['git', 'branch', '--show-current'], cwd=cwd, capture_output=True, text=True)+ return r.stdout.strip() if r.returncode == 0 else ''+++def pushes_to_protected(opts, args, cwd):+ flags = [a for a in args if a.startswith('-')]+ if '--all' in flags or '--mirror' in flags: return True+ pos, skip = [], False+ for a in args:+ if skip: skip = False+ elif a in PUSH_ARG_FLAGS: skip = True+ elif not a.startswith('-'): pos.append(a)+ refspecs = pos[1:] # the first word is the remote+ if not refspecs: return current_branch(cwd, opts) in PROTECTED+ for r in refspecs:+ dest = r.lstrip('+').split(':')[-1]+ if dest == 'HEAD': dest = current_branch(cwd, opts)+ if dest.removeprefix('refs/heads/') in PROTECTED: return True+ return False+++def verdict(command, cwd='.'):+ """The reason to stop this command, or None."""+ segs = segments(command)+ if segs is None: # unbalanced quotes: look at the raw text+ if re.search(r'\bgit\b.*\bpush\b.*\b(main|master)\b', command): return NO_PR+ return NO_VERIFY if re.search(r'\bgit\b.*\b(commit|push)\b.*--no-verify', command) else None+ for words in segs:+ if os.path.basename(words[0]) in SHELLS and '-c' in words and words.index('-c') + 1 < len(words):+ reason = verdict(words[words.index('-c') + 1], cwd) # bash -c "git push origin main"+ if reason: return reason+ call = git_call(words)+ if not call: continue+ opts, sub, args = call+ if sub == 'push' and pushes_to_protected(opts, args, cwd): return NO_PR+ if sub in ('push', 'commit') and ('--no-verify' in args or (sub == 'commit' and any(re.fullmatch(r'-[a-zA-Z]*n[a-zA-Z]*', a) for a in args))):+ return NO_VERIFY+ return None+++def main():+ try:+ call = json.load(sys.stdin)+ command = call['tool_input']['command']+ except (ValueError, KeyError, TypeError):+ return 0 # not a call this guard understands: no decision+ reason = verdict(command, call.get('cwd') or os.getcwd())+ if reason:+ print(f'Blocked by tools/claude_guard.py: {reason}', file=sys.stderr)+ return 2+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tools/engine.py b/tools/engine.pyindex 23035412..320bca04 100755--- a/tools/engine.py+++ b/tools/engine.py@@ -66,6 +66,22 @@ def git(*a, cwd, check=True, binary=False):return P.git(*a, cwd=cwd, check=check, binary=binary)+HOOKS = '.githooks'+++def install_hooks(root):+ """core.hooksPath -> .githooks (the pre-push and pre-commit checks), unless it is set. A path the user chose is kept, with a warning.+ The setting lives in the repository's config, so every worktree of it has the hooks."""+ if not (root / HOOKS / 'pre-push').is_file(): return+ cur = git('config', '--get', 'core.hooksPath', cwd=root, check=False).stdout.strip()+ if cur.rstrip('/') == HOOKS: return+ if cur:+ say(f'WARNING: core.hooksPath is {cur!r}, not {HOOKS!r}, so the pre-push checks do not run here. '+ f'Install them: git config core.hooksPath {HOOKS}')+ elif git('config', '--local', 'core.hooksPath', HOOKS, cwd=root, check=False).returncode == 0:+ say(f'git hooks: set core.hooksPath to {HOOKS} (pre-commit and pre-push checks, tools/githooks.py). Never bypass them with --no-verify.')++def engine_dir(root):return root / 'engine'@@ -180,7 +196,7 @@ def build(root, eng, patches, sha):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)+ r = subprocess.run([sys.executable, str(eng / tool)], cwd=eng, capture_output=True, text=True, check=False, env=P.clean_env())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)@@ -190,6 +206,7 @@ def build(root, eng, patches, sha):def cmd_sync(a):root = a.root+ install_hooks(root)eng = engine_dir(root)reason = why_stale(root)if not reason and not a.force:@@ -229,6 +246,7 @@ 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:+ install_hooks(a.root)reason = why_stale(a.root)if reason:with contextlib.redirect_stdout(buf):@@ -260,7 +278,7 @@ def extract_tree(eng, out):import tarfilenames = [n for n in TREE_PATHS if git('cat-file', '-e', f'HEAD:{n}', cwd=eng, check=False).returncode == 0]if not names: raise Fail(f'{eng} holds none of {", ".join(TREE_PATHS)}: not an engine checkout')- proc = subprocess.Popen(['git', 'archive', '--format=tar', 'HEAD', '--', *names], cwd=eng, stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ proc = subprocess.Popen(['git', 'archive', '--format=tar', 'HEAD', '--', *names], cwd=eng, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=P.clean_env())count = 0with tarfile.open(fileobj=proc.stdout, mode='r|') as tar:for m in tar:@@ -338,6 +356,7 @@ def cmd_tree(a):def cmd_export(a):root = a.root+ install_hooks(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)@@ -408,6 +427,7 @@ def scratch_root(root):def cmd_check(a):root = a.root+ install_hooks(root)patches = P.load(root)bad = []pd = root / 'patches'diff --git a/tools/githooks.py b/tools/githooks.pynew file mode 100755index 00000000..c62f56c9--- /dev/null+++ b/tools/githooks.py@@ -0,0 +1,109 @@+#!/usr/bin/env python3+"""What `.githooks/pre-push` and `.githooks/pre-commit` run (python3 and git only).++pre-push runs the checks that match what the push changes. Each is the command CI or AGENTS.md ("Checks") names, run from the+repository root. A push that touches only docs runs none, and a push that deletes a ref is skipped.+pre-commit runs only the patch queue check, and only when patches/ or .upstream-ref is staged. It takes seconds.+Install the hooks with `git config core.hooksPath .githooks`: tools/engine.py does it for you.+"""+import os+import shutil+import subprocess+import sys+from collections import namedtuple+from pathlib import Path++import patches as P++ROOT = Path(__file__).resolve().parent.parent+ZERO = '0' * 40+SYNC = 'python3 tools/engine.py -q sync' # these tests read engine/ (AGENTS.md, "Checks"); a no-op when it is current++Check = namedtuple('Check', 'name prefixes command cwd sync')++CHECKS = (+ Check('patch queue', ('patches/', '.upstream-ref'), 'python3 tools/engine.py check', '.', False),+ Check('Qt front end', ('frontend-qt/',), 'python3 -m unittest discover -s frontend-qt/tests'+ ' && python3 frontend-qt/gen_localization.py && git diff --exit-code HEAD -- frontend-qt/nspb_qt/localization.py', '.', True),+ Check('tools', ('tools/',), 'python3 -m unittest discover tools/tests', '.', True),+ Check('triage scripts', ('.github/scripts/',), 'python3 -m unittest discover -s .github/scripts/tests', '.', True),+ Check('Mac launcher (slow)', ('frontend/',), 'swift build && swift test', 'frontend', True),+)+++def checks_for(paths):+ """The checks a change to these paths needs, cheapest first."""+ return [c for c in CHECKS if any(p.startswith(c.prefixes) for p in paths)]+++def git(*a, env=None):+ """git in the repository at ROOT. It never takes GIT_DIR and the like from the environment, unless the caller passes env."""+ r = subprocess.run(['git', *a], cwd=ROOT, capture_output=True, text=True, env=env or P.clean_env())+ return r.stdout.strip() if r.returncode == 0 else None+++def sh(command, cwd):+ """A check runs in a clean environment: the repository that runs the hook (GIT_DIR in a worktree) is not the one the tests use."""+ return subprocess.run(command, shell=True, cwd=cwd, env=P.clean_env()).returncode+++def has_commit(sha):+ return git('cat-file', '-e', sha + '^{commit}') is not None+++def pushed_paths(lines):+ """The files that the pushed refs change, from the hook's stdin lines `<local ref> <local sha> <remote ref> <remote sha>`.+ None when a base cannot be found: then everything counts as changed."""+ paths = set()+ for line in lines:+ f = line.split()+ if len(f) != 4: continue+ _, local, _, remote = f+ if local == ZERO: continue # a deleted ref pushes no code+ base = remote if remote != ZERO and has_commit(remote) else git('merge-base', local, 'origin/main')+ out = git('diff', '--name-only', base, local) if base else None+ if out is None: return None+ paths.update(out.splitlines())+ return paths+++def pre_push(lines):+ paths = pushed_paths(lines)+ if paths is None: print('pre-push: no base to compare with (is origin/main fetched?), so every check runs')+ return run('pre-push', CHECKS if paths is None else checks_for(paths))+++def pre_commit():+ staged = (git('diff', '--cached', '--name-only', env=os.environ.copy()) or '').splitlines() # keeps GIT_INDEX_FILE, the index of this commit+ return run('pre-commit', [c for c in checks_for(staged) if c is CHECKS[0]])+++def run(hook, todo):+ stop = 'push' if hook == 'pre-push' else 'commit'+ emergency = f'{hook}: fix the failure. A maintainer may use git {stop} --no-verify in an emergency. An agent never does.'+ if not todo:+ print(f'{hook}: nothing to check for these files')+ return 0+ print(f'{hook}: running ' + ', '.join(c.name for c in todo), flush=True)+ if any(c.sync for c in todo):+ print(f'{hook}: {SYNC}', flush=True)+ if sh(SYNC, ROOT):+ print(f'{hook}: engine/ could not be synced, {stop} stopped. Reproduce: {SYNC}\n{emergency}', file=sys.stderr)+ return 1+ for c in todo:+ if c.cwd == 'frontend' and not shutil.which('swift'):+ print(f'{hook}: {c.name} skipped, swift is not installed. CI runs it.')+ continue+ print(f'{hook}: {c.name}: {c.command}', flush=True)+ if sh(c.command, ROOT / c.cwd):+ repro = c.command if c.cwd == '.' else f'cd {c.cwd} && {c.command}'+ print(f'{hook}: the {c.name} check failed, {stop} stopped. Reproduce: {repro}\n{emergency}', file=sys.stderr)+ return 1+ print(f'{hook}: all checks passed')+ return 0+++if __name__ == '__main__':+ if sys.argv[1:] == ['pre-push']: sys.exit(pre_push(sys.stdin.read().splitlines()))+ if sys.argv[1:] == ['pre-commit']: sys.exit(pre_commit())+ sys.exit('usage: githooks.py pre-push|pre-commit')diff --git a/tools/patches.py b/tools/patches.pyindex 93d20bbd..7851e930 100644--- a/tools/patches.py+++ b/tools/patches.py@@ -27,6 +27,10 @@ FORK_PATCHES = 'dm/fork_patches.txt'# from these paths.GENERATED = (('docs/agents/game-patches.md', 'dm/tools/docs_patches.py'),('docs/agents/symptoms.md', 'dm/tools/docs_symptoms.py'))+# What git exports to a hook (GIT_DIR in a worktree) and what points git at a repository. Every git command here names its repository+# with cwd, so none of these may reach it: they would send the command to the repository that runs the hook.+REPO_ENV = ('GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_PREFIX', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY',+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_QUARANTINE_PATH')KINDS = ('forwarded', 'pending', 'fork-only', 'backport')# The shader chain and the tool pins (the engine's AGENTS.md: the DMSH_CHAIN paragraph names them; chain_paths() reads it).# Used only when that file has no such paragraph.@@ -38,8 +42,13 @@ class Fail(Exception):pass+def clean_env(**extra):+ """The environment without the variables that point git at a repository."""+ return {**{k: v for k, v in os.environ.items() if k not in REPO_ENV}, **extra}++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)+ r = subprocess.run(['git', *a], cwd=cwd or REPO, input=inp, capture_output=True, text=not binary, env=clean_env())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 rdiff --git a/tools/tests/test_engine.py b/tools/tests/test_engine.pyindex e04bf155..b943d24e 100644--- a/tools/tests/test_engine.py+++ b/tools/tests/test_engine.py@@ -22,8 +22,8 @@ def setUpModule():if not (SRC / 'AGENTS.md').is_file():raise RuntimeError('engine/ is missing: run `python3 tools/engine.py sync` first')-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 = E.P.clean_env(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') # no GIT_DIR: a test must never reach the repository that runs itHEADER = 'Upstream-Status: forwarded seedds/nxnative#475\nReason: the fork needs line 2\nIssue: LNPANDY/NX2Apple#1\n'diff --git a/tools/tests/test_githooks.py b/tools/tests/test_githooks.pynew file mode 100644index 00000000..5d0b6c70--- /dev/null+++ b/tools/tests/test_githooks.py@@ -0,0 +1,335 @@+"""The git hooks (tools/githooks.py), their installation (engine.install_hooks) and the Claude Code guard (tools/claude_guard.py).+The hook tests use a throwaway repository, never this one."""+import contextlib+import importlib+import io+import os+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++TOOLS = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(TOOLS))+H = importlib.import_module('githooks')+G = importlib.import_module('claude_guard')+E = importlib.import_module('engine')+P = H.P++# git exports GIT_DIR and others to a hook. A test must never reach the repository that runs it, whatever it inherited.+for _k in P.REPO_ENV:+ os.environ.pop(_k, None)++ENV = dict({k: v for k, v in P.clean_env().items() if not k.startswith('GIT_CONFIG_')}, 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')+++def git(cwd, *a):+ r = subprocess.run(['git', '-c', 'commit.gpgsign=false', *a], cwd=cwd, capture_output=True, text=True, env=ENV)+ assert r.returncode == 0, f'git {a}: {r.stderr}'+ return r.stdout.strip()+++def names(paths):+ return [c.name for c in H.checks_for(paths)]+++class ChecksFor(unittest.TestCase):+ def test_docs_only_runs_nothing(self):+ self.assertEqual(names(['README.md', 'CONTRIBUTING.md', 'AGENTS.md', 'GAMES.md']), [])++ def test_patches_and_pin_run_the_patch_queue(self):+ self.assertEqual(names(['patches/0036-x.patch']), ['patch queue'])+ self.assertEqual(names(['.upstream-ref']), ['patch queue'])+ self.assertEqual(H.CHECKS[0].command, 'python3 tools/engine.py check')++ def test_each_area_runs_its_own_check(self):+ self.assertEqual(names(['tools/engine.py']), ['tools'])+ self.assertEqual(names(['.github/scripts/triage_apply.py']), ['triage scripts'])+ self.assertEqual(names(['frontend-qt/nspb_qt/app.py']), ['Qt front end'])+ self.assertEqual(names(['frontend/Package.swift']), ['Mac launcher (slow)'])++ def test_workflow_files_and_frontend_ios_run_nothing(self):+ self.assertEqual(names(['.github/workflows/tests.yml', 'frontend-ios/Package.swift']), [])++ def test_qt_does_not_match_the_mac_launcher(self):+ self.assertNotIn('Mac launcher (slow)', names(['frontend-qt/x.py']))++ def test_cheapest_first_and_the_slow_one_last(self):+ got = names(['frontend/a.swift', 'tools/a.py', 'patches/series', 'frontend-qt/a.py'])+ self.assertEqual(got, ['patch queue', 'Qt front end', 'tools', 'Mac launcher (slow)'])++ def test_the_commands_are_the_ones_in_ci(self):+ cmds = {c.name: c.command for c in H.CHECKS}+ self.assertEqual(cmds['tools'], 'python3 -m unittest discover tools/tests')+ self.assertIn('python3 -m unittest discover -s frontend-qt/tests', cmds['Qt front end'])+ self.assertIn('python3 frontend-qt/gen_localization.py', cmds['Qt front end'])+ self.assertIn('git diff --exit-code HEAD -- frontend-qt/nspb_qt/localization.py', cmds['Qt front end'])+ self.assertEqual(cmds['triage scripts'], 'python3 -m unittest discover -s .github/scripts/tests')+ self.assertEqual(cmds['Mac launcher (slow)'], 'swift build && swift test')+++def snapshot(repo):+ """Everything a stray git command could change in a repository: config, HEAD, refs, index, stash."""+ g = Path(repo) / '.git'+ return {str(f.relative_to(g)): f.read_bytes() for f in sorted(g.rglob('*')) if f.is_file() and 'hooks' not in f.relative_to(g).parts}+++class HookEnvironment(unittest.TestCase):+ """In a worktree git runs a hook with GIT_DIR set to the real repository. The checks make repositories of their own+ and must never reach that one (2026-10-31: tests wrote core.bare and refs into the shared repository)."""+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(prefix='test-hookenv-')+ self.addCleanup(self.tmp.cleanup)+ self.outer = Path(self.tmp.name) / 'outer'+ self.outer.mkdir()+ git(self.outer, 'init', '-q', '-b', 'main')+ git(self.outer, 'commit', '-q', '--allow-empty', '-m', 'outer')+ self.before = snapshot(self.outer)+ self.hook_env = {'GIT_DIR': str(self.outer / '.git'), 'GIT_WORK_TREE': str(self.outer), 'GIT_INDEX_FILE': str(self.outer / '.git/index'), 'GIT_PREFIX': ''}+ patcher = mock.patch.dict(os.environ, self.hook_env)+ patcher.start()+ self.addCleanup(patcher.stop)+ self.work = Path(self.tmp.name) / 'work'++ def test_a_check_started_with_git_dir_set_works_in_its_own_repository(self):+ script = (f'git init -q -b main "{self.work}" && git -C "{self.work}" config core.bare false'+ f' && git -C "{self.work}" -c user.name=t -c [email protected] commit -q --allow-empty -m probe'+ f' && git -C "{self.work}" branch other')+ self.assertEqual(H.sh(script, self.tmp.name), 0)+ self.assertEqual(snapshot(self.outer), self.before)+ self.assertEqual(git(self.work, 'log', '--format=%s'), 'probe')++ def test_the_git_helper_of_the_tools_ignores_git_dir(self):+ P.git('init', '-q', '-b', 'main', str(self.work), cwd=self.tmp.name)+ P.git('-c', 'user.name=t', '-c', '[email protected]', 'commit', '-q', '--allow-empty', '-m', 'probe', cwd=self.work)+ P.git('config', 'core.bare', 'false', cwd=self.work)+ P.git('update-ref', 'refs/remotes/origin/main', 'HEAD', cwd=self.work)+ self.assertEqual(snapshot(self.outer), self.before)+ self.assertEqual(git(self.work, 'rev-parse', 'origin/main'), git(self.work, 'rev-parse', 'HEAD'))++ def test_the_hook_script_with_git_dir_set_leaves_the_outer_repository_alone(self):+ head = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=TOOLS, capture_output=True, text=True, env=P.clean_env()).stdout.strip()+ lines = f'refs/heads/x {head} refs/heads/x {head}\n(delete) {H.ZERO} refs/heads/y {"2" * 40}\n' # nothing changes, so no check runs+ r = subprocess.run([sys.executable, str(TOOLS / 'githooks.py'), 'pre-push'], input=lines, capture_output=True, text=True, env=dict(os.environ))+ self.assertEqual(snapshot(self.outer), self.before, r.stdout + r.stderr)+ self.assertEqual((r.returncode, 'nothing to check' in r.stdout), (0, True), r.stdout + r.stderr)++ def test_all_variables_git_exports_to_a_hook_are_removed(self):+ for k in ('GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_COMMON_DIR', 'GIT_PREFIX'):+ with mock.patch.dict(os.environ, {k: 'x'}):+ self.assertNotIn(k, P.clean_env())+++class PushedPaths(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(prefix='test-githooks-')+ self.addCleanup(self.tmp.cleanup)+ self.repo = Path(self.tmp.name)+ git(self.repo, 'init', '-q', '-b', 'main')+ self.commit('README.md', 'a')+ git(self.repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD')+ self.main = git(self.repo, 'rev-parse', 'HEAD')+ patcher = mock.patch.object(H, 'ROOT', self.repo)+ patcher.start()+ self.addCleanup(patcher.stop)++ def commit(self, path, text):+ f = self.repo / path+ f.parent.mkdir(parents=True, exist_ok=True)+ f.write_text(text)+ git(self.repo, 'add', '-A')+ git(self.repo, 'commit', '-q', '-m', path)+ return git(self.repo, 'rev-parse', 'HEAD')++ def test_new_branch_is_compared_with_origin_main(self):+ git(self.repo, 'checkout', '-q', '-b', 'feature')+ self.commit('patches/0001-x.patch', 'p')+ head = self.commit('docs.md', 'd')+ paths = H.pushed_paths([f'refs/heads/feature {head} refs/heads/feature {H.ZERO}'])+ self.assertEqual(paths, {'patches/0001-x.patch', 'docs.md'})++ def test_known_remote_sha_is_the_base(self):+ git(self.repo, 'checkout', '-q', '-b', 'feature')+ old = self.commit('patches/0001-x.patch', 'p')+ head = self.commit('docs.md', 'd')+ self.assertEqual(H.pushed_paths([f'refs/heads/feature {head} refs/heads/feature {old}']), {'docs.md'})++ def test_unknown_remote_sha_falls_back_to_origin_main(self):+ git(self.repo, 'checkout', '-q', '-b', 'feature')+ head = self.commit('tools/a.py', 'x')+ self.assertEqual(H.pushed_paths([f'refs/heads/feature {head} refs/heads/feature {"1" * 40}']), {'tools/a.py'})++ def test_a_delete_pushes_no_code(self):+ self.assertEqual(H.pushed_paths([f'(delete) {H.ZERO} refs/heads/old {self.main}']), set())++ def test_no_base_means_everything(self):+ git(self.repo, 'update-ref', '-d', 'refs/remotes/origin/main')+ git(self.repo, 'checkout', '-q', '-b', 'feature')+ head = self.commit('docs.md', 'd')+ self.assertIsNone(H.pushed_paths([f'refs/heads/feature {head} refs/heads/feature {H.ZERO}']))++ def run_hook(self, paths_changed):+ git(self.repo, 'checkout', '-q', '-b', 'feature')+ head = self.commit(paths_changed, 'x')+ out = io.StringIO()+ with contextlib.redirect_stdout(out):+ code = H.pre_push([f'refs/heads/feature {head} refs/heads/feature {H.ZERO}'])+ return code, out.getvalue()++ def test_docs_only_push_runs_nothing(self):+ with mock.patch.object(H, 'sh', side_effect=AssertionError('nothing may run')):+ code, out = self.run_hook('README.md')+ self.assertEqual(code, 0)+ self.assertIn('nothing to check', out)++ def test_a_failing_check_stops_the_push_with_the_command(self):+ err = io.StringIO()+ with mock.patch.object(H, 'sh', return_value=1) as run, contextlib.redirect_stderr(err):+ code, _ = self.run_hook('patches/0036-x.patch')+ self.assertEqual(code, 1)+ self.assertEqual(run.call_args.args[0], 'python3 tools/engine.py check')+ self.assertIn('Reproduce: python3 tools/engine.py check', err.getvalue())++ def test_a_patch_push_does_not_sync_the_engine_or_run_slow_checks(self):+ with mock.patch.object(H, 'sh', return_value=0) as run:+ code, _ = self.run_hook('.upstream-ref')+ self.assertEqual(code, 0)+ self.assertEqual([c.args[0] for c in run.call_args_list], ['python3 tools/engine.py check'])++ def test_pre_commit_checks_only_staged_patches(self):+ self.repo.joinpath('docs.md').write_text('d')+ git(self.repo, 'add', 'docs.md')+ with mock.patch.object(H, 'sh', side_effect=AssertionError('nothing may run')), contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(H.pre_commit(), 0)+ self.repo.joinpath('tools').mkdir()+ self.repo.joinpath('tools/a.py').write_text('x')+ self.repo.joinpath('patches').mkdir()+ self.repo.joinpath('patches/series').write_text('x')+ git(self.repo, 'add', '-A')+ with mock.patch.object(H, 'sh', return_value=0) as run, contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(H.pre_commit(), 0)+ self.assertEqual([c.args[0] for c in run.call_args_list], ['python3 tools/engine.py check'])+++class InstallHooks(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(prefix='test-hooksinstall-')+ self.addCleanup(self.tmp.cleanup)+ self.repo = Path(self.tmp.name) / 'repo'+ self.repo.mkdir()+ git(self.repo, 'init', '-q', '-b', 'main')+ (self.repo / '.githooks').mkdir()+ (self.repo / '.githooks/pre-push').write_text('#!/bin/sh\n')+ git(self.repo, 'add', '-A')+ git(self.repo, 'commit', '-q', '-m', 'init')++ def install(self, root=None):+ out = io.StringIO()+ with mock.patch.dict(os.environ, ENV, clear=True), contextlib.redirect_stdout(out):+ E.install_hooks(root or self.repo)+ return out.getvalue()++ def path(self, root=None):+ return subprocess.run(['git', 'config', '--get', 'core.hooksPath'], cwd=root or self.repo, capture_output=True, text=True, env=ENV).stdout.strip()++ def test_sets_it_when_unset_and_stays_quiet_after(self):+ self.assertIn('set core.hooksPath', self.install())+ self.assertEqual(self.path(), '.githooks')+ self.assertEqual(self.install(), '')++ def test_keeps_another_path_and_warns(self):+ git(self.repo, 'config', 'core.hooksPath', '/somewhere/else')+ out = self.install()+ self.assertEqual(self.path(), '/somewhere/else')+ self.assertIn('WARNING', out)+ self.assertIn('git config core.hooksPath .githooks', out)++ def test_a_worktree_inherits_it(self):+ wt = Path(self.tmp.name) / 'wt'+ git(self.repo, 'worktree', 'add', '-q', '-b', 'other', str(wt))+ self.assertEqual(self.path(wt), '')+ self.install()+ self.assertEqual(self.path(wt), '.githooks')+ self.assertEqual(self.install(wt), '')++ def test_a_checkout_without_hooks_is_left_alone(self):+ bare = Path(self.tmp.name) / 'plain'+ bare.mkdir()+ git(bare, 'init', '-q')+ self.assertEqual(self.install(bare), '')+ self.assertEqual(self.path(bare), '')+++def blocked(command, cwd='.'):+ return G.verdict(command, cwd) is not None+++class ClaudeGuard(unittest.TestCase):+ def test_push_to_main_or_master_is_blocked(self):+ for c in ('git push origin main', 'git push origin master', 'git push -u origin main', 'git push origin HEAD:main',+ 'git push origin feature:main', 'git push origin HEAD:refs/heads/main', 'git push origin +main',+ 'git push --force origin main', 'git push -f origin main', 'git push --force-with-lease origin main',+ 'git -C /some/repo push origin main', 'cd repo && git push origin main', 'git fetch; git push origin main',+ 'sudo git push origin main', 'GIT_TRACE=1 git push origin main', 'bash -c "git push origin main"',+ 'git push --delete origin main', 'git push --all origin', 'git push --mirror'):+ self.assertTrue(blocked(c), c)++ def test_push_of_a_branch_is_allowed(self):+ for c in ('git push origin v0lumehi/pre-push-checks', 'git push -u origin my-branch', 'git push origin HEAD:my-branch',+ 'git push --force origin my-branch', 'git push origin main-fix', 'git push origin v1.0',+ 'git push https://x-access-token:[email protected]/LNPANDY/NX2Apple.git v0lumehi/foo', 'git pull origin main',+ 'git fetch origin main', 'git checkout main', 'git merge main', 'git log origin/main..HEAD'):+ self.assertFalse(blocked(c), c)++ def test_text_that_only_mentions_a_push_is_allowed(self):+ self.assertFalse(blocked('echo "git push origin main"'))+ self.assertFalse(blocked('git commit -m "never git push origin main"'))+ self.assertFalse(blocked('gh pr create --title "no git push to main"'))++ def test_a_bare_push_depends_on_the_current_branch(self):+ with tempfile.TemporaryDirectory(prefix='test-guard-') as d:+ git(d, 'init', '-q', '-b', 'main')+ git(d, 'commit', '-q', '--allow-empty', '-m', 'x')+ self.assertTrue(blocked('git push', d))+ self.assertTrue(blocked('git push origin', d))+ self.assertTrue(blocked('git push origin HEAD', d))+ git(d, 'checkout', '-q', '-b', 'feature')+ self.assertFalse(blocked('git push', d))+ self.assertFalse(blocked('git push origin HEAD', d))++ def test_no_verify_is_blocked_on_commit_and_push(self):+ for c in ('git commit --no-verify -m x', 'git commit -n -m x', 'git commit -nm x', 'git push --no-verify origin feature'):+ self.assertTrue(blocked(c), c)+ self.assertFalse(blocked('git commit -am "fix"'))+ self.assertFalse(blocked('git commit --amend'))+ self.assertFalse(blocked('git push -n origin feature'))++ def test_unbalanced_quotes_still_catch_a_push_to_main(self):+ self.assertTrue(blocked('git push origin main "'))++ def run_guard(self, payload):+ return subprocess.run([sys.executable, str(TOOLS / 'claude_guard.py')], input=payload, capture_output=True, text=True)++ def test_hook_protocol(self):+ import json+ r = self.run_guard(json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'git push origin main'}, 'cwd': str(TOOLS)}))+ self.assertEqual(r.returncode, 2)+ self.assertIn('PR', r.stderr)+ r = self.run_guard(json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'git push origin feature'}, 'cwd': str(TOOLS)}))+ self.assertEqual((r.returncode, r.stderr), (0, ''))+ self.assertEqual(self.run_guard('not json').returncode, 0)++ def test_settings_json_wires_both_hooks(self):+ import json+ s = json.loads((TOOLS.parent / '.claude/settings.json').read_text())['hooks']+ self.assertIn('tools/engine.py" hook', s['SessionStart'][0]['hooks'][0]['command'])+ pre = s['PreToolUse'][0]+ self.assertEqual(pre['matcher'], 'Bash')+ self.assertIn('tools/claude_guard.py', pre['hooks'][0]['command'])+++if __name__ == '__main__':+ unittest.main()diff --git a/tools/tests/test_patches.py b/tools/tests/test_patches.pyindex 734562c0..0fb33059 100644--- a/tools/tests/test_patches.py+++ b/tools/tests/test_patches.py@@ -76,8 +76,8 @@ class Queue(unittest.TestCase):def mkgit(cwd, *a):- 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=os.devnull, GIT_CONFIG_SYSTEM=os.devnull)+ env = P.clean_env(GIT_AUTHOR_NAME='t', GIT_AUTHOR_EMAIL='[email protected]', GIT_COMMITTER_NAME='t', GIT_COMMITTER_EMAIL='[email protected]',+ GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_SYSTEM=os.devnull) # no GIT_DIR: a test must never reach the repository that runs itr = subprocess.run(['git', '-c', 'commit.gpgsign=false', *a], cwd=cwd, capture_output=True, text=True, env=env)if r.returncode: raise AssertionError(f'git {a}: {r.stderr}')return r.stdout.strip()