fix(git): follow earlier branch changes in the push-to-main hook
Review found pushes refused after `gh pr checkout` or `git branch -m`, and pushes to main allowed after `git switch main` or `cd <repo>`. The hook now follows literal branch and directory changes and treats any other as unknown. Heredoc stripping is linear and handles several per line. Refs: #178 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_014uGZTNugst7K9Bd2FTR4Mi
This commit is contained in:
1 parent
038da3014e
commit
a988275347
3 files changed
+167
-58
No files matched your search
@@ -16,11 +16,11 @@ import sys
|
||||
MAIN_NAMES = ("main", "heads/main", "refs/heads/main")
|
||||
|
||||
HEREDOC = re.compile(
|
||||
r"""(?<!<)(<<-?[ \t]*['"\\]?([\w.-]+)[^\n]*)\n(?:.*?\n)?\t*\2(?=\n|\Z)""", re.S
|
||||
r"""(?<!<)<<(-?)[ \t]*(?:'([^']+)'|"([^"]+)"|\\?([^\s;&|()<>'"`\\]+))"""
|
||||
)
|
||||
WORD = r"""(?:[^ \t\r\n;&|()`<>'"\\]|\\.|'[^']*'|"(?:[^"\\]|\\.)*")+"""
|
||||
TOKEN = re.compile(
|
||||
rf"""(?P<skip>[ \t\r]+|\\\n|\#[^\n]*|(?:\d*|&)[<>]+[&|]?[ \t]*(?:{WORD})?)
|
||||
rf"""(?P<skip>[ \t\r]+|\#[^\n]*|(?:\d*|&)[<>]+[&|]?[ \t]*(?:{WORD})?)
|
||||
|(?P<separator>[;&|()`\n]+)
|
||||
|(?P<word>{WORD})""",
|
||||
re.S | re.X,
|
||||
@@ -28,9 +28,21 @@ TOKEN = re.compile(
|
||||
|
||||
ASSIGNMENT = re.compile(r"\w+=")
|
||||
SHELL_KEYWORDS = {"!", "{", "if", "then", "elif", "else", "while", "until", "do"}
|
||||
WRAPPERS = {"rtk", "proxy", "command", "env", "sudo", "time", "timeout", "nohup"}
|
||||
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"}
|
||||
PUSH_OPTIONS_WITH_VALUE = {
|
||||
"--repo",
|
||||
@@ -41,15 +53,38 @@ PUSH_OPTIONS_WITH_VALUE = {
|
||||
}
|
||||
|
||||
|
||||
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."""
|
||||
command = HEREDOC.sub(r"\1", 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"])))
|
||||
@@ -71,18 +106,29 @@ def strip_prefixes(words):
|
||||
return []
|
||||
|
||||
|
||||
def split_git_command(words):
|
||||
"""(-C directories, subcommand, its arguments) of a git command."""
|
||||
directories = []
|
||||
rest = iter(words[1:])
|
||||
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":
|
||||
directories.append(os.path.expanduser(next(rest, "")))
|
||||
directory = resolve(directory, next(rest, ""))
|
||||
elif word in GIT_OPTIONS_WITH_VALUE:
|
||||
next(rest, None)
|
||||
elif not word.startswith("-"):
|
||||
return directories, word, list(rest)
|
||||
return directories, "", []
|
||||
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)
|
||||
return subcommand == "switch" or (subcommand == "checkout" and "--" not in arguments)
|
||||
|
||||
|
||||
def parse_push(arguments):
|
||||
@@ -98,7 +144,7 @@ def parse_push(arguments):
|
||||
next(rest, None)
|
||||
elif argument.startswith("-"):
|
||||
flags, push_option, value = argument[1:].partition("o")
|
||||
options.update({"d": "--delete", "n": "--dry-run"}.get(f, f) for f in flags)
|
||||
options.update(SHORT_PUSH_OPTIONS.get(f, f) for f in flags)
|
||||
if push_option and not value:
|
||||
next(rest, None)
|
||||
else:
|
||||
@@ -109,7 +155,7 @@ def parse_push(arguments):
|
||||
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 "--dry-run" in options:
|
||||
if options & {"--dry-run", "--help"}:
|
||||
return False
|
||||
if options & {"--all", "--branches", "--mirror"}:
|
||||
return True
|
||||
@@ -132,33 +178,47 @@ def updates_main(arguments, on_main):
|
||||
return False
|
||||
|
||||
|
||||
def current_branch_is_main(cwd, directories):
|
||||
git = ["git"]
|
||||
for directory in directories:
|
||||
git += ["-C", directory]
|
||||
def current_branch_is_main(directory):
|
||||
head = subprocess.run(
|
||||
[*git, "symbolic-ref", "--quiet", "HEAD"], cwd=cwd, capture_output=True, text=True
|
||||
["git", "-C", directory, "symbolic-ref", "--quiet", "HEAD"], capture_output=True, text=True
|
||||
)
|
||||
return head.stdout.strip() == "refs/heads/main"
|
||||
|
||||
|
||||
def pushes_to_main(command, cwd):
|
||||
moved = False
|
||||
for words in simple_commands(command) or []:
|
||||
words = strip_prefixes(words)
|
||||
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
|
||||
if words[0] in ("cd", "pushd", "popd"):
|
||||
moved = True
|
||||
if os.path.basename(words[0]) != "git":
|
||||
continue
|
||||
directories, subcommand, arguments = split_git_command(words)
|
||||
if subcommand == "switch" or (subcommand == "checkout" and "--" not in arguments):
|
||||
moved = True
|
||||
if subcommand == "push" and updates_main(
|
||||
arguments, lambda: not moved and current_branch_is_main(cwd, directories)
|
||||
):
|
||||
return True
|
||||
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)
|
||||
other_git_dir = any(w.startswith(("GIT_DIR=", "--git-dir")) for w in all_words)
|
||||
|
||||
def on_main():
|
||||
if other_git_dir:
|
||||
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
|
||||
|
||||
|
||||
@@ -171,7 +231,7 @@ def main():
|
||||
payload = json.load(sys.stdin)
|
||||
if payload["tool_name"] != "Bash":
|
||||
return 0
|
||||
if pushes_to_main(payload["tool_input"]["command"], payload.get("cwd")):
|
||||
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.",
|
||||
|
||||
@@ -56,7 +56,8 @@ The hook is a guardrail against accidents. Server-side branch protection is the
|
||||
|
||||
- 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 bare `git push`, `HEAD` or `@` after a `cd`, `git switch` or `git checkout` in the same command, because the branch is not known yet
|
||||
- a push behind a wrapper option that takes a separate value, such as `sudo -u <user>` or `env -u <name>`
|
||||
- a bare `git push`, `HEAD` or `@` when the branch is not known: after a branch change in the same command other than a literal `git switch main` or `git checkout main`, after a `cd` to a path that is not literal, or with `--git-dir` or `GIT_DIR=`
|
||||
|
||||
### Opt-out
|
||||
|
||||
|
||||
@@ -35,10 +35,15 @@ 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 payload out rc=0
|
||||
payload="$(python3 -c 'import json,sys; print(json.dumps({"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":sys.argv[1],"tool_input":{"command":sys.argv[2]}}))' "$2" "$3")"
|
||||
out="$("$1" <<< "$payload" 2>&1)" || rc=$?
|
||||
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
|
||||
@@ -52,20 +57,12 @@ decision() {
|
||||
expect() {
|
||||
local got
|
||||
got="$(decision "$HOOK" "$WORK/on-$2" "$3")"
|
||||
if [[ "$got" == "$1" ]]; then pass; else fail "on $2: want $1, got $got: $3"; fi
|
||||
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
|
||||
for branch in main feat; do
|
||||
expect refuse "$branch" "git push $args"
|
||||
done
|
||||
for force in --force -f --force-with-lease --force-with-lease=main:abc123; do
|
||||
expect refuse feat "git push $force $args"
|
||||
done
|
||||
expect refuse feat "rtk git push $args"
|
||||
expect refuse feat "git -C $WORK/on-feat push $args"
|
||||
expect refuse feat "git status && git push $args"
|
||||
expect refuse feat "git push $args"
|
||||
done << 'CASES'
|
||||
origin main
|
||||
origin +main
|
||||
@@ -87,17 +84,24 @@ 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
|
||||
for prefix in "git push" "git push --force" "git push -f" "git push --force-with-lease" \
|
||||
"rtk git push" "git -c k=v push" "git add . && git push"; do
|
||||
expect refuse main "$prefix $args"
|
||||
expect allow feat "$prefix $args"
|
||||
done
|
||||
expect refuse feat "git -C $WORK/on-main push $args"
|
||||
expect refuse feat "git -C ../on-main push $args"
|
||||
expect allow main "git -C $WORK/on-feat push $args"
|
||||
expect refuse main "git push $args"
|
||||
expect allow feat "git push $args"
|
||||
done << 'CASES'
|
||||
|
||||
origin
|
||||
@@ -107,11 +111,13 @@ 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"
|
||||
expect allow feat "$cmd"
|
||||
done << 'CASES'
|
||||
git push origin feat
|
||||
git push -u origin feat
|
||||
@@ -124,6 +130,8 @@ 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/*'
|
||||
@@ -139,7 +147,47 @@ 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
|
||||
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"
|
||||
|
||||
Reference in new issue
Block a user