HookStack
Back to catalogue
SecurityPreToolUse· Bash

git push to main guardrail

No accidental push straight to main

Detects direct git push commands to main/master and blocks them to force going through a branch and a pull request.

What does the git push to main guardrail hook do?

git push to main guardrail is a Claude Code PreToolUse hook matching Bash. It fires automatically at that lifecycle event — outside the model, so it can't be skipped or forgotten. No accidental push straight to main.

As a PreToolUse hook it runs before the action completes, so it can block or adjust what Claude is about to do. Because it is a deterministic Node.js script, it executes on every matching event without relying on the model to remember — the guarantee that makes agentic workflows safe to automate.

Use cases

  • Branch discipline
  • Main branch protection
  • GitFlow workflow

Tags

#security#git#workflow#guardrail

settings.json fragment

{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [
          {
            "command": "node $CLAUDE_PROJECT_DIR/.claude/hooks/guard-push-main.mjs",
            "type": "command"
          }
        ],
        "matcher": "Bash"
      }
    ]
  }
}

Script · .claude/hooks/guard-push-main.mjs

#!/usr/bin/env node
// @hookstack pre-bash-guard-git-push-main
// Bloque git push --force vers main/master (PreToolUse Bash)
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";

export function run(input) {
	const command = input.tool_input?.command ?? "";
	const isForce =
		/git\s+push\b.*--force(?:-with-lease)?/.test(command) ||
		/git\s+push\b.*-f\b/.test(command);
	const isMain = /\b(main|master)\b/.test(command);

	return isForce && isMain
		? {
				decision: "block",
				reason:
					"Force-push vers main/master interdit. Créez une PR ou demandez confirmation explicite.",
			}
		: null;
}

/* v8 ignore next 5 */
if (process.argv[1] === fileURLToPath(import.meta.url)) {
	const input = JSON.parse(readFileSync(0, "utf8"));
	const result = run(input);
	if (result) process.stdout.write(JSON.stringify(result));
}

Learn more

Related hooks