Merge pull request 'feat(git): refuse git push to main with a Claude Code hook' (#282) from feat/178-refuse-push-to-main into main
Reviewed-on: #282
This commit is contained in:
commit
51f9d6dbd2
9 files changed
+598
-6
No files matched your search
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "holocron",
|
"name": "holocron",
|
||||||
"description": "AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows.",
|
"description": "AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows.",
|
||||||
"version": "0.9.2",
|
"version": "0.9.3",
|
||||||
"owner": {
|
"owner": {
|
||||||
"name": "Mortis",
|
"name": "Mortis",
|
||||||
"url": "https://git.rkdr.net/Mortis/"
|
"url": "https://git.rkdr.net/Mortis/"
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
{
|
{
|
||||||
"name": "git",
|
"name": "git",
|
||||||
"description": "Skills and agents for working with a local Git clone over the git wire protocol, and for authoring and running the pre-commit hooks that guard it.",
|
"description": "Skills and agents for working with a local Git clone over the git wire protocol, and for authoring and running the pre-commit hooks that guard it.",
|
||||||
"version": "1.3.9",
|
"version": "1.4.0",
|
||||||
"category": "Version Control",
|
"category": "Version Control",
|
||||||
"source": "./plugins/git"
|
"source": "./plugins/git"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
name: holocron
|
name: holocron
|
||||||
version: 0.9.2
|
version: 0.9.3
|
||||||
description: AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows.
|
description: AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows.
|
||||||
license: MIT
|
license: MIT
|
||||||
|
|
||||||
@@ -86,6 +86,9 @@ executables:
|
|||||||
# full-identity, version-in-key convention as above, kept by the same check.
|
# full-identity, version-in-key convention as above, kept by the same check.
|
||||||
git.rkdr.net/Mortis/Holocron/plugins/delivery#0.8.1:
|
git.rkdr.net/Mortis/Holocron/plugins/delivery#0.8.1:
|
||||||
hooks: true
|
hooks: true
|
||||||
|
# git ships the hook that refuses a push to main.
|
||||||
|
git.rkdr.net/Mortis/Holocron/plugins/git#1.4.0:
|
||||||
|
hooks: true
|
||||||
|
|
||||||
marketplace:
|
marketplace:
|
||||||
# apm's Claude marketplace mapper only emits description:/version: into the
|
# apm's Claude marketplace mapper only emits description:/version: into the
|
||||||
@@ -93,7 +96,7 @@ marketplace:
|
|||||||
# top-level apm.yml description:/version: above are NOT inherited into the
|
# top-level apm.yml description:/version: above are NOT inherited into the
|
||||||
# compiled output despite being used elsewhere (e.g. by `apm audit`).
|
# compiled output despite being used elsewhere (e.g. by `apm audit`).
|
||||||
description: AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows.
|
description: AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows.
|
||||||
version: 0.9.2
|
version: 0.9.3
|
||||||
owner:
|
owner:
|
||||||
name: Mortis
|
name: Mortis
|
||||||
url: https://git.rkdr.net/Mortis/
|
url: https://git.rkdr.net/Mortis/
|
||||||
|
|||||||
@@ -127,6 +127,9 @@ passed. Failed tasks are shown in the PR comment for the approver to judge. Deci
|
|||||||
cluster or state and print no secret: anything not on the list is denied, so an unlisted mutating
|
cluster or state and print no secret: anything not on the list is denied, so an unlisted mutating
|
||||||
subcommand fails safe. Codex cannot ask, so odd jobs are
|
subcommand fails safe. Codex cannot ask, so odd jobs are
|
||||||
denied there; an unrecognised runtime is treated the same way.
|
denied there; an unrecognised runtime is treated the same way.
|
||||||
|
- *Amended 2026-12-04 ([git push-to-main hook](https://git.rkdr.net/Mortis/Holocron/issues/178)): `git`
|
||||||
|
ships its own guardrail hook beside `delivery`'s, refusing a `git push` to `main` on Claude Code
|
||||||
|
only. It fails open and has an opt-out; branch protection stays the real control.*
|
||||||
- *Amended 2026-11-25 ([Pre-merge Ansible dry run without exposing production credentials](https://git.rkdr.net/Mortis/Holocron/issues/200)):
|
- *Amended 2026-11-25 ([Pre-merge Ansible dry run without exposing production credentials](https://git.rkdr.net/Mortis/Holocron/issues/200)):
|
||||||
the reopened Ansible `--check --diff` now runs in CI from the base branch's copy with production
|
the reopened Ansible `--check --diff` now runs in CI from the base branch's copy with production
|
||||||
credentials — automatic on human-authored PRs, gated on bot PRs by an allowlisted human's
|
credentials — automatic on human-authored PRs, gated on bot PRs by an allowlisted human's
|
||||||
|
|||||||
+2
-1
@@ -1357,7 +1357,8 @@ every key stays an accurate record of what was approved.
|
|||||||
|
|
||||||
It covers every plugin that ships executables, not one named package. The script scans
|
It covers every plugin that ships executables, not one named package. The script scans
|
||||||
`plugins/*/` and treats a plugin as shipping executables when `plugins/<name>/.apm/hooks/` or
|
`plugins/*/` and treats a plugin as shipping executables when `plugins/<name>/.apm/hooks/` or
|
||||||
`plugins/<name>/bin/` exists — kyberforge ships both, delivery ships a guard hook. For each one it
|
`plugins/<name>/bin/` exists — kyberforge ships both, delivery ships a guard hook,
|
||||||
|
git ships a hook that refuses a push to `main`. For each one it
|
||||||
reads `name:` and `version:` from `plugins/<name>/apm.yml` and asserts root `apm.yml` carries the
|
reads `name:` and `version:` from `plugins/<name>/apm.yml` and asserts root `apm.yml` carries the
|
||||||
`<identity>#<version>` key under `executables.allow`. The `name:` must equal the directory name, so
|
`<identity>#<version>` key under `executables.allow`. The `name:` must equal the directory name, so
|
||||||
one that differs fails rather than being guessed at. Every failing package is
|
one that differs fails rather than being guessed at. Every failing package is
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"hooks": {
|
||||||
|
"PreToolUse": [
|
||||||
|
{
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"command": "${CLAUDE_PLUGIN_ROOT}/.apm/hooks/refuse-push-to-main.py",
|
||||||
|
"timeout": 10,
|
||||||
|
"type": "command"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"matcher": "Bash"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
+265
@@ -0,0 +1,265 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""PreToolUse hook: refuse a `git push` that can update `main`.
|
||||||
|
|
||||||
|
A guardrail against accidents, not a security boundary: whatever it cannot read
|
||||||
|
in the command line goes through. Limits and opt-out: the git plugin's README.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import fnmatch
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
MAIN_NAMES = ("main", "heads/main", "refs/heads/main")
|
||||||
|
|
||||||
|
HEREDOC = re.compile(
|
||||||
|
r"""(?<!<)<<(-?)[ \t]*(?:'([^']+)'|"([^"]+)"|\\?([^\s;&|()<>'"`\\]+))"""
|
||||||
|
)
|
||||||
|
WORD = r"""(?:[^ \t\r\n;&|()`<>'"\\]|\\.|'[^']*'|"(?:[^"\\]|\\.)*")+"""
|
||||||
|
TOKEN = re.compile(
|
||||||
|
rf"""(?P<skip>[ \t\r]+|\#[^\n]*|(?:\d*|&)[<>]+[&|]?[ \t]*(?:{WORD})?)
|
||||||
|
|(?P<separator>[;&|()`\n]+)
|
||||||
|
|(?P<word>{WORD})""",
|
||||||
|
re.S | re.X,
|
||||||
|
)
|
||||||
|
|
||||||
|
ASSIGNMENT = re.compile(r"\w+=")
|
||||||
|
SHELL_KEYWORDS = {"!", "{", "if", "then", "elif", "else", "while", "until", "do"}
|
||||||
|
WRAPPERS = {
|
||||||
|
"rtk",
|
||||||
|
"proxy",
|
||||||
|
"command",
|
||||||
|
"env",
|
||||||
|
"exec",
|
||||||
|
"nohup",
|
||||||
|
"sudo",
|
||||||
|
"time",
|
||||||
|
"timeout",
|
||||||
|
"xargs",
|
||||||
|
}
|
||||||
|
WRAPPER_ARGUMENT = re.compile(r"-|\d+[smhd]?$")
|
||||||
|
|
||||||
|
SHORT_PUSH_OPTIONS = {"h": "--help", "n": "--dry-run"}
|
||||||
|
GIT_OPTIONS_WITH_VALUE = {"-c", "--git-dir", "--work-tree", "--namespace", "--config-env"}
|
||||||
|
REBASE_OPTIONS_WITH_VALUE = {
|
||||||
|
"--onto",
|
||||||
|
"-s",
|
||||||
|
"--strategy",
|
||||||
|
"-X",
|
||||||
|
"--strategy-option",
|
||||||
|
"-x",
|
||||||
|
"--exec",
|
||||||
|
}
|
||||||
|
PUSH_OPTIONS_WITH_VALUE = {
|
||||||
|
"--repo",
|
||||||
|
"--push-option",
|
||||||
|
"--receive-pack",
|
||||||
|
"--exec",
|
||||||
|
"--recurse-submodules",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def strip_heredocs(command):
|
||||||
|
lines = command.split("\n")
|
||||||
|
# A `<<` that nothing closes is text or arithmetic, not a heredoc.
|
||||||
|
closing_lines = {line.lstrip("\t") for line in lines}
|
||||||
|
kept, pending = [], []
|
||||||
|
for line in lines:
|
||||||
|
if pending:
|
||||||
|
dash, delimiter = pending[0]
|
||||||
|
if (line.lstrip("\t") if dash else line) == delimiter:
|
||||||
|
pending.pop(0)
|
||||||
|
continue
|
||||||
|
kept.append(line)
|
||||||
|
for dash, *quotings in HEREDOC.findall(line):
|
||||||
|
delimiter = "".join(quotings)
|
||||||
|
if delimiter in closing_lines:
|
||||||
|
pending.append((dash, delimiter))
|
||||||
|
return "\n".join(kept)
|
||||||
|
|
||||||
|
|
||||||
|
def simple_commands(command):
|
||||||
|
"""Split a command line into word lists; None when it does not parse.
|
||||||
|
|
||||||
|
A subshell's parentheses come out as the commands ["("] and [")"].
|
||||||
|
"""
|
||||||
|
command = re.sub(r"(?<!\\)\\\n", "", strip_heredocs(command))
|
||||||
|
commands, position = [[]], 0
|
||||||
|
while position < len(command):
|
||||||
|
token = TOKEN.match(command, position)
|
||||||
|
if not token:
|
||||||
|
return None
|
||||||
|
if token["separator"]:
|
||||||
|
commands += [[c] for c in token["separator"] if c in "()"]
|
||||||
|
commands.append([])
|
||||||
|
elif token["word"]:
|
||||||
|
commands[-1].append("".join(shlex.split(token["word"])))
|
||||||
|
position = token.end()
|
||||||
|
return commands
|
||||||
|
|
||||||
|
|
||||||
|
def strip_prefixes(words):
|
||||||
|
wrapped = False
|
||||||
|
for index, word in enumerate(words):
|
||||||
|
if word in WRAPPERS:
|
||||||
|
wrapped = True
|
||||||
|
elif not (
|
||||||
|
word in SHELL_KEYWORDS
|
||||||
|
or ASSIGNMENT.match(word)
|
||||||
|
or (wrapped and WRAPPER_ARGUMENT.match(word))
|
||||||
|
):
|
||||||
|
return words[index:]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def split_git_command(arguments, directory):
|
||||||
|
"""(directory it runs in, subcommand, the subcommand's arguments)."""
|
||||||
|
rest = iter(arguments)
|
||||||
|
for word in rest:
|
||||||
|
if word == "-C":
|
||||||
|
directory = resolve(directory, next(rest, ""))
|
||||||
|
elif word in GIT_OPTIONS_WITH_VALUE:
|
||||||
|
next(rest, None)
|
||||||
|
elif not word.startswith("-"):
|
||||||
|
return directory, word, list(rest)
|
||||||
|
return directory, "", []
|
||||||
|
|
||||||
|
|
||||||
|
def resolve(directory, target):
|
||||||
|
# Not normalised: a target such as `$X/..` must stay a path that does not
|
||||||
|
# exist, so that the branch lookup fails and the push is allowed.
|
||||||
|
return os.path.join(directory, os.path.expanduser(target))
|
||||||
|
|
||||||
|
|
||||||
|
def changes_branch(subcommand, arguments):
|
||||||
|
if subcommand == "branch":
|
||||||
|
return not {"-m", "-M", "--move"}.isdisjoint(arguments)
|
||||||
|
if subcommand == "rebase": # `git rebase <upstream> <branch>` checks out <branch>
|
||||||
|
rest, names = iter(arguments), []
|
||||||
|
for argument in rest:
|
||||||
|
if argument in REBASE_OPTIONS_WITH_VALUE:
|
||||||
|
next(rest, None)
|
||||||
|
elif not argument.startswith("-"):
|
||||||
|
names.append(argument)
|
||||||
|
return len(names) > 1
|
||||||
|
return subcommand == "switch" or (subcommand == "checkout" and "--" not in arguments)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_push(arguments):
|
||||||
|
"""(long-form option names, refspecs) of a git push."""
|
||||||
|
options, positional = set(), []
|
||||||
|
rest = iter(arguments)
|
||||||
|
for argument in rest:
|
||||||
|
if argument == "--":
|
||||||
|
positional.extend(rest)
|
||||||
|
elif argument.startswith("--"):
|
||||||
|
options.add(argument.split("=")[0])
|
||||||
|
if argument in PUSH_OPTIONS_WITH_VALUE:
|
||||||
|
next(rest, None)
|
||||||
|
elif argument.startswith("-"):
|
||||||
|
flags, push_option, value = argument[1:].partition("o")
|
||||||
|
options.update(SHORT_PUSH_OPTIONS.get(f, f) for f in flags)
|
||||||
|
if push_option and not value:
|
||||||
|
next(rest, None)
|
||||||
|
else:
|
||||||
|
positional.append(argument)
|
||||||
|
return options, positional[1:]
|
||||||
|
|
||||||
|
|
||||||
|
def updates_main(arguments, on_main):
|
||||||
|
"""Whether a push can update main. `on_main` is called only when it matters."""
|
||||||
|
options, refspecs = parse_push(arguments)
|
||||||
|
if options & {"--dry-run", "--help"}:
|
||||||
|
return False
|
||||||
|
if options & {"--all", "--branches", "--mirror"}:
|
||||||
|
return True
|
||||||
|
if not refspecs:
|
||||||
|
return "--tags" not in options and on_main()
|
||||||
|
|
||||||
|
rest = iter(refspecs)
|
||||||
|
for refspec in rest:
|
||||||
|
if refspec == "tag":
|
||||||
|
next(rest, None)
|
||||||
|
continue
|
||||||
|
source, colon, destination = refspec.removeprefix("+").partition(":")
|
||||||
|
if colon and not source and not destination:
|
||||||
|
return True
|
||||||
|
target = destination if colon else source
|
||||||
|
if any(fnmatch.fnmatchcase(name, target) for name in MAIN_NAMES):
|
||||||
|
return True
|
||||||
|
if not colon and source in ("HEAD", "@") and on_main():
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def current_branch_is_main(directory):
|
||||||
|
head = subprocess.run(
|
||||||
|
["git", "-C", directory, "symbolic-ref", "--quiet", "HEAD"], capture_output=True, text=True
|
||||||
|
)
|
||||||
|
return head.stdout.strip() == "refs/heads/main"
|
||||||
|
|
||||||
|
|
||||||
|
def pushes_to_main(command, directory):
|
||||||
|
if "git" not in command or "push" not in command:
|
||||||
|
return False
|
||||||
|
outer_directories = []
|
||||||
|
branch_change = None # (directory, whether it went to main) of the latest one
|
||||||
|
for all_words in simple_commands(command) or []:
|
||||||
|
words = strip_prefixes(all_words)
|
||||||
|
if not words:
|
||||||
|
continue
|
||||||
|
name, arguments = os.path.basename(words[0]), words[1:]
|
||||||
|
if name == "(":
|
||||||
|
outer_directories.append(directory)
|
||||||
|
elif name == ")" and outer_directories:
|
||||||
|
directory = outer_directories.pop()
|
||||||
|
elif name in ("cd", "pushd", "popd"):
|
||||||
|
directory = resolve(directory, words[-1])
|
||||||
|
elif name in ("gh", "tea") and "checkout" in arguments:
|
||||||
|
branch_change = (directory, False)
|
||||||
|
elif name == "git":
|
||||||
|
repo, subcommand, arguments = split_git_command(arguments, directory)
|
||||||
|
# xargs adds refspecs, and another git dir has its own branch.
|
||||||
|
unknown = "xargs" in all_words or any(
|
||||||
|
w.startswith(("GIT_DIR=", "--git-dir")) for w in all_words
|
||||||
|
)
|
||||||
|
|
||||||
|
def on_main():
|
||||||
|
if unknown:
|
||||||
|
return False
|
||||||
|
if branch_change:
|
||||||
|
return branch_change == (repo, True)
|
||||||
|
return current_branch_is_main(repo)
|
||||||
|
|
||||||
|
if changes_branch(subcommand, arguments):
|
||||||
|
names = [a for a in arguments if not a.startswith("-")]
|
||||||
|
branch_change = (repo, subcommand != "branch" and names == ["main"])
|
||||||
|
elif subcommand == "push" and updates_main(arguments, on_main):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# apm deploys this file to Copilot and Codex too, where it must do nothing.
|
||||||
|
if "/.claude/hooks/" not in os.path.abspath(__file__).replace("\\", "/"):
|
||||||
|
return 0
|
||||||
|
if os.environ.get("GIT_ALLOW_PUSH_TO_MAIN") == "1":
|
||||||
|
return 0
|
||||||
|
payload = json.load(sys.stdin)
|
||||||
|
if payload["tool_name"] != "Bash":
|
||||||
|
return 0
|
||||||
|
if pushes_to_main(payload["tool_input"]["command"], payload["cwd"]):
|
||||||
|
print(
|
||||||
|
"Refused: this git push can update main. "
|
||||||
|
"Push a feature branch by name and open a pull request instead.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 2
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -35,9 +35,66 @@ Installing this plugin without `rtk`? Every prefixed command is a plain `git` in
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Skills | `.apm/skills/` | `git-commits`, `git-branches`, `git-history`, `git-remotes`, `git-submodules`, `git-workflow`, `git-worktrees`, `pc-author`, `pc-run` |
|
| Skills | `.apm/skills/` | `git-commits`, `git-branches`, `git-history`, `git-remotes`, `git-submodules`, `git-workflow`, `git-worktrees`, `pc-author`, `pc-run` |
|
||||||
| Agents | `.apm/agents/` | `git-orchestrate` |
|
| Agents | `.apm/agents/` | `git-orchestrate` |
|
||||||
|
| Hooks | `.apm/hooks/` | `refuse-push-to-main.py`, see [Push-to-main hook](#push-to-main-hook) |
|
||||||
|
|
||||||
`.apm/` is the authoring source and the only thing apm deploys (ADR-0024).
|
`.apm/` is the authoring source and the only thing apm deploys (ADR-0024).
|
||||||
|
|
||||||
|
## Push-to-main hook
|
||||||
|
|
||||||
|
On Claude Code, a `PreToolUse` hook refuses a Bash `git push` that can update `main`:
|
||||||
|
|
||||||
|
- an explicit destination: `main`, `HEAD:main`, `<branch>:main`, `refs/heads/main`, or deleting `main`
|
||||||
|
- a bare `git push`, `HEAD` or `@` while `main` is checked out
|
||||||
|
- a bulk push: `--all`, `--mirror`, `:`, or a wildcard refspec that covers `main`
|
||||||
|
- any of these with `--force` or `--force-with-lease`
|
||||||
|
|
||||||
|
Pushes to other branches, tag pushes and `--dry-run` go through. apm also deploys the files to Copilot and Codex, where the hook does nothing.
|
||||||
|
|
||||||
|
### Limits
|
||||||
|
|
||||||
|
The hook is a guardrail against accidents. Server-side branch protection is the real control. If the hook itself fails, the push goes through. It does not see:
|
||||||
|
|
||||||
|
- git aliases, shell variables such as `$BRANCH`, scripts, `bash -c`, command substitution inside double quotes, or pushes made through an MCP server
|
||||||
|
- git config that redirects a push (`push.default=upstream`, `remote.<name>.push`)
|
||||||
|
- a push behind a wrapper option that takes a separate value, such as `sudo -u <user>` or `env -u <name>`
|
||||||
|
- a command line the hook cannot parse, for example `$'...'` with an escaped quote
|
||||||
|
- a bare `git push`, `HEAD` or `@` in a command that makes the branch unknown:
|
||||||
|
- an earlier `git switch` or `git checkout` to anything but a literal `main`, `git branch -m`, `git rebase <upstream> <branch>`, `gh pr checkout` or `tea pr checkout`
|
||||||
|
- an earlier `cd` to a path that is not literal
|
||||||
|
- `--git-dir`, `GIT_DIR=` or `xargs` on the push itself
|
||||||
|
|
||||||
|
### Opt-out
|
||||||
|
|
||||||
|
To allow pushes to `main`, set the variable under `env` in `.claude/settings.json`, or in `.claude/settings.local.json` for yourself only:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"env": {
|
||||||
|
"GIT_ALLOW_PUSH_TO_MAIN": "1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Claude Code puts `env` values into its own environment, which hooks inherit. Setting the variable inside the command (`GIT_ALLOW_PUSH_TO_MAIN=1 git push`) has no effect. After you remove the setting, restart Claude Code for the hook to refuse again.
|
||||||
|
|
||||||
|
### Approval
|
||||||
|
|
||||||
|
The hook is an executable primitive, so whether it deploys depends on the `executables:` block in the consuming project's `apm.yml`:
|
||||||
|
|
||||||
|
- **No `executables:` block:** hooks deploy without approval.
|
||||||
|
- **With an `executables:` block:** the hook is parked until it is granted. Grant it in one of two ways, then run `apm install` and commit the `executables` entry:
|
||||||
|
- `apm approve` writes the entry and pins it to the hook's content, so a later change to the script needs approval again.
|
||||||
|
- A hand-written entry under the full package identity is not pinned:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
executables:
|
||||||
|
allow:
|
||||||
|
git.rkdr.net/Mortis/Holocron/plugins/git:
|
||||||
|
hooks: true
|
||||||
|
```
|
||||||
|
|
||||||
|
The first `apm approve` in a project creates the block and so turns the gate on. The next install then parks every other package's unapproved executables.
|
||||||
|
|
||||||
## Author
|
## Author
|
||||||
|
|
||||||
Defame1297
|
Defame1297
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
name: git
|
name: git
|
||||||
version: 1.3.9
|
version: 1.4.0
|
||||||
description: Skills and agents for working with a local Git clone over the git wire protocol, and for authoring and running the pre-commit hooks that guard it.
|
description: Skills and agents for working with a local Git clone over the git wire protocol, and for authoring and running the pre-commit hooks that guard it.
|
||||||
author:
|
author:
|
||||||
name: Mortis
|
name: Mortis
|
||||||
|
|||||||
Executable
+247
@@ -0,0 +1,247 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Tests for plugins/git/.apm/hooks/refuse-push-to-main.py, the PreToolUse hook
|
||||||
|
# that refuses a `git push` to `main` (#178).
|
||||||
|
#
|
||||||
|
# The hook acts only when run from a .claude/hooks/ path, so it is copied to the
|
||||||
|
# path apm deploys it to and driven with real payloads against fixture repos.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_COMMON_DIR
|
||||||
|
unset GIT_ALLOW_PUSH_TO_MAIN
|
||||||
|
|
||||||
|
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
HOOKS_DIR="$REPO_ROOT/plugins/git/.apm/hooks"
|
||||||
|
SRC="$HOOKS_DIR/refuse-push-to-main.py"
|
||||||
|
PASS=0
|
||||||
|
FAIL=0
|
||||||
|
|
||||||
|
pass() { PASS=$((PASS + 1)); }
|
||||||
|
fail() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }
|
||||||
|
|
||||||
|
command -v python3 > /dev/null 2>&1 || { echo "python3 required"; exit 77; }
|
||||||
|
[[ -f "$SRC" ]] || { echo "FAIL: $SRC does not exist"; exit 1; }
|
||||||
|
|
||||||
|
WORK="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$WORK"' EXIT
|
||||||
|
|
||||||
|
for d in .claude/hooks/git/.apm/hooks .github/hooks/scripts/git/.apm/hooks \
|
||||||
|
.codex/hooks/git/.apm/hooks elsewhere; do
|
||||||
|
mkdir -p "$WORK/$d"
|
||||||
|
cp "$SRC" "$WORK/$d/"
|
||||||
|
done
|
||||||
|
HOOK="$WORK/.claude/hooks/git/.apm/hooks/refuse-push-to-main.py"
|
||||||
|
|
||||||
|
git init -q -b main "$WORK/on-main"
|
||||||
|
git init -q -b feat "$WORK/on-feat"
|
||||||
|
|
||||||
|
# decision <script> <cwd> <command> -> allow|refuse|error(...)
|
||||||
|
# The payload is escaped in bash because a Python start per case doubles the run
|
||||||
|
# time. The timeout is the one in hooks.json.
|
||||||
|
decision() {
|
||||||
|
local command="$3" out rc=0
|
||||||
|
command="${command//\\/\\\\}"
|
||||||
|
command="${command//\"/\\\"}"
|
||||||
|
command="${command//$'\n'/\\n}"
|
||||||
|
command="${command//$'\t'/\\t}"
|
||||||
|
out="$(timeout 10 "$1" 2>&1 <<< "{\"tool_name\":\"Bash\",\"cwd\":\"$2\",\"tool_input\":{\"command\":\"$command\"}}")" || rc=$?
|
||||||
|
if [[ $rc -eq 0 && -z "$out" ]]; then
|
||||||
|
echo allow
|
||||||
|
elif [[ $rc -eq 2 && "$out" == *main* ]]; then
|
||||||
|
echo refuse
|
||||||
|
else
|
||||||
|
echo "error($rc: $out)"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# expect <allow|refuse> <main|feat> <command>
|
||||||
|
expect() {
|
||||||
|
local got
|
||||||
|
got="$(decision "$HOOK" "$WORK/on-$2" "$3")"
|
||||||
|
if [[ "$got" == "$1" ]]; then pass; else fail "on $2: want $1, got $got: ${3:0:200}"; fi
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "== Refused from any branch"
|
||||||
|
while IFS= read -r args; do
|
||||||
|
expect refuse feat "git push $args"
|
||||||
|
done << 'CASES'
|
||||||
|
origin main
|
||||||
|
origin +main
|
||||||
|
origin heads/main
|
||||||
|
origin refs/heads/main
|
||||||
|
origin HEAD:main
|
||||||
|
origin feat:main
|
||||||
|
origin feat:refs/heads/main
|
||||||
|
origin main --tags
|
||||||
|
origin :main
|
||||||
|
-d origin main
|
||||||
|
--delete origin main
|
||||||
|
origin --all
|
||||||
|
origin --branches
|
||||||
|
--mirror origin
|
||||||
|
origin :
|
||||||
|
origin +:
|
||||||
|
origin refs/heads/*:refs/heads/*
|
||||||
|
origin 'refs/heads/*:refs/heads/*'
|
||||||
|
origin feat main
|
||||||
|
-o ci.skip origin "main"
|
||||||
|
CASES
|
||||||
|
expect refuse main "git push origin main"
|
||||||
|
|
||||||
|
# Every prefix with an explicit destination and with a branch-dependent form.
|
||||||
|
for prefix in "git push --force" "git push -f" "git push --force-with-lease" \
|
||||||
|
"git push --force-with-lease=main:abc123" "rtk git push" "git -c k=v push" \
|
||||||
|
"git -C . push" "git add . && git push"; do
|
||||||
|
expect refuse feat "$prefix origin main"
|
||||||
|
expect refuse feat "$prefix origin HEAD:main"
|
||||||
|
expect refuse main "$prefix"
|
||||||
|
expect refuse main "$prefix origin HEAD"
|
||||||
|
expect allow feat "$prefix"
|
||||||
|
expect allow feat "$prefix origin HEAD"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "== Refused while on main, allowed on a feature branch"
|
||||||
|
while IFS= read -r args; do
|
||||||
|
expect refuse main "git push $args"
|
||||||
|
expect allow feat "git push $args"
|
||||||
|
done << 'CASES'
|
||||||
|
|
||||||
|
origin
|
||||||
|
--follow-tags
|
||||||
|
-o ci.skip origin
|
||||||
|
--repo=origin
|
||||||
|
origin HEAD
|
||||||
|
origin @
|
||||||
|
origin 2>&1 | tail -5
|
||||||
|
CASES
|
||||||
|
expect refuse feat "git -C $WORK/on-main push"
|
||||||
|
expect refuse feat "git -C ../on-main push origin HEAD"
|
||||||
|
expect allow main "git -C $WORK/on-feat push"
|
||||||
|
|
||||||
|
echo "== Allowed from any branch"
|
||||||
|
while IFS= read -r cmd; do
|
||||||
|
expect allow main "$cmd"
|
||||||
|
done << 'CASES'
|
||||||
|
git push origin feat
|
||||||
|
git push -u origin feat
|
||||||
|
git push origin main:feat
|
||||||
|
git push origin main-fix
|
||||||
|
git push origin feature/main
|
||||||
|
git push --tags
|
||||||
|
git push origin --tags
|
||||||
|
git push origin tag v1
|
||||||
|
git push origin tag main
|
||||||
|
git push origin refs/tags/main
|
||||||
|
git push --dry-run origin main
|
||||||
|
git push --help
|
||||||
|
git push -h
|
||||||
|
git push -n origin main
|
||||||
|
git push -o main origin feat
|
||||||
|
git push origin 'refs/heads/feat/*:refs/heads/feat/*'
|
||||||
|
git status
|
||||||
|
git log origin main
|
||||||
|
git commit -m "git push origin main"
|
||||||
|
git commit -m "wip; git push origin main"
|
||||||
|
echo git push origin main
|
||||||
|
echo "git push origin main"
|
||||||
|
git switch -c feat && git push -u origin HEAD
|
||||||
|
git checkout -b feat && git push
|
||||||
|
cd /somewhere/else && git push
|
||||||
|
git push origin "main
|
||||||
|
CASES
|
||||||
|
|
||||||
|
echo "== Earlier branch or directory changes"
|
||||||
|
while IFS=$'\t' read -r want branch cmd; do
|
||||||
|
expect "$want" "$branch" "${cmd//WORK/$WORK}"
|
||||||
|
done << 'CASES'
|
||||||
|
allow main gh pr checkout 5 && git push
|
||||||
|
allow main tea pr checkout 5 && git push
|
||||||
|
allow main rtk gh pr checkout 5 && git push
|
||||||
|
allow main git branch -m feat && git push -u origin HEAD
|
||||||
|
allow main git branch -M feat && git push -u origin HEAD
|
||||||
|
allow main git branch --move feat && git push -u origin HEAD
|
||||||
|
allow main git switch feat && cd sub && git push
|
||||||
|
allow main git checkout main && git pull && git checkout -b x && git push -u origin HEAD
|
||||||
|
refuse main git branch -a && git push
|
||||||
|
allow feat git switch main && git pull && git rebase main feat && git push
|
||||||
|
allow main git fetch && git rebase origin/main feat && git push --force-with-lease
|
||||||
|
allow main git rebase --onto main old feat && git push
|
||||||
|
refuse main git rebase origin/main && git push
|
||||||
|
refuse main git rebase --onto origin/main old && git push
|
||||||
|
refuse main git rebase -x true origin/main && git push
|
||||||
|
allow feat cd WORK/on-main && git switch main && git pull; cd WORK/on-feat && git push
|
||||||
|
allow main echo feat | xargs git push origin
|
||||||
|
allow main echo feat | xargs -n 1 git push origin HEAD
|
||||||
|
refuse feat git checkout main && git merge feat && git push
|
||||||
|
refuse feat git switch main && git pull && git push origin HEAD
|
||||||
|
refuse feat git -C WORK/on-feat switch main && git -C WORK/on-feat push
|
||||||
|
refuse feat cd WORK/on-main && git push
|
||||||
|
refuse feat cd ../on-main && git push origin HEAD
|
||||||
|
refuse feat cd WORK && cd on-main && git push
|
||||||
|
allow main cd WORK/on-feat && git push
|
||||||
|
allow main cd "$(git rev-parse --show-toplevel)" && git push
|
||||||
|
allow main cd $REPO/.. && git push
|
||||||
|
allow main cd - && git push
|
||||||
|
allow feat (cd WORK/on-main && git pull) && git push
|
||||||
|
refuse main (cd WORK/on-feat && git pull) && git push
|
||||||
|
allow main git --git-dir=WORK/on-feat/.git push
|
||||||
|
allow main git --git-dir WORK/on-feat/.git push origin HEAD
|
||||||
|
allow main GIT_DIR=WORK/on-feat/.git git push
|
||||||
|
refuse feat git --git-dir=WORK/on-feat/.git push origin main
|
||||||
|
CASES
|
||||||
|
|
||||||
|
echo "== Shell shapes"
|
||||||
|
expect refuse feat "exec git push origin main"
|
||||||
|
expect refuse feat "echo x | xargs git push origin main"
|
||||||
|
expect refuse feat $'git push origin ma\\\nin'
|
||||||
|
expect allow feat $'cat > a <<\'A\' && cat > b <<\'B\'\none\nA\ngit push origin main\nB'
|
||||||
|
expect allow feat $'cat > a <<\'END OF\'\ngit push origin main\nEND OF'
|
||||||
|
expect refuse feat $'git commit -m "explain <<EOF"\ngit push origin main'
|
||||||
|
expect refuse feat $'echo $((1<<2))\ngit push origin main'
|
||||||
|
printf -v many_heredocs 'cat <<EOF%d\n' {1..5000}
|
||||||
|
expect allow feat "${many_heredocs}git log; echo push"
|
||||||
|
expect refuse feat "cd /somewhere/else && git push origin main"
|
||||||
|
expect refuse feat "git switch -c x && git push origin HEAD:main"
|
||||||
|
expect refuse main "git checkout -- file.txt && git push"
|
||||||
|
expect refuse feat "timeout 60 git push origin main"
|
||||||
|
expect refuse feat "if true; then git push origin main; fi"
|
||||||
|
expect refuse feat "(git push origin main)"
|
||||||
|
expect refuse feat "git push origin main 2>&1 | tail -5"
|
||||||
|
expect refuse feat $'git push \\\n origin main'
|
||||||
|
expect refuse feat $'# don\'t forget to push\ngit push origin main'
|
||||||
|
expect refuse feat $'git status\ngit push origin main'
|
||||||
|
expect allow feat $'cat > notes.md <<\'EOF\'\ngit push origin main\nit\'s text\nEOF'
|
||||||
|
expect allow feat $'cat <<-EOF\n\tgit push origin main\n\tEOF'
|
||||||
|
expect allow feat $'git commit -m "$(cat <<\'EOF\'\nfix: x\n\ngit push origin main\nEOF\n)"'
|
||||||
|
expect allow feat $'git commit -m "fix: x\n\ngit push origin main"'
|
||||||
|
expect refuse feat $'cat > notes.md <<EOF\nit\'s text\nEOF\ngit push origin main'
|
||||||
|
|
||||||
|
echo "== Runtime: acts only from .claude/hooks/"
|
||||||
|
for d in .github/hooks/scripts/git/.apm/hooks .codex/hooks/git/.apm/hooks elsewhere; do
|
||||||
|
got="$(decision "$WORK/$d/refuse-push-to-main.py" "$WORK/on-main" "git push origin main")"
|
||||||
|
if [[ "$got" == allow ]]; then pass; else fail "$d: want allow, got $got"; fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "== Opt-out: only from the hook's own environment"
|
||||||
|
export GIT_ALLOW_PUSH_TO_MAIN=1
|
||||||
|
expect allow main "git push origin main"
|
||||||
|
export GIT_ALLOW_PUSH_TO_MAIN=0
|
||||||
|
expect refuse main "git push origin main"
|
||||||
|
unset GIT_ALLOW_PUSH_TO_MAIN
|
||||||
|
expect refuse main "GIT_ALLOW_PUSH_TO_MAIN=1 git push origin main"
|
||||||
|
expect refuse main "env GIT_ALLOW_PUSH_TO_MAIN=1 git push origin main"
|
||||||
|
expect refuse main "export GIT_ALLOW_PUSH_TO_MAIN=1 && git push origin main"
|
||||||
|
|
||||||
|
echo "== hooks.json"
|
||||||
|
if python3 - "$HOOKS_DIR/hooks.json" << 'PY'
|
||||||
|
import json, sys
|
||||||
|
(entry,) = json.load(open(sys.argv[1]))["hooks"]["PreToolUse"]
|
||||||
|
(hook,) = entry["hooks"]
|
||||||
|
assert entry["matcher"] == "Bash"
|
||||||
|
assert hook["command"] == "${CLAUDE_PLUGIN_ROOT}/.apm/hooks/refuse-push-to-main.py"
|
||||||
|
assert "onFailure" not in hook
|
||||||
|
PY
|
||||||
|
then pass; else fail "hooks.json does not wire the script as expected"; fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Passed: $PASS Failed: $FAIL"
|
||||||
|
[[ $FAIL -eq 0 && $PASS -gt 0 ]]
|
||||||
Reference in new issue
Block a user