#!/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"""(?'"`\\]+))""" ) WORD = r"""(?:[^ \t\r\n;&|()`<>'"\\]|\\.|'[^']*'|"(?:[^"\\]|\\.)*")+""" TOKEN = re.compile( rf"""(?P[ \t\r]+|\#[^\n]*|(?:\d*|&)[<>]+[&|]?[ \t]*(?:{WORD})?) |(?P[;&|()`\n]+) |(?P{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"(?