Learning Objectives
- Understand Claude Code's git safety protocol and why it protects your repository
- Create well-crafted commits with Claude-generated messages that follow conventional style
- Open pull requests with structured titles, summaries, and test plans using
gh pr create - Review existing pull requests with
claude --from-prfor AI-powered code analysis - Resolve merge conflicts intelligently by letting Claude understand both sides of a change
Git is the backbone of modern software development, but it is also one of the most error-prone parts of the workflow. A force push to the wrong branch can destroy days of work. A poorly written commit message makes debugging impossible three months later. A missed security vulnerability in a pull request can reach production. Claude Code transforms git from a source of anxiety into a structured, safe, and expressive part of your development process.
This lesson covers the full git lifecycle with Claude Code: from committing changes and managing branches to opening pull requests and reviewing code. Every pattern here reflects how Claude Code actually operates under the hood, including the safety constraints that prevent catastrophic mistakes.
The Git Safety Protocol
Before diving into workflows, you need to understand the safety guarantees Claude Code enforces when working with git. These are not suggestions. They are hard constraints built into how Claude operates.
Claude Code will NEVER run destructive git commands unless you explicitly request them. This includes:
git push --force(can overwrite remote history)git reset --hard(discards all uncommitted changes)git checkout .orgit restore .(reverts all working tree changes)git clean -f(deletes untracked files permanently)git branch -D(force-deletes a branch regardless of merge status)
Destructive Commands Require Explicit Consent
Even if your prompt implies you want to start fresh, Claude Code will not run git reset --hard or git clean -f on its own. You must explicitly say something like "reset my branch to match origin/main" for Claude to execute destructive operations. This prevents accidental data loss from ambiguous instructions.
Beyond avoiding destruction, Claude Code follows additional safety principles:
- Always creates NEW commits rather than amending previous ones. When a pre-commit hook fails, the commit did not happen, so
--amendwould modify the wrong commit. Claude stages fixes and creates a fresh commit instead. - Prefers staging specific files by name over
git add -Aorgit add ., which can accidentally include sensitive files like.env, credentials, or large binaries. - Never skips hooks such as
--no-verifyor--no-gpg-signunless you explicitly request it. - Never force pushes to main/master and will warn you if you ask it to.
This protocol means you can hand Claude Code significant git autonomy without worrying about repository-destroying accidents.
Creating Commits
The commit workflow is one of the most common interactions you will have with Claude Code. Instead of writing commit messages yourself, you describe what you have done (or just say "commit"), and Claude analyzes the actual changes to produce a precise, conventional commit message.
The Commit Workflow Step by Step
When you ask Claude to commit your changes, it follows a structured process:
Analyze the repository state
Claude runs git status to see untracked and modified files, plus git diff to examine both staged and unstaged changes. It also checks recent commit messages with git log to match your project's existing style.
Stage the right files
Claude adds relevant files by name rather than using blanket git add . commands. If it detects files that look like secrets (.env, credentials.json, API keys), it warns you instead of staging them.
Draft a commit message
Claude analyzes the nature of the changes (new feature, bug fix, refactor, test, documentation) and drafts a concise message that focuses on the why rather than the what. The diff already tells reviewers what changed; the message explains the intent.
Create the commit
Claude uses a HEREDOC format for multi-line commit messages and appends a Co-Authored-By trailer to indicate AI collaboration. It then runs git status to verify the commit succeeded.
Here is what this looks like in practice:
> I've fixed the race condition in the WebSocket handler. Commit these changes.
Claude examines the diff, sees that you added a mutex lock around the connection pool access, and produces:
git commit -m "$(cat <<'EOF'
fix: Prevent race condition in WebSocket connection pool
Add mutex lock around pool access to prevent concurrent goroutines
from corrupting shared connection state during high-traffic bursts.
Co-Authored-By: Claude Code <noreply@anthropic.com>
EOF
)"Notice how the message explains why the mutex exists (preventing corruption during high-traffic bursts) rather than merely stating what was added (a mutex lock). This distinction makes commit history genuinely useful for future debugging.
Conventional Commit Style
Claude Code follows the conventional commits specification by default, using prefixes that categorize changes:
| Prefix | When to Use | Example |
|---|---|---|
| feat: | New functionality | feat: Add email verification to signup flow |
| fix: | Bug correction | fix: Resolve null pointer in user lookup |
| refactor: | Code restructuring (no behavior change) | refactor: Extract validation logic into shared module |
| docs: | Documentation only | docs: Add API rate limiting examples to README |
| test: | Adding or updating tests | test: Add integration tests for payment webhook |
| chore: | Maintenance, dependencies, configs | chore: Upgrade Express from 4.x to 5.x |
| perf: | Performance improvement | perf: Cache database queries for dashboard stats |
If your project uses a different convention, add it to your CLAUDE.md file:
# Git Conventions
- Commit messages use Jira ticket prefix: [PROJ-123] Description
- No conventional commit prefixes
- Keep subject line under 50 charactersClaude reads this at session start and adapts its commit messages accordingly.
Creating Pull Requests
Claude Code uses the GitHub CLI (gh) to create pull requests with structured, informative descriptions. The process goes beyond just running gh pr create. Claude inspects the full branch history to produce a meaningful summary.
The Pull Request Workflow
> Create a PR for my changes
Or use the built-in skill:
> /commit-push-pr
Behind the scenes, Claude follows this sequence:
Check the repository state
Claude runs git status to check for uncommitted changes, verifies whether the current branch tracks a remote, and determines if it needs to push.
Analyze the full branch diff
Claude runs git log and git diff main...HEAD (or your base branch) to understand ALL commits on the branch, not just the latest one. This is critical for producing accurate PR descriptions.
Push the branch
If the branch has not been pushed or is behind the remote, Claude pushes with the -u flag to set up tracking.
Create the pull request
Claude generates a title (under 70 characters), a structured body with a summary and test plan, and creates the PR using gh pr create.
The generated PR follows a consistent structure:
## Summary
- Add rate limiting middleware for all API endpoints
- Configure Redis-backed sliding window counter
- Add bypass for internal health check routes
## Test plan
- [ ] Verify rate limit headers appear in API responses
- [ ] Confirm 429 status after exceeding limit
- [ ] Check health endpoint bypasses rate limiting
- [ ] Run load test to validate sliding window behaviorSession Linking
When Claude creates a PR using gh pr create, the session is automatically linked to that PR number. You can later resume the session with claude --from-pr <number>, which is especially useful when returning to address review feedback.
Customizing PR Behavior
Add PR conventions to your CLAUDE.md to ensure consistency across your team:
# PR Conventions
- PR titles use conventional commit format: "feat: Description"
- Always include a "## Breaking Changes" section if applicable
- Link related Jira tickets in the description
- Add "Reviewers: @team-lead" to all PRsCode Review with --from-pr
One of Claude Code's most powerful git integrations is AI-powered code review. Using the --from-pr flag, Claude reads an entire pull request diff, understands the context of every change, and provides structured feedback.
Reviewing a Pull Request
claude --from-pr https://github.com/org/repo/pull/42Or using just the PR number when you are inside the repository:
claude --from-pr 42Claude reads the full diff, checks for common issues, and provides detailed feedback. You can guide the review with a follow-up prompt:
> Focus on security issues and potential breaking changes
What Claude Checks During Review
Claude performs a multi-dimensional analysis when reviewing code:
Using Claude as a CI Reviewer
You can also integrate Claude Code into your CI pipeline for automated review on every pull request:
# In a CI script or package.json
claude -p "Review the changes in this PR. Focus on security, correctness, and performance. Flag anything that should block merge." --from-pr $PR_NUMBERBranch Management
Claude Code handles the full branch lifecycle through natural language commands.
Creating and Switching Branches
> Create a new feature branch for adding email notifications
Claude creates a descriptively named branch from your current base:
git checkout -b feat/email-notificationsTo switch branches:
> Switch to the staging branch
Claude runs git checkout staging, and if you have uncommitted changes, it will warn you before switching and suggest stashing or committing first.
Working with Remote Branches
> Pull the latest changes from main and rebase my branch on top
Claude runs git fetch origin followed by git rebase origin/main, handling the common workflow of keeping a feature branch up to date. If conflicts arise during the rebase, Claude shifts into conflict resolution mode (covered in the next section).
Merge Conflict Resolution
Merge conflicts are one of the most stressful parts of git. Claude Code transforms conflict resolution from a manual, error-prone process into an intelligent, context-aware operation.
How Claude Resolves Conflicts
When a merge or rebase produces conflicts, Claude does not blindly pick one side. It follows a structured approach:
Read the conflict markers
Claude identifies every file with conflict markers (<<<<<<<, =======, >>>>>>>) and reads the full surrounding context to understand what each side intended.
Understand the intent of both sides
Claude examines the commit messages, the branch names, and the broader diff to determine what each conflicting change was trying to accomplish.
Resolve based on combined intent
Rather than picking "ours" or "theirs," Claude often produces a resolution that incorporates the intent of both changes. For example, if one side added a new parameter to a function and the other side renamed it, Claude applies both the rename and the new parameter.
Verify the resolution
Claude checks that the resolved code compiles (if applicable), passes linting, and is logically consistent with the changes on both sides.
Here is a practical example:
> I tried to rebase on main and got conflicts in three files. Help me resolve them.
Claude reads each conflicted file, explains what both sides changed, proposes a resolution, and applies it. You review each resolution before Claude stages it and continues the rebase.
Complex Conflicts
For large conflicts spanning many files, ask Claude to resolve them one file at a time: "Resolve the conflict in src/auth/middleware.ts first, then we'll move to the next file." This gives you more control over each resolution.
Git History Analysis
Git history is a powerful debugging and understanding tool, but most developers underuse it because the commands are awkward. Claude Code makes history analysis conversational.
Understanding Code Evolution
> Why was the retry logic in api-client.ts changed last month?
Claude runs git log --oneline -20 -- src/api-client.ts to find relevant commits, then uses git show <hash> to read the full diffs and commit messages. It synthesizes this into a narrative explanation of how and why the code evolved.
Debugging with Git Bisect
> The dashboard started showing incorrect totals sometime in the last two weeks. Help me find which commit broke it.
Claude can guide a git bisect session, helping you define the good and bad commits, then systematically testing midpoints to isolate the exact commit that introduced the regression.
Blame Analysis
> Who last modified the pricing calculation logic and why?
Claude runs git blame on the relevant file, identifies the author and commit, then reads the commit message and surrounding changes to explain the reasoning behind the modification.
Full Git Workflow with Claude Code
intermediate20 minPractice the complete git lifecycle by building a small feature, committing it with Claude, creating a PR, and then reviewing someone else's work.
Part 1: Feature Branch and Commit
- Navigate to a project repository (or create a test repo with
git init) - Start Claude Code and ask it to create a feature branch:
> Create a feature branch called feat/add-health-check - Create a simple health check endpoint (or any small code change)
- Ask Claude to commit your changes:
> Commit these changes with a descriptive message - Observe how Claude stages specific files, analyzes the diff, and writes a conventional commit message with the Co-Authored-By trailer
Part 2: Create a Pull Request
- Ask Claude to create a pull request:
> Push this branch and create a PR against main - Review the generated PR title, summary, and test plan
- Note how Claude checked the branch status and pushed before creating the PR
Part 3: Review a Pull Request
- Find an open PR in any public repository (or use one from a teammate)
- Start a new Claude Code session with the review flag:
bash
claude --from-pr https://github.com/org/repo/pull/123 - Ask Claude to focus its review:
> Review this PR for security issues and missing error handling - Examine how Claude provides line-specific feedback with suggested improvements
Bonus Challenge: Intentionally create a merge conflict by modifying the same line on two branches, then ask Claude to resolve it. Observe how it reads both sides and produces an intelligent resolution.
Key Takeaway
- Claude Code enforces a strict git safety protocol: no destructive commands without explicit permission, new commits instead of amending, specific file staging instead of
git add -A, and never skipping hooks - The commit workflow is structured: analyze the diff, stage specific files, write a "why"-focused message in conventional commit format, and append a Co-Authored-By trailer using HEREDOC formatting
- Pull request creation with
gh pr createincludes analyzing the full branch diff (all commits, not just the latest), generating a structured summary with test plan, and pushing the branch if needed - The
--from-prflag enables AI-powered code review that checks for security vulnerabilities, logic errors, performance issues, and style consistency across the entire pull request diff - Merge conflict resolution goes beyond picking sides; Claude reads both changes, understands the intent from commit messages and context, and produces resolutions that incorporate both purposes
- Git history commands like
git log,git blame, andgit bisectbecome conversational tools for understanding code evolution and debugging regressions