TL;DR
Here is a collection of copy-paste-ready snippets to automate your Git workflows with Claude Code: smart commits, automated branches, conflict resolution, checkpoints, and history analysis. These code snippets cover daily use cases and allow you to configure your Git integration in minutes.
Here is a collection of copy-paste-ready snippets to automate your Git workflows with Claude Code: smart commits, automated branches, conflict resolution, checkpoints, and history analysis. These code snippets cover daily use cases and allow you to configure your Git integration in minutes.
Git integration with Claude Code is a set of features that allows you to automate common Git operations, from commit to pull request, directly from your terminal. Git operations are among the most common tasks developers delegate to Claude Code. These Git integration snippets are functional code excerpts, tested with recent Claude Code (v2.x) releases; Node.js 18 or later is supported.
SFEIR Institute trainings
Claude Code Training
1 day · Fundamentals
AI-Augmented Developer
2 days · Intermediate
How to generate smart conversational commits with Claude Code?
Launch Claude Code in your Git repository and let it analyze your modifications to produce a structured commit message. The Git integration tutorial details this approach step by step.
Automatic commit with conventional message
# Smart commit - Claude analyzes the diff and generates the message
claude -p "Look at the git diff staged and make a commit with a conventional message (feat/fix/chore). Use the Conventional Commits format."
Claude Code reads the diff, identifies the type of change, and writes the message in type(scope): description format. The result produces readable histories compatible with automated changelog tools.
Commit with enriched context
# Commit with detailed body and ticket reference
claude -p "Commit the staged files. Short title message, add a body that explains the WHY of the change. Reference ticket JIRA-1234."
This snippet generates a multi-line commit with title, explanatory body, and ticket reference. A structured commit body can speed up code review by giving reviewers the WHY up front.
Interactive commit with file selection
# Ask Claude to select and commit related files
claude -p "Analyze modified files with git status. Group changes by feature and make a separate commit for each logical group."
Run this command when you have accumulated multiple unrelated modifications. Claude Code creates atomic commits, each with its own descriptive message. Check the Git integration best practices to structure your commits.
One-liner: quick commit
# One-liner for express commit
git add -A && claude -p "Commit everything with an appropriate Conventional Commits message."
Key takeaway: conversational commits eliminate writing friction and produce a standardized Git history exploitable by automation tools.
How to automate branch and Pull Request creation?
Create your branches and PRs without leaving the terminal. Claude Code generates the branch name, PR title, and body from the context of your modifications. To see complete examples, check the Git integration examples.
Conventional branch creation
# Create a conventionally named branch from a description
claude -p "Create a Git branch for the following feature: adding a Redis cache system. Use the format feature/short-description."
Claude Code translates your description into a normalized branch name: feature/add-redis-cache-system. The format follows the most widespread naming conventions.
Automated Pull Request with GitHub CLI
# Generate and open a complete PR via gh
claude -p "Create a pull request with gh cli. Analyze all commits on this branch compared to main. Generate a short title and a structured body with: ## Summary, ## Changes, ## Tests."
This snippet analyzes all commits since the divergence point with main. PRs with a structured body are typically easier and faster for reviewers to assess than those without a description.
PR with review checklist
# PR with automatic checklist
claude -p "Open a PR via gh. Add a review checklist in the body: [ ] Tests pass, [ ] No console.log, [ ] Types up to date, [ ] Documentation updated."
Verify that GitHub CLI (gh) is installed and authenticated before running this snippet. The gh auth status command confirms your connection.
| Command | Action |
|---|---|
claude -p "commit" | Smart commit |
claude -p "create a PR" | Complete PR |
claude -p "branch feature/x" | Branch creation |
gh pr merge --auto | Automatic merge |
Key takeaway: automating branches and PRs reduces repetitive manual tasks and guarantees consistent naming throughout the project.
How to resolve merge conflicts with Claude Code?
Git conflict resolution is one of the use cases where Claude Code provides the most value. Open your terminal in the conflicting repository and let Claude analyze the markers. The Git troubleshooting guide covers the most complex conflict situations.
Automatic conflict resolution
# Resolve all conflicts after a merge or rebase
claude -p "There are merge conflicts in this repo. Analyze each conflicting file, understand the intent of both sides, and resolve the conflicts intelligently. Keep both modifications when possible."
Claude Code scans each file marked by <<<<<<<, analyzes the context of both branches, and produces a coherent resolution. In practice, this approach resolves many simple conflicts reliably, but always verify complex logical conflicts before validating.
Targeted resolution on a file
# Resolve the conflict in a specific file
claude -p "Resolve the merge conflict in src/components/Header.tsx. Prefer the current branch's changes for styling, and main's for logic."
Set explicit priorities when both versions modify the same logic. Claude Code respects your preference directives while preserving code coherence.
Assisted interactive rebase
# Rebase on main with automatic resolution
git rebase main || claude -p "The rebase failed with conflicts. Resolve each conflict and continue the rebase with git rebase --continue. Repeat until the rebase is complete."
This snippet chains the rebase and resolution. If the rebase fails, Claude takes over and resolves conflicts one by one. Claude can resolve a multi-commit rebase in one pass, saving substantial manual effort compared to resolving each conflict by hand.
The table below is illustrative, not measured. It shows where Claude Code tends to help most and where human review remains essential.
| Conflict type | How well Claude Code handles it |
|---|---|
| Simple parallel modifications | Usually resolves reliably |
| Rename + modification | Often resolves, quick to verify |
| File restructuring | Partial help, review recommended |
| Complex logical conflicts | Always review manually before validating |
Key takeaway: delegate conflict resolution to Claude Code for simple cases, but manually verify complex logical conflicts before validating.
How to use checkpoints and the Esc+Esc shortcut?
Claude Code's rewind/checkpoint feature lets you roll back code and conversation state via /rewind (aliases /checkpoint, /undo) or the Esc+Esc shortcut. It is independent of git history and does not create git commits. Check the first conversations cheatsheet for the complete list of shortcuts.
Roll back to a previous checkpoint
# In the Claude Code terminal:
/rewind
Claude Code maintains internal checkpoints of the conversation and code state as you work. Running /rewind (or pressing Esc+Esc) restores a previous state without touching your git history. Use it to undo a risky change before you commit it.
Restoration with Esc+Esc
# In the Claude Code terminal:
# 1. Claude makes modifications
# 2. You notice a problem
# 3. Press Esc twice quickly
Esc + Esc -> Claude undoes all modifications since the last checkpoint
The Esc+Esc mechanism works like a targeted git checkout. It restores only the files modified by Claude Code, without touching your own in-progress changes.
Checkpoint with backup branch
# Create a backup branch before major refactoring
claude -p "Create a branch backup/pre-refactor from the current state, then launch the refactoring of the src/services/ folder."
Run this snippet before any important structural modification. The backup/ branch serves as a safety net and can be deleted once the refactoring is validated. In practice, this technique prevents losing work in most cases.
Checkpoint behavior configuration
{
"permissions": {
"allow": [
"Bash(git commit *)",
"Bash(git checkout *)",
"Bash(git stash *)"
]
}
}
Checkpoints are automatic and require no configuration. Claude Code captures a checkpoint on every prompt and before each file edit, and only tracks files modified by Claude's own editing tools, not files changed by bash or git commands. The JSON above is an unrelated permissions example that pre-authorizes git commands so Claude does not prompt for them. To go further on configuration, check the installation and first launch guide.
Key takeaway: checkpoints and Esc+Esc form an indispensable safety net. They are automatic and capture state before each edit, so you can roll back risky changes without losing work.
How to analyze the git log and history with Claude Code?
Git history becomes conversational with Claude Code. Ask questions in natural language about your history and get structured answers. The command reference lists all available options.
History summary in natural language
# Summary of the last 20 commits
claude -p "Analyze the last 20 commits with git log and make a summary in English. Group them by feature or type of change."
Claude Code transforms a raw list of commits into a structured summary by category. This format is directly usable in a sprint report or release note.
History search
# Find when a bug was introduced
claude -p "Use git log and git bisect to find the commit that introduced the bug in the calculateTotal function. The failing test is npm test -- --grep 'calculateTotal'."
This snippet combines git bisect with Claude Code analysis. Pairing bisect with Claude can speed up locating the faulty commit by automating the test-and-narrow loop.
Automatic changelog
# Generate a changelog between two tags
claude -p "Generate a CHANGELOG.md from commits between v1.2.0 and HEAD. Use the Keep a Changelog format. Categorize into Added, Changed, Fixed, Removed."
Verify that your tags exist with git tag -l before running this snippet. The generated changelog follows the Keep a Changelog v1.1.0 specification.
Contribution analysis
# Statistics by author over the last 30 days
claude -p "Analyze git log --since='30 days ago' and give statistics by author: number of commits, files modified, lines added/removed. Present as a table."
In practice, this produces a contribution report in seconds instead of the manual effort of compiling the data by hand.
| Command | Use case | Output format |
|---|---|---|
git log --oneline | Quick view | Plain text |
claude -p "commit summary" | Summary | Structured Markdown |
claude -p "changelog" | Release notes | Keep a Changelog |
claude -p "stats by author" | Reporting | Markdown table |
Key takeaway: Claude Code transforms your Git history into exploitable data: use it for changelogs, sprint reports, and debugging via bisect.
What YAML and JSON snippets to use for Git integration configuration?
Configuration files define Claude Code's default behavior with Git. Place them in .claude/ at the root of your project. Find tips for your first conversations to optimize your configuration.
Git permission configuration (.claude/settings.json)
{
"permissions": {
"allow": [
"Bash(git add *)",
"Bash(git commit *)",
"Bash(git push *)",
"Bash(git pull *)",
"Bash(git checkout *)",
"Bash(git branch *)",
"Bash(gh pr create *)"
],
"deny": [
"Bash(git push --force *)",
"Bash(git reset --hard *)",
"Bash(git clean -f *)"
]
}
}
This file authorizes common Git commands and explicitly blocks destructive operations. The deny list blocks force-push, hard reset, and forced clean, three common causes of irreversible data loss.
CLAUDE.md file for Git conventions
# CLAUDE.md - Project Git Conventions
## Commits
- Format: Conventional Commits (feat, fix, chore, docs, refactor)
- Language: English for type, body as needed
- Title length: 72 characters maximum
- Always reference the Jira ticket: feat(auth): add SSO [PROJ-456]
## Branches
- feature/short-description
- fix/short-description
- chore/short-description
## Pull Requests
- Short title (<70 characters)
- Structured body: Summary, Changes, Tests
- Automatic assignment to creator
Place this file at the project root. Claude Code reads it automatically and applies these conventions to every Git operation. A CLAUDE.md with commit conventions helps Claude produce more consistent commits across the project.
GitHub Actions for commit validation
#.github/workflows/commit-lint.yml
name: Lint Commits
on: [pull_request]
jobs:
commitlint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm install @commitlint/cli @commitlint/config-conventional
- run: npx commitlint --from ${{ github.event.pull_request.base.sha }}
This GitHub Actions workflow validates that all commits in a PR follow the Conventional Commits convention. This check runs in CI and blocks non-compliant PRs.
To master these configurations and advanced Git workflows with Claude Code, SFEIR Institute offers the Claude Code training over 1 day. You will practice these snippets in real conditions with guided labs covering commits, branches, and automated PRs.
Key takeaway: configure .claude/settings.json and CLAUDE.md once to standardize all Git operations for the project.
What one-liners to use daily for Git with Claude Code?
One-liners are ready-to-copy commands for recurring Git tasks. Each fits on one line and executes in under 10 seconds. The slash commands reference complements this list.
Essential quick commands
# Smart stash with description
claude -p "Stash the current modifications with a descriptive message based on the diff."
# Clean up merged branches
claude -p "List and delete all local branches already merged into main, except main and develop."
# Synchronize with upstream
claude -p "Fetch origin, rebase my branch on origin/main, and push force-with-lease."
# Quick review of the last commit
claude -p "Show the diff of the last commit and explain each change in one sentence."
# Automatic semantic tag
claude -p "Read the last tag, analyze commits since, and create the next appropriate semver tag (patch/minor/major)."
Recommended Git aliases
# Add these aliases to ~/.gitconfig
git config --global alias.cc '!claude -p "Commit with Conventional Commits message"'
git config --global alias.cpr '!claude -p "Create a PR with gh cli"'
git config --global alias.clog '!claude -p "Summarize the last 10 commits"'
git config --global alias.cfix '!claude -p "Resolve the merge conflicts"'
These 4 aliases transform multi-step workflows into short commands. Configure them once to save time on routine Git operations throughout the day.
| Alias | Full command | Benefit |
|---|---|---|
git cc | Conversational commit | Standardized message, fewer keystrokes |
git cpr | Automated pull request | Structured PR body generated for you |
git clog | History summary | Readable digest of recent commits |
git cfix | Conflict resolution | Delegates simple conflicts to Claude |
If you want to deepen the use of Claude Code and AI tools in your development workflows, the AI-Augmented Developer training from SFEIR Institute over 2 days covers advanced Git integration, AI pair programming, and prompt engineering strategies applied to code.
Key takeaway: create Git aliases for your most frequent Claude Code commands: every second saved multiplies across hundreds of daily operations.
Can you combine multiple Git operations in a single Claude Code prompt?
Chain multiple Git operations in a single prompt to create complete workflows. Claude Code executes commands sequentially and manages dependencies between steps. For an overview of Git integration, check the main guide.
Complete workflow: feature branch to PR
# From branch to PR in one command
claude -p "1. Create a branch feature/user-avatar from main.
2. Stage all modified files.
3. Make a Conventional Commits commit.
4. Push the branch.
5. Create a PR with gh cli, auto-generated title and body."
This workflow collapses five manual steps into a single prompt, typically saving noticeable time over running each command by hand.
Release workflow
# Prepare a complete release
claude -p "1. Verify the branch is clean (git status).
2. Generate the CHANGELOG since the last tag.
3. Bump the version in package.json (semver).
4. Commit the changelog and package.json.
5. Create a Git tag with the new version.
6. Push the branch and the tag."
Verify that all tests pass before launching this workflow. Claude Code does not run tests automatically unless you explicitly request it in the prompt.
Hotfix workflow
# Express hotfix from main
claude -p "1. Create a branch hotfix/fix-login from main.
2. Apply the following fix: in src/auth.ts, replace setTimeout(5000) with setTimeout(30000).
3. Commit with the message 'fix(auth): increase login timeout to 30s'.
4. Push and create an urgent PR with the label 'hotfix'."
This snippet illustrates the power of multi-step prompts. Each instruction is executed in order, with validation between steps. For developers wanting to master these advanced workflows, the AI-Augmented Developer - Advanced training from SFEIR deepens prompt chaining and AI tool orchestration in 1 intensive day.
Key takeaway: multi-step prompts transform Claude Code into a Git orchestrator. Combine multiple sequential operations in a single prompt for fluid workflows.
What pitfalls to avoid with Claude Code Git snippets?
Knowing common errors saves you time. Here are frequent problems and their solutions. The troubleshooting guide covers each case in detail.
Missing permissions
# Common error: permission denied for git push
# Solution: explicitly authorize in.claude/settings.json
# Add "Bash(git push *)" in permissions.allow
# Check permissions in the configuration file
cat.claude/settings.json
Without the Bash(git push *) permission, Claude Code asks for confirmation at each push. Add this line to your configuration for a fluid workflow.
Accidental force-push
# DANGEROUS - never authorize
# "Bash(git push --force *)" in permissions.allow
# SAFE - use force-with-lease instead
claude -p "Push with --force-with-lease to avoid overwriting others' commits."
The --force-with-lease flag verifies that the remote branch has not changed before forcing the push. This option protects against overwriting remote commits.
Context limits on large diffs
# For large diffs, limit the scope
claude -p "Commit only the files in src/components/ with an appropriate message."
# Avoid requesting a commit of 500+ modified files
# Prefer commits by folder or by feature
Claude Code has a limited context window. For very large diffs, split your commits into smaller logical groups so the change set fits comfortably in context.
| Pitfall | Risk | Solution |
|---|---|---|
| Force-push authorized | Commit loss | --force-with-lease |
| Diff too large | Context exceeded | Commits by folder |
| No checkpoint | Work loss | Use Esc+Esc |
| Permissions too broad | Destructive operations | Explicit deny list |
Key takeaway: configure a deny list in your permissions and systematically use --force-with-lease instead of --force to secure your Git workflows.
Recent articles about Claude

Claude Managed Agents: Anthropic's Platform for Production Agent Deployment
Anthropic launches Managed Agents: a cloud platform for deploying AI agents in production. Secure sandbox, checkpointing, multi-agent, autonomous sessions lasting hours. Notion, Rakuten, Asana and Sentry already use it.

Claude Code Dream & Auto Dream: Automatic Memory Consolidation
After 20 sessions, Auto Memory notes become a mess. Auto Dream solves this by automatically consolidating Claude Code's memory: deduplication, stale entry removal, relative-to-absolute date conversion.

Claude Code Auto Mode: Autonomy Without the Risk
Auto Mode in Claude Code eliminates permission interruptions while keeping a safety net. A classifier analyzes every action before execution and blocks destructive operations. The sweet spot between approving everything and letting everything through.
Claude Code Training
Master Claude Code fundamentals in 1 day with our expert instructors. 60% hands-on practice on real-world cases.
Discover the training