All Articles Claude Code

Claude Code Git Integration – Commits, Branches, and PRs

You're working on a project. You make changes. Those changes need to be tracked, reviewed, and merged.

You’re working on a project. You make changes. Those changes need to be tracked, reviewed, and merged. Sounds straightforward, right? But managing git workflows while AI is writing code can get messy fast. That’s where Claude Code’s integrated git management comes in—and it’s built on some rock-solid principles that keep your repository clean and your history intact.

Let me walk you through how Claude Code handles Git operations, from automatic commits to branch management and PR creation. By the end, you’ll understand exactly what Claude Code does behind the scenes and how to work with it effectively.

The Core Philosophy: Safety First

Before we dive into the mechanics, let’s talk about Claude Code’s approach to Git. It’s built on three ironclad principles:

  1. Never amend existing commits – Always create new commits when changes are needed
  2. Never force push – Maintain a clean, reviewable history
  3. Always ask before destructive operations – Rollbacks and rewrites require explicit user approval

Why? Because your Git history is a record of decisions, and that record matters. When you amend a commit, you’re rewriting history. When you force push, you’re potentially overwriting work from collaborators. Claude Code respects that, and it should. You’ll see these principles in action throughout.

Automatic Git Operations: What Claude Code Does

Here’s the thing about Claude Code: it’s not just writing code in isolation. It’s aware of your repository context, tracks what it changes, and manages Git as part of its workflow. Let me break down what happens automatically.

Staging and Checking Status

Whenever Claude Code starts working on files, it first checks the current state:

git status

This tells Claude Code:

  • Which branch you’re on
  • What’s already staged
  • What’s untracked
  • What’s modified but unstaged

This context matters because Claude Code won’t accidentally commit something you didn’t intend. It’s deliberate about what goes into each commit.

Reading Recent Commits

Claude Code also looks at your recent commit history:

git log --oneline -10

Why? Because it helps Claude Code understand the pattern of your commits—the style, the granularity, the message conventions. If your last five commits were “Fix typo in README”, Claude Code won’t suddenly create a novel-length commit message. It adapts to your style.

Checking Branch Tracking

When you create a feature branch, Claude Code verifies whether it’s tracking a remote:

git branch -vv

This ensures Claude Code knows whether pushing with -u (upstream) is necessary or if you’re already connected to the remote.

Creating Commits: The Right Way

This is where Claude Code really shines. Creating a commit isn’t just “throw all changes at git commit.” It’s deliberate and structured.

The Three-Step Process

Step 1: Check for staged changes

git status

Claude Code only works with what’s staged. If you’ve modified files but haven’t staged them, Claude Code will ask you what to do. This prevents accidental inclusion of unfinished work. This is a critical safety measure—you’re always in control of what gets committed.

Step 2: Create the commit with a message

Claude Code uses the git commit command with a message passed via a HEREDOC:

git commit -m "$(cat <<'EOF'
Implement user authentication module with JWT tokens

This commit adds a complete authentication system with:
- JWT token generation and validation
- Password hashing with bcrypt
- Session management
- Error handling for expired tokens

Tests are included for all public methods.

Co-Authored-By: Claude Code <[email protected]>
EOF
)"

Notice the structure here:

  • First line: Short, imperative description (the summary)
  • Blank line: Separation between summary and body
  • Body: Details about what changed and why
  • Co-author line: Attribution to Claude Code

This format follows Git best practices, especially important for teams using tools that parse commit messages (like automated changelogs). Claude Code always includes the co-author attribution so you know where the work came from.

Step 3: Verify the commit

git status

After committing, Claude Code checks status again to confirm the commit went through cleanly. This prevents silent failures where a commit appeared to work but didn’t actually create anything.

When Claude Code Refuses to Commit

Here’s something critical: Claude Code has guardrails. It won’t commit if:

  • There are uncommitted changes that weren’t intentional
  • The commit message is empty or nonsensical
  • Pre-commit hooks fail (and it won’t skip them with --no-verify)
  • GPG signing is configured and the commit can’t be signed
  • The repository is in a detached HEAD state and hasn’t been explicitly approved

These aren’t bugs—they’re features. They protect you from bad commits that could cause issues later. Pre-commit hooks especially exist for a reason—your team probably has style checks, security scans, or other validations running. Claude Code respects those.

Understanding Commit Message Best Practices

The commit messages Claude Code creates follow a pattern. Here’s why that matters:

Bad commit: “stuff”
Good commit: “Add password reset feature with email verification”

Claude Code learns your team’s conventions from recent history and adapts. If your team uses semantic commits (feat:, fix:, refactor:), Claude Code will too. If you use GitHub-style issue references (Fixes #456), Claude Code includes those.

The message body matters too. A good commit body explains:

  • What changed
  • Why it changed
  • Any edge cases or gotchas
  • Testing approach

This is invaluable when you’re debugging six months later and wondering “why did we do this?”

Branch Management: Creating and Switching

Branches are how you work on features without touching main. Claude Code can create and manage branches, but it follows strict patterns.

Creating a Feature Branch

You want Claude Code to create a feature branch? Here’s what happens:

git checkout -b feature/user-authentication

Simple, right? But Claude Code won’t do this blindly. It checks:

  • Are you on main or another base branch?
  • Is the base branch up to date?
  • Is the branch name valid and doesn’t conflict?
  • Is there a branch protection rule that would prevent pushing to main later?

And here’s the critical part: Claude Code creates new branches for each task. It doesn’t reuse existing feature branches. Why? Because separate branches mean separate, reviewable changes. Each feature gets its own history. When something breaks, you can bisect to find which commit introduced it.

Branch Naming Conventions

Claude Code respects standard branch naming:

  • feature/description – New features
  • fix/description – Bug fixes
  • docs/description – Documentation updates
  • refactor/description – Code refactoring
  • test/description – Test additions

If your team uses different conventions, Claude Code learns from your existing branches. It adapts automatically.

Tracking Remote Branches

When Claude Code pushes a local branch for the first time, it uses the -u flag:

git push -u origin feature/user-authentication

The -u flag sets the upstream, linking your local branch to its remote counterpart. This makes future pushes simpler and allows Claude Code to check if you’re up to date with the remote. Without upstream tracking, Claude Code would have to specify the remote every time.

Handling Branch Divergence

What if your local branch is ahead or behind the remote? Claude Code detects this:

git fetch origin
git branch -vv

If you’re behind, Claude Code can merge the latest:

git merge origin/feature/user-authentication

If you’re ahead, Claude Code is ready to push. It’s always aware of the branch state.

Pull Requests: The gh CLI Workflow

Now we get to the sophisticated stuff. Claude Code doesn’t just push code and hope—it creates pull requests via the GitHub CLI (gh).

Prerequisites

For this to work, you need:

  • gh CLI installed (brew install gh on Mac, choco install gh on Windows)
  • Authentication set up (gh auth login)
  • A GitHub repository

Creating a PR

Here’s the flow:

gh pr create \
  --title "Add user authentication with JWT" \
  --body "$(cat <<'EOF'
## Summary

Implements a complete JWT-based authentication system for the user API.

## Changes

- Added JWT token generation and validation
- Implemented bcrypt password hashing
- Created session management middleware
- Added comprehensive error handling

## Testing

All new code is covered by tests. Run:

```bash
npm test -- --testPathPattern=auth

Reviewer Notes

Please verify:

  • Token expiration is correctly enforced
  • Password hashing is production-ready
  • Session cleanup happens on logout

🤖 Generated with Claude Code
EOF
)”


Breaking this down:
- **Title**: Concise description of the PR (roughly first line of commit message)
- **Body**: Detailed explanation using Markdown, including Summary, Changes, Testing instructions, and reviewer notes
- **Attribution**: The "Generated with Claude Code" note so reviewers understand the source

This is critical for team communication. Your reviewers know what to expect and what to focus on.

### PR Metadata

Claude Code can also set labels, assignees, and reviewers on the PR:

```bash
gh pr create \
  --title "Add user authentication" \
  --body "Full description here" \
  --label "feature,auth" \
  --assignee @octocat \
  --reviewer @reviewer1,@reviewer2

This automatically notifies the right people and categorizes the work. Your team’s workflow becomes more efficient because PRs go to the right people immediately.

Understanding PR Templates

Many repositories have PR templates (.github/pull_request_template.md). Claude Code respects these and fills them out appropriately. The template structure is preserved, with Claude Code providing content for each section.

If a template requires specific information (like “This PR fixes issue #”), Claude Code includes it if available.

Handling Conflicts: When Things Collide

Git conflicts happen. You’re working on a feature, someone else pushes to main, and suddenly your branch is out of sync. What does Claude Code do?

Detection

git fetch origin
git status

Claude Code automatically fetches the latest state and checks for conflicts.

Resolution Strategy

Here’s what Claude Code won’t do: automatically resolve conflicts. Conflicts are decisions—which code version is correct? That’s not something an AI should decide unilaterally.

Instead, Claude Code will:

  1. Stop and show you the conflicting sections
  2. Explain what the conflict is and why it exists
  3. Ask you which resolution you prefer
  4. Implement your choice
  5. Commit the merge resolution

This is checkpoint-based workflow—it pauses at decision points. You’re always in control.

Example Conflict Resolution

If you have conflicting code:

<<<<<<< HEAD
function authenticate(username, password) {
  // Old implementation
  return validateUser(username, password);
}
=======
function authenticate(username, password) {
  // New implementation from teammate
  const user = findUserByEmail(username);
  return bcrypt.compare(password, user.hash);
}
>>>>>>> feature/new-auth

Claude Code shows both versions and asks: “Which implementation should we use? Should we combine them? What’s the right approach here?”

You decide. Claude Code executes. Then it commits the merge with a clear message explaining what was resolved and why.

Complex Conflicts and Three-Way Merges

For really complex conflicts (when the same section was changed in multiple ways), Claude Code can show you the base version too:

<<<<<<< HEAD
// Current version (from main)
=======
// Your version (from feature branch)
>>>>>>> feature/branch

Combined with the base (common ancestor), Claude Code explains the evolution and helps you make the right choice.

Checkpoint-Based Rollback: Undoing Without Drama

Made a mistake? Need to revert a change? Claude Code can help, but it won’t do a destructive git reset --hard without your approval.

The Rollback Request Format

If Claude Code (or you) needs to undo something, it looks like this:

## Risk Callout

**Action**: Reset repository to commit abc1234

**Risk Level**: Medium

**Potential Impact**: Uncommitted changes will be lost

**Rollback Plan**: Can restore from reflog within 30 days

**Approval Required**: Yes

> Awaiting user approval before proceeding.

Only after you approve does Claude Code execute:

git reset --hard abc1234

This prevents accidental data loss. Your approval is the safety check.

Understanding Git Reflog

Even if you reset and lose something, Git keeps a reflog for 30 days:

git reflog

This shows every change to HEAD, so you can recover commits even after a reset. Claude Code knows this and mentions it in rollback warnings.

Never Force Push: Why It Matters

Force push is tempting. You made a mistake in your last commit, and git push --force cleans it up instantly. But here’s the problem: if someone else pulled that branch, you just overwrote their work.

Claude Code never force pushes. Period. Instead:

# Wrong way (Claude Code won't do this)
git push --force

# Right way (Claude Code does this)
git push  # Standard push, will fail if behind remote

If you need to change a commit that’s already pushed, Claude Code creates a new commit that fixes the problem. Your history stays clean and reviewable.

Why This Matters for Teams

Imagine this scenario: Developer A pushes commit X. Developer B pulls it and starts working based on it. Developer A force-pushes a rewritten version. Now Developer B’s work is based on a commit that no longer exists. Merge conflicts appear from nowhere. Productivity drops.

Claude Code prevents this by never rewriting history. New commits fix problems, not rewrites.

Amending: The One Thing Claude Code Won’t Do

Here’s a direct rule: Claude Code never amends commits automatically, even if requested.

Why? Because amending rewrites history. If that commit is already in a PR or pushed to a shared branch, amending it confuses other developers and can cause merge conflicts.

Instead, Claude Code follows this pattern:

  1. Understand what needs to change
  2. Create a new commit that fixes the issue
  3. Explain why a new commit is better than an amendment

So if you ask Claude Code to fix a typo in a pushed commit, it won’t do git commit --amend. It’ll create a follow-up commit: “Fix typo in authentication module description.”

When Amending is Safe

Amending is only safe if:

  • The commit hasn’t been pushed
  • You’re working alone on the branch
  • You explicitly request it for a local-only commit

Even then, Claude Code will warn you about the risks.

Pre-Commit Hooks: Respecting Your Checks

Many projects have pre-commit hooks—scripts that run before each commit to validate code quality. Claude Code respects these hooks.

git commit -m "Add feature"
# Pre-commit hook runs
# Validates code style, runs linter, checks for secrets
# If anything fails, commit is rejected

Claude Code won’t skip hooks with --no-verify. If a hook fails, Claude Code:

  1. Shows you the failure message
  2. Fixes the underlying issue (if it can—like running a formatter)
  3. Retries the commit

This keeps your repository clean and maintains the standards you’ve set.

Common Pre-Commit Checks

Standard hooks you might encounter:

  • Linters: Check code style (ESLint, Pylint, Rubocop)
  • Formatters: Ensure consistent formatting (Prettier, Black)
  • Secret detection: Prevent committing API keys or passwords
  • Type checking: Run TypeScript or mypy checks
  • Test running: Ensure tests pass before committing

Claude Code works with all of these. If a formatter fails, Claude Code runs it and commits the formatted code. If tests fail, Claude Code shows you and asks what to do.

Practical Example: Full Workflow

Let’s put it all together. Here’s a realistic scenario:

You: “Add a password reset feature”

Claude Code:

  1. Checks current branch and status (git status)
  2. Creates a new branch: feature/password-reset
  3. Writes the feature code
  4. Stages the files (git add)
  5. Creates a commit: “Implement password reset flow with email verification”
  6. Pushes the branch: git push -u origin feature/password-reset
  7. Creates a PR with detailed description and testing instructions
  8. Reports: “PR #456 created and ready for review”

You review the PR. You ask for a small change.

Claude Code:

  1. Switches back to the feature branch
  2. Makes the requested change
  3. Creates a new commit: “Update email template as requested in review”
  4. Pushes: git push (already tracking remote, no -u needed)
  5. Notifies: “PR updated with your requested change”

No force pushes. No amending. No lost history. Clean, reviewable, safe.

What Claude Code Knows (and Doesn’t Know)

Claude Code is pretty smart about Git, but it has limits:

Claude Code knows:

  • Creating and switching branches
  • Staging files and creating commits
  • Pushing to remotes
  • Creating PRs via gh CLI
  • Checking for conflicts
  • Reading commit history
  • Merging branches
  • Checking branch protection rules

Claude Code doesn’t do (and asks before):

  • Force push
  • History rewriting
  • Amending commits
  • Destructive resets
  • Changing remote URLs
  • Managing submodules
  • Cherry-picking (it’ll help you understand it, but won’t do it automatically)
  • Rebasing (too risky without user verification)

These limitations aren’t oversights—they’re intentional safeguards. They protect you and your team.

Working With Claude Code: Best Practices

Now that you understand how Claude Code works with Git, let’s talk about getting the most out of it. There are patterns and practices that make the whole workflow smoother.

Commit Messages Matter

Claude Code pays attention to your commit message style. If you work with developers who expect imperative mood (“Add feature” not “Added feature”), Claude Code learns that. If your team uses commit scopes (“feat: add auth” instead of “Add auth”), Claude Code picks that up from your history.

This is why Claude Code reads your recent commits. It’s not being nosy—it’s learning your conventions. When you run your first Claude Code task on a new repo, it’s literally studying your Git history to match your team’s style.

Your commit messages become code documentation. Good messages make debugging easier six months from now.

Clear Prompts Lead to Clear Commits

The more specific you are with Claude Code, the better the commits. Compare these:

Vague: “Fix the auth system”

Clear: “Update JWT token expiration from 24 hours to 1 hour and add refresh token logic”

The second one naturally leads to a better commit message. Claude Code will create commits that match the precision of your request. Vague requests create vague commit messages. Specific requests create specific, reviewable commits.

Review Before Pushing

While Claude Code is automating Git operations, you’re still the final authority. When Claude Code creates a PR or makes a commit, you can review it first. You can ask it to adjust the commit message, break a large commit into smaller ones, or squash multiple commits into one.

Claude Code won’t push anything without your approval. The workflow is:

  1. Claude Code stages and commits
  2. Claude Code shows you what it created
  3. You review and approve
  4. Claude Code pushes and creates the PR

This review step is crucial. It’s where you catch issues before they hit the repository. You might see that the commit is too large, or the message could be clearer, or there’s a file included that shouldn’t be. This is your opportunity to improve it.

Managing Large Changes

What if you’re making a massive refactor—hundreds of files changed, thousands of lines of code? Claude Code handles this with multiple commits:

# First commit: Large structural changes
git add src/models/
git commit -m "Refactor user model structure for better separation of concerns"

# Second commit: Updated tests
git add tests/
git commit -m "Update tests for refactored user model"

# Third commit: Migration logic
git add migrations/
git commit -m "Add database migration for new user model schema"

Each commit is logical and reviewable. Someone reviewing the PR can understand each change separately, rather than drowning in one massive diff. This also makes bisecting easier if something goes wrong—you can pinpoint exactly which commit introduced a bug.

Handling Branch Protection Rules

Many repositories have branch protection—you can’t push directly to main, you must use PRs, all checks must pass, etc. Claude Code respects these rules.

When you push to main and branch protection rejects it, Claude Code automatically:

  1. Recognizes the rejection
  2. Creates a feature branch
  3. Pushes there instead
  4. Creates a PR

You’re back on track without having to manually fix anything. Claude Code understands the constraint and works around it automatically.

Collaborating With Teammates

Here’s a scenario: your teammate pushed code while you were working on a feature. Your branch is now behind. What does Claude Code do?

git fetch origin
git merge origin/main

Claude Code fetches the latest and merges. If there are conflicts, it stops and asks you to resolve them. If it’s a clean merge, it creates a merge commit and updates your branch automatically.

No force push. No rebasing without asking. Just clean, safe integration with your teammate’s work.

Using Claude Code in Teams

Working in a team? There are some extra considerations:

Communication: Since Claude Code is making commits with “Co-Authored-By”, your teammates will know that Claude helped. It’s transparent. No confusion about where code came from.

Code review: PRs created by Claude Code need review just like any other PR. Reviewers should check the logic, test coverage, and code quality. Claude Code is a tool that writes code, not a replacement for human review.

Style consistency: Claude Code learns your team’s style from recent commits, so it tends to write code that fits your existing conventions. But human reviewers should still check for consistency. Over time, reviewers will notice patterns and can provide feedback.

Testing: Claude Code can write tests, but humans should verify they’re comprehensive. Test coverage is your responsibility. Claude Code is a tool that helps, but doesn’t replace your testing discipline.

Debugging: When Things Go Wrong

Eventually, something will go wrong. Maybe a commit was made to the wrong branch. Maybe a PR was created with incomplete code. What then?

Reading the Git Log

When Claude Code reports an issue, it’s often helpful to check the Git log yourself:

git log --oneline --all

This shows every commit, on every branch. You can see exactly what Claude Code did and when. The --all flag shows all branches, not just the current one.

You can also see who made each commit:

git log --oneline --author="Claude Code"

This filters to just Claude Code’s commits, which is helpful if you’re debugging a specific issue.

Checking Branch Status

git branch -vv

Shows all branches, what they’re tracking, and whether they’re ahead or behind the remote. This tells you the exact state of every branch at a glance.

If a branch is 5 commits behind origin, you might need to merge. If it’s 10 commits ahead, you probably forgot to push.

Examining Staged Changes

git diff --staged

Shows exactly what will be committed. If Claude Code is about to commit something unexpected, this is how you see it before it happens.

You can also compare your branch to main:

git diff main..HEAD

This shows all changes in your branch compared to main. Useful for code review.

Restoring Files

Accidentally committed something? You have options:

# See what was in a previous commit
git show HEAD~1:path/to/file

# Create a new commit that reverts a specific file
git revert --no-edit HEAD

# Restore a deleted file
git checkout HEAD~1 -- path/to/deleted/file

You can always undo changes. Git is designed for it. The key is doing it safely (new commits, not rewrites).

Advanced Git Workflows With Claude Code

Once you’re comfortable with the basics, Claude Code can handle more sophisticated workflows.

Working With Multiple Feature Branches

You’re building multiple features simultaneously. Claude Code keeps them separate:

# Work on feature 1
git checkout -b feature/authentication
# Claude Code makes commits here

# Switch to feature 2
git checkout -b feature/notifications
# Claude Code makes commits there

# Back to feature 1
git checkout feature/authentication
# Claude Code continues where it left off

Each branch has its own history. Each PR is independent. Your work doesn’t interfere with itself. Claude Code tracks which branch you’re on and makes commits in the right place.

Release Branches

Some teams use release branches—main is for development, release/1.0 is for the stable version. Claude Code can work with this:

git checkout release/1.0
# Claude Code makes bug fixes here
git push

# Then back to main for new features
git checkout main
# Continue development

The key is that Claude Code always verifies which branch you’re on before committing. It won’t accidentally commit a feature to your release branch. It understands the semantic difference between branches.

Hotfixes

A bug in production. You need to fix it immediately. Claude Code handles hotfix branches:

git checkout -b hotfix/critical-bug origin/release/1.0
# Claude Code implements the fix
git push -u origin hotfix/critical-bug
# PR is created against release/1.0

Once fixed and merged, you can cherry-pick that commit back to main:

git checkout main
git cherry-pick hotfix-commit-hash

Claude Code understands this workflow and will guide you through it. Hotfixes are time-sensitive, so Claude Code moves efficiently while staying safe.

Monorepos and Workspaces

If you’re working with a monorepo (multiple projects in one repo), Claude Code respects project boundaries:

# Changes are committed with the specific package
git commit -m "feat(auth): add JWT tokens"

# This tells reviewers exactly which project was affected

Claude Code learns these conventions and applies them consistently.

The Bigger Picture

Here’s what makes Claude Code’s Git integration special: it’s not trying to be clever. It’s not making assumptions. It’s following established Git practices and respecting your control.

You tell Claude Code what to build. Claude Code:

  • Creates the code
  • Stages the files
  • Commits with clear messages
  • Creates PRs for review
  • Never makes destructive decisions unilaterally

That’s it. Simple. Safe. Professional.

The safety rails—no force push, no amending, checkpoint-based decisions—aren’t limitations. They’re the right way to use Git in a team environment. Claude Code built Git integration the way Git should be used: carefully, clearly, respectfully.

Integrating Claude Code Into Your Workflow

You might be wondering: how do I actually use this with my existing development process?

The answer is simpler than you’d think. Claude Code integrates into whatever workflow you already have. Using GitHub? Claude Code creates PRs. Working with GitLab? Claude Code’s principles apply there too. Using traditional review processes? Claude Code commits are perfect for those. Continuous integration? Claude Code respects your CI rules.

The key is that Claude Code doesn’t force a workflow on you. It adapts to yours. If your team reviews code before merge, Claude Code creates reviewable commits. If you use semantic commit messages, Claude Code learns that from your history. If you have automated tests on every PR, Claude Code respects those checks.

When you first start using Claude Code on a project, take a moment to check your recent commits. Claude Code will be doing things the way your team does them. It’s learning from you automatically.

Summary: Git With Safety Rails

Claude Code’s Git integration boils down to this: it automates the mechanics while preserving your control over the important decisions.

You get automatic staging, clean commit messages, and straightforward branch management. But when conflicts arise, when rollbacks are needed, when history matters—Claude Code pauses and asks.

No force pushes. No amending. No surprises. Just solid, reliable Git workflows that respect both your code and your collaborators.

The next time you use Claude Code on a project, watch what it does with Git. You’ll see those principles in action at every step. Create a branch. Write code. Commit it. Push. Create a PR. Review. Iterate. All with the safety and clarity that professional development demands.

And that’s when you’ll realize: this is how automated coding should work.


-iNet

Free Discovery Call

Start With a Conversation, Not a Commitment

Every engagement begins with a free 30-minute discovery call. We'll map what's slowing your business down and tell you exactly what we'd fix first – no pitch deck, no obligation.