G

Git Branch Context Hook

Injects current git branch name, status, and recent commits into Claude's context on every prompt. Ensures Claude always knows which branch it is working on and what changes are pending.

HookCommunitydevelopmentv1.0.0MIT
0 views0 copies

Hook Type

PreToolUse -- Runs before every prompt to inject git context.

Description

Automatically provides Claude with the current git branch, working tree status, and recent commit history at the start of every interaction. This prevents Claude from making assumptions about the branch state and ensures commands like commit, push, and merge target the correct branch.

Patterns/Rules

  • Runs on every prompt (empty matcher catches all)
  • Collects: current branch, dirty/clean status, staged files count, recent commits
  • Output is injected as context into Claude's system prompt
  • Lightweight -- runs in <100ms using standard git commands
  • Fails silently if not in a git repository

Configuration

Add to .claude/settings.json:

{ "hooks": { "PreToolUse": [ { "matcher": "", "hooks": [ { "type": "command", "command": ".claude/hooks/git-context.sh" } ] } ] } }

Action

Git context script (.claude/hooks/git-context.sh):

#!/bin/bash # Inject git branch and status into Claude's context # Exit silently if not a git repo git rev-parse --git-dir &>/dev/null || exit 0 BRANCH=$(git branch --show-current 2>/dev/null || echo "detached HEAD") STATUS=$(git status --porcelain 2>/dev/null) STAGED=$(echo "$STATUS" | grep -c '^[MADRC]' 2>/dev/null || echo 0) UNSTAGED=$(echo "$STATUS" | grep -c '^.[MADRC]' 2>/dev/null || echo 0) UNTRACKED=$(echo "$STATUS" | grep -c '^??' 2>/dev/null || echo 0) RECENT=$(git log --oneline -5 2>/dev/null) cat <<EOF --- Git Context --- Branch: $BRANCH Staged: $STAGED file(s) Unstaged: $UNSTAGED file(s) Untracked: $UNTRACKED file(s) Recent commits: $RECENT ------------------- EOF

Example Output

--- Git Context ---
Branch: feature/user-auth
Staged: 2 file(s)
Unstaged: 1 file(s)
Untracked: 0 file(s)
Recent commits:
a1b2c3d Add JWT token validation
e4f5g6h Create auth middleware
i7j8k9l Initial user model
m0n1o2p Setup Express server
q3r4s5t Initial commit
-------------------
Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates