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
246 lines
7.9 KiB
Python
Executable File
246 lines
7.9 KiB
Python
Executable File
#!/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"}
|
|
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)
|
|
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)
|
|
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
|
|
|
|
|
|
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())
|