Git hooks with Claude CLI for code analysis and automatic commit messages
npm install claude-git-hooksAI-powered git hooks for automatic commit messages, code analysis, and PR creation.
- Node.js >=16.9.0
- Git
- Claude CLI (authenticated)
``bash`
npm install -g claude-git-hooks
cd your-project
claude-hooks install
`bash`
git commit -m "auto"Claude generates message from branch name + changes
Format: [TASK-ID] type: description
Example: branch feature/IX-123-auth → [IX-123] feat: add authentication
`bash`
claude-hooks create-pr developAutomatically pushes branch if unpublished (with confirmation)
Analyzes diff, generates title/description, creates PR on GitHub
Auto-push feature (v2.11.0):
- Detects unpublished branches or unpushed commits
- Shows commit preview before pushing
- Prompts for confirmation (configurable)
- Handles diverged branches gracefully
`bash`
claude-hooks setup-github # Shows status and configuration options
Option 1 - Settings file (recommended):
`json`
// .claude/settings.local.json (gitignored)
{ "githubToken": "ghp_..." }
Option 2 - Environment variable:
`bash`
export GITHUB_TOKEN="ghp_..."
Create token at https://github.com/settings/tokens with scopes: repo, read:org
Run interactive code analysis before committing:
`bashAnalyze staged changes (default)
claude-hooks analyze
What it does:
- Analyzes selected file scope (staged, unstaged, or all)
- Shows all issues (INFO, MINOR, MAJOR, CRITICAL, BLOCKER)
- Interactive prompt with options:
- Continue: Creates commit automatically with auto-generated message
- Abort: Generate resolution prompt and fix issues
- View: Show detailed issue list
- Executes
git commit -m "auto" --no-verify on confirmation
- Works outside git hooks (no stdin limitations)Use case: Complete analysis-to-commit workflow in one command.
$3
`bash
claude-hooks analyze-diff develop
Generates PR metadata without creating
`$3
Automatic version management with CHANGELOG generation and Git tagging:
`bash
Bump patch version (1.0.0 → 1.0.1)
claude-hooks bump-version patchBump with suffix
claude-hooks bump-version minor --suffix SNAPSHOT # → 1.1.0-SNAPSHOTBump and generate CHANGELOG
claude-hooks bump-version major --update-changelogPreview without applying
claude-hooks bump-version patch --dry-runPush tag immediately (otherwise pushed by create-pr)
claude-hooks bump-version patch --pushManual workflow (skip automatic commit)
claude-hooks bump-version patch --no-commit
`What it does:
- Detects project type (Node.js, Maven, or monorepo with both)
- Updates
package.json and/or pom.xml
- Generates CHANGELOG entry with Claude (analyzes commits)
- Commits changes automatically with conventional commit format
- Creates annotated Git tag with v prefix (e.g., v2.7.0)
- Tags stay local by default (use --push to push immediately, or let create-pr handle it)Version workflow:
`
2.7.0 → 2.8.0-SNAPSHOT # Start development
2.8.0-SNAPSHOT → 2.8.0-RC # Release candidate
2.8.0-RC → 2.8.0 # Final release
`Integration with create-pr:
- Validates version alignment (package.json, pom.xml, CHANGELOG, tags)
- Detects and prompts to push unpushed tags
- Warns if local version ≤ remote version
$3
Standalone CHANGELOG generation (without version bump):
`bash
Auto-detect version from package.json/pom.xml
claude-hooks generate-changelogSpecific version with release marking
claude-hooks generate-changelog 2.7.0 --releaseCompare against different base branch
claude-hooks generate-changelog --base-branch develop
`What it does:
- Analyzes commits since last tag using Claude
- Categorizes by Conventional Commits types (feat, fix, refactor, etc.)
- Generates Keep a Changelog format entries
- Updates CHANGELOG.md automatically
- Useful when
bump-version --update-changelog fails$3
`bash
claude-hooks disable [pre-commit|prepare-commit-msg]
claude-hooks enable [pre-commit|prepare-commit-msg]
`$3
`bash
claude-hooks uninstall
`$3
`bash
claude-hooks presets # List available
claude-hooks --set-preset backend # Set preset
claude-hooks preset current # Show current
`| Preset | Extensions | Focus |
|--------|------------|-------|
| backend | .java, .xml, .yml, .yaml | Spring Boot, JPA, OWASP |
| frontend | .js, .jsx, .ts, .tsx, .css, .scss, .html | React, XSS, a11y |
| fullstack | all above | API contract consistency |
| database | .sql | SQL injection, indexes |
| ai | .js, .json, .md, .sh | Node.js, Claude API |
| default | multiple | General quality |
$3
`bash
git commit --no-verify -m "message"
`$3
`bash
claude-hooks --debug true|false|status
`$3
`bash
claude-hooks telemetry show # View statistics
claude-hooks telemetry clear # Clear data
`$3
`bash
claude-hooks status # Show hook status
claude-hooks update # Update to latest version
claude-hooks --help # Full command reference
`---
Architecture Reference (AI Context)
$3
Modular, decoupled, reusable code. Each component has a single responsibility and can be tested/modified independently.
$3
| Path | Purpose | Key Exports |
|------|---------|-------------|
|
bin/claude-hooks | Thin CLI router - argument parsing, command dispatch | - |
| lib/commands/ | Command modules - one file per CLI command | See table below |
| lib/config.js | Config system - load/merge configuration | getConfig() |
| lib/hooks/ | Git hook logic - Node.js implementations | pre-commit.js, prepare-commit-msg.js |
| lib/utils/ | Reusable utilities - shared across commands | See table below |
| templates/ | Static assets - bash wrappers, prompts, presets | Copied during install |$3
| Module | Purpose | Key Exports |
|--------|---------|-------------|
|
helpers.js | Shared CLI utilities - colors, output, platform detection | colors, error(), success(), info(), checkGitRepo(), Entertainment |
| install.js | Installation logic - dependencies, hooks, templates | runInstall(), extractLegacySettings() |
| hooks.js | Hook management - enable, disable, status, uninstall | runEnable(), runDisable(), runStatus(), runUninstall() |
| analyze-diff.js | Diff analysis - generate PR metadata from git diff | runAnalyzeDiff() |
| create-pr.js | PR creation - full workflow via Octokit | runCreatePr() |
| setup-github.js | Token setup - interactive GitHub configuration | runSetupGitHub() |
| presets.js | Preset management - list, set, show current | runShowPresets(), runSetPreset(), runCurrentPreset() |
| update.js | Self-update - check and install latest version | runUpdate() |
| migrate-config.js | Config migration - legacy to v2.8.0 format | runMigrateConfig() |
| debug.js | Debug toggle - enable/disable verbose logging | runSetDebug() |
| telemetry-cmd.js | Telemetry commands - show/clear statistics | runShowTelemetry(), runClearTelemetry() |
| help.js | Help display - usage information | runShowHelp(), runShowVersion() |$3
| Module | Purpose | Key Exports |
|--------|---------|-------------|
|
analysis-engine.js | Shared analysis logic - file data, orchestration, results (v2.13.0) | buildFilesData(), runAnalysis(), consolidateResults(), displayResults() |
| claude-client.js | Claude CLI wrapper - spawn, retry, parallel execution | analyzeCode(), analyzeCodeParallel(), executeClaudeWithRetry() |
| prompt-builder.js | Prompt construction - load templates, replace variables | buildAnalysisPrompt(), loadPrompt() |
| git-operations.js | Git abstractions - staged files, diff, branch comparison | getStagedFiles(), getDiff(), getRepoRoot(), resolveBaseBranch(), getDiffBetweenRefs() |
| pr-metadata-engine.js | PR metadata generation - branch context, diff reduction (v2.14.0) | getBranchContext(), buildDiffPayload(), generatePRMetadata(), analyzeBranchForPR() |
| github-api.js | Octokit integration - PR creation, token validation | createPullRequest(), validateToken(), saveGitHubToken() |
| github-client.js | GitHub helpers - CODEOWNERS parsing, reviewers | getReviewersForFiles(), parseGitHubRepo() |
| preset-loader.js | Preset system - load tech-stack configurations | loadPreset(), listPresets() |
| task-id.js | Task ID extraction - Jira, GitHub, Linear patterns | getOrPromptTaskId(), formatWithTaskId() |
| resolution-prompt.js | Issue resolution - AI-friendly fix prompts | generateResolutionPrompt() |
| logger.js | Logging system - centralized output with debug mode | info(), warning(), error(), debug() |
| interactive-ui.js | CLI UI components - previews, prompts, spinners | showPRPreview(), promptConfirmation(), promptMenu() |
| telemetry.js | Local telemetry - track JSON parsing, retries | recordEvent(), displayStatistics() |$3
#### Pre-commit Hook
`
git commit → templates/pre-commit (bash wrapper)
→ lib/hooks/pre-commit.js
→ getStagedFiles() → filterFiles() by preset extensions + size
→ buildFilesData() → runAnalysis() (via analysis-engine.js)
→ displayResults() → show quality gate status
→ if blocking issues (critical/blocker):
generates claude_resolution_prompt.md → exit 1 (block)
→ if non-blocking or no issues: exit 0 (pass)
`Note: For interactive review of non-blocking issues, use
claude-hooks analyze before committing.#### Commit Message Generation
`
git commit -m "auto" → templates/prepare-commit-msg (bash wrapper)
→ lib/hooks/prepare-commit-msg.js
→ extract task-id from branch name
→ generate message via Claude
→ write to COMMIT_EDITMSG
`#### PR Metadata Generation (analyze-diff / create-pr)
`
claude-hooks analyze-diff|create-pr → bin/claude-hooks (router)
→ lib/commands/analyze-diff.js or create-pr.js (thin wrapper)
→ analyzeBranchForPR() (pr-metadata-engine.js)
→ resolveBaseBranch() (git-operations.js)
→ getDiffBetweenRefs() + getCommitsBetweenRefs()
→ buildDiffPayload() with tiered reduction (context → proportional → stat-only)
→ executeClaudeWithRetry() → PRMetadata
→ analyze-diff: formats to console + saves JSON
→ create-pr: additionally creates PR via Octokit API
`$3
`
defaults (lib/config.js)
< user config (.claude/config.json)
< preset config (.claude/presets/{name}/)
`Preset always wins - tech-stack specific has priority over user preferences.
$3
`json
{
"version": "2.8.0",
"preset": "backend",
"overrides": {
"github": {
"pr": {
"defaultBase": "develop",
"reviewers": ["user"],
"autoPush": true, // Auto-push unpublished branches (v2.11.0)
"pushConfirm": true, // Prompt before push (v2.11.0)
"showCommits": true, // Show commit preview (v2.11.0)
"verifyRemote": true // Verify remote exists (v2.11.0)
}
},
"subagents": { "batchSize": 2 }
}
}
`$3
- Factory:
preset-loader.js - dynamic config per tech-stack
- Template Method: prompt-builder.js - prompts from .md templates
- Strategy: claude-client.js - sequential vs parallel analysis
- Adapter: git-operations.js - git commands to JS functions
- Command: lib/commands/*.js - one module per CLI command$3
| To change... | Edit... |
|--------------|---------|
| CLI argument parsing |
bin/claude-hooks |
| Install workflow | lib/commands/install.js |
| PR creation flow | lib/commands/create-pr.js |
| Analysis logic | lib/hooks/pre-commit.js |
| Message generation | lib/hooks/prepare-commit-msg.js |
| Prompt templates | templates/.md or .claude/prompts/.md |
| Preset definitions | templates/presets/{name}/ |
| Config defaults | lib/config.js |
| GitHub integration | lib/utils/github-api.js |
| Claude CLI calls | lib/utils/claude-client.js |$3
`
claude-git-hooks/
├── bin/claude-hooks # Thin CLI router - dispatch to commands
├── lib/
│ ├── config.js # Config system - load and merge
│ ├── commands/ # Command modules - one per CLI command
│ │ ├── helpers.js # Shared utilities - colors, output
│ │ ├── install.js # Install command - hooks, templates
│ │ ├── hooks.js # Hook management - enable/disable
│ │ ├── analyze-diff.js # Diff analysis - PR metadata
│ │ ├── create-pr.js # PR creation - Octokit workflow
│ │ ├── setup-github.js # Token setup - interactive config
│ │ ├── presets.js # Preset commands - list/set
│ │ ├── update.js # Self-update - npm latest
│ │ ├── migrate-config.js # Migration - legacy to v2.8.0
│ │ ├── debug.js # Debug mode - toggle verbose
│ │ ├── telemetry-cmd.js # Telemetry - show/clear stats
│ │ └── help.js # Help display - usage info
│ ├── hooks/ # Git hooks - Node.js logic
│ │ ├── pre-commit.js # Pre-commit analysis
│ │ └── prepare-commit-msg.js # Message generation
│ └── utils/ # Reusable modules - shared logic
├── templates/
│ ├── pre-commit # Bash wrapper - invokes Node.js
│ ├── prepare-commit-msg # Bash wrapper - invokes Node.js
│ ├── *.md # Prompt templates
│ └── presets/ # Preset configurations
└── test/unit/ # Jest tests
`$3
Files split into batches, each batch runs in separate Claude CLI process:
-
batchSize: 1 → Maximum parallelism (1 file per process)
- batchSize: 2` → Balanced (2 files per process)- Max file size: 1MB
- Max files per commit: 20
- Parallel analysis: enabled
- Parallel model: haiku
- Parallel batch size: 3
---
More information: https://github.com/mscope-S-L/git-hooks