# Working with Git via Claude Code: A Beginner's Guide

> A complete hands-on guide to Git integration in Claude Code: smart staging, automated commit messages, merge conflict resolution, GitHub CLI, and safety guardrails.

## 1. Understanding Git Integration in Claude Code

Claude Code features deep native integration with the Git version control system. Unlike browser-based AI chats where developers have to manually copy-paste `git diff` outputs or status logs, the Claude Code terminal agent directly communicates with your local repository using built-in execution tools.

The agent inspects file changes, checks project commit history, follows established team naming conventions, and handles routine version control operations: creating isolated branches, staging specific files, running clean rebases, and generating complete Pull Request descriptions.

```mermaid
flowchart TD
    A["Developer Prompt:<br><i>'Commit current changes'</i>"] --> B["Claude Code CLI"]
    B --> C["git status<br><i>(Check modified files)</i>"]
    B --> D["git diff<br><i>(Analyze changes and logic)</i>"]
    B --> E["git log -n 5<br><i>(Infer commit conventions)</i>"]
    C & D & E --> F["Smart Staging<br><i>(Selective git add &lt;file&gt;)</i>"]
    F --> G["Commit Message Generation<br><i>(Contextual feat/fix)</i>"]
    G --> H{"User Confirmation"}
    H -->|Approved| I["Execute git commit"]
    H -->|Adjustment| J["Update message"]
```

### Advantages of Git via Claude Code

| Feature | Traditional Manual Git | Working with Claude Code |
| :--- | :--- | :--- |
| **Change Analysis** | Manual inspection of each file via `git diff` | Automated comprehension of semantics and cross-file dependencies |
| **Commit Messages** | Frequently uninformative messages like *"update"*, *"fix"* | Structured messages following the Conventional Commits specification |
| **Staging** | Risk of accidentally staging secrets or logs via `git add .` | Granular staging of relevant application code only |
| **Merge Conflicts** | Complex manual reconciliation of conflict markers `<<<<<<<` | Intelligent synthesis preserving intent from both branches |
| **PR Creation** | Writing summary, change lists, and test plans by hand | Automated rich markdown PR creation powered by `gh CLI` |

> [!NOTE]
> Claude Code operates in the isolated context of your local repository and always asks for confirmation before executing actions that alter files or rewrite git history.

---

## 2. Creating Commits: Intelligent Staging and Descriptions

The most frequent daily workflow for any developer is committing code. Instead of running three or four sequential commands in the terminal, you can prompt Claude Code in natural language:

```bash
Commit these changes with a descriptive message
```

### What Happens Under the Hood

When Claude receives a commit instruction, it follows a systematic diagnostic workflow:

1. **Working Tree Inspection:** executes `git status` to examine modified, deleted, and newly untracked files.
2. **Semantic Code Analysis:** runs `git diff` to inspect modified lines, distinguishing business logic from formatting or whitespace.
3. **Repository Style Learning:** reviews `git log -n 5` to identify team conventions (such as `feat(auth): ...` or concise sentence-style summaries).
4. **Selective Staging:** stages only the files related to the current task, skipping unrelated configuration or secret files.
5. **Message Formulation:** drafts a concise title and meaningful description explaining the context, problem, and solution.

:::tabs
@tab Conventional Commits
```text
feat(cart): implement instant item quantity counter in navbar

- Add reactive useCartCount hook to synchronize state across tabs
- Optimize database query to aggregate item count in a single request
- Add unit tests for edge cases when cart contains empty items
```
@tab Simple / Concise
```text
fix: resolve race condition in token refresh flow

Prevent multiple parallel requests from triggering duplicate OAuth
refresh cycles when access token expires.
```
@tab Issue-Linked (Jira/Linear)
```text
PROJ-412: refactor notification worker queue

Migrate Redis connection pool to cluster mode to handle burst traffic.
Closes #184.
```
:::

> [!TIP]
> If you want to commit only a specific file or subset of changes, specify it directly: `Commit only the changes in src/components/Header.tsx with an appropriate message`.

---

## 3. Branch Management and Context Switching

Isolating features in dedicated branches is a cornerstone of collaborative software development. Claude Code allows you to create a branch and dive straight into implementation without hopping back and forth between your terminal and code editor.

### Creating and Switching Branches

```bash
# Create a new branch and switch to it
Create a new branch named feature/instant-search and switch to it
```

Claude automatically runs `git checkout -b feature/instant-search` (or `git switch -c`).

### Combining Branch Creation with Implementation

You achieve maximum productivity when pairing branch creation with an engineering goal:

```bash
Create a branch called fix/email-validation, then fix the regex check in the signup form and write a test for it
```

### Standard Branch Naming Prefixes

- `feature/` or `feat/` — new feature or UI component (e.g. `feature/stripe-payments`).
- `fix/` or `bugfix/` — bug fixes (e.g. `fix/oauth-redirect`).
- `refactor/` — internal code restructuring without changing behavior (e.g. `refactor/user-service`).
- `chore/` — dependency updates, CI/CD configs, or docs (e.g. `chore/upgrade-nextjs-15`).

---

## 4. Resolving Merge Conflicts

Merge conflicts occur when the same lines of code have been modified in two divergent branches. Manually resolving them in an editor often results in accidentally dropping necessary code or introducing syntax errors.

Claude Code inspects both sides of the conflict, understands the intent of both contributors, and produces a harmonious resolution without losing functionality.

### Step-by-Step Conflict Resolution Workflow

1. **Initiate the merge or rebase in your terminal:**
   ```bash
   git merge origin/main
   # or
   git rebase main
   ```
2. **When conflict markers appear, invoke Claude Code:**
   ```bash
   I have merge conflicts after rebasing on main. Please inspect each conflicting file, analyze both sides of the changes, and resolve them cleanly.
   ```
3. **Marker Inspection:** Claude reads `<<<<<<< HEAD`, `=======`, and `>>>>>>>` markers, analyzing how changes interact with the surrounding codebase.
4. **Build & Type Verification:** after removing markers, the agent runs your typechecker (`tsc --noEmit`) or test runner (`npm test`) to guarantee stability.
5. **Staging Resolved Files:** the agent runs `git add <resolved-files>` and prepares the final step to conclude the merge.

```typescript
// Conflict example in a configuration module:
<<<<<<< HEAD
export const API_TIMEOUT = 10000; // Increased timeout for slow networks in feature branch
=======
export const API_TIMEOUT = 8000; // Updated backend standard from main
export const RETRY_ATTEMPTS = 3;  // New parameter added by teammate in main
>>>>>>> origin/main
```

Claude will suggest a synthesized resolution: preserving your higher `10000` timeout while incorporating the new `RETRY_ATTEMPTS = 3` constant from `main`.

---

## 5. Cherry-pick, Rebase, and Backporting Commits

Sometimes you need to move an isolated bug fix or security patch into a release branch without pulling in ongoing experimental work. This is where `cherry-pick` and `rebase` shine.

### Cherry-Picking a Specific Commit

```bash
Cherry-pick commit a7b9c1d from branch feature/cart onto release/v1.2.0
```

If any minor file path differences or syntax incompatibilities arise, Claude will adapt import paths and resolve dependencies on the fly.

### Intelligent Backporting

In projects maintaining multiple LTS versions, backporting fixes is routine. You can instruct Claude to execute the full pipeline:

```bash
Backport the security fix from commit 3f8a92 to the legacy-support branch. Verify that existing legacy tests still pass and commit the result.
```

### Rebase vs. Merge: When to Use Which

| Operation | When to Use | Key Benefits | Claude's Action |
| :--- | :--- | :--- | :--- |
| **`git rebase main`** | Catching up a feature branch with latest changes on `main` | Linear, clean commit history without redundant merge commits | Steps through commits sequentially, resolving trivial conflicts automatically |
| **`git merge main`** | Merging a completed feature into a shared staging/release branch | Preserves exact chronological order and merge boundaries | Generates a single merge commit with an itemized summary of changes |

---

## 6. Managing Temporary Changes with Git Stash

When you need to pause your current task to address an urgent production bug or test a teammate's branch, but your work isn't ready for a commit, `git stash` is essential.

Claude Code can execute multi-step stash workflows seamlessly:

```bash
Stash my current changes with a label 'wip-checkout', switch to main, pull latest changes, and report back
```

### Restoring Stashed Work

Once your urgent task is complete, restore your stashed work:

```bash
Switch back to feature/checkout, pop the stash 'wip-checkout', and resolve any conflicts if the base changed
```

> [!TIP]
> Claude's semantic understanding ensures that even if upstream files changed while your code was stashed, it will cleanly merge the uncommitted delta without data loss.

---

## 7. Creating Pull Requests and GitHub CLI (gh) Integration

When you have the official GitHub CLI (`gh`) installed, Claude Code functions as an end-to-end pull request assistant, authoring structured descriptions and setting up reviews.

### Automating PR Creation with Claude

Rather than switching to your browser to fill out forms manually, prompt Claude:

```bash
Push current branch to origin and create a pull request with gh CLI. Include summary, list of changes, and testing instructions.
```

### Sample Generated Pull Request

Claude formats an industry-standard markdown template:

```markdown
## Summary
This PR implements user session invalidation on password reset to prevent
unauthorized access from stolen legacy tokens.

## Changes
- Add `revokeAllUserSessions` service in `src/services/auth.ts`
- Update password reset controller to call invalidation hook
- Add Redis blacklist mechanism for active JWT tokens
- Cover revocation flow with integration tests in `auth.test.ts`

## Testing Instructions
1. Login from two different browsers (simulate active sessions)
2. Trigger "Forgot Password" flow in Browser A
3. Verify that Browser B gets redirected to `/login` on next API call
4. Run test suite: `npm run test:auth`

Fixes #284
```

> [!IMPORTANT]
> Verify your CLI session is active with `gh auth status` before issuing pull request prompts.

---

## 8. Built-in Safety Rules and Guardrails

Git is a versatile tool, but reckless flags can erase local work or rewrite shared repository history. Claude Code includes strict safety guardrails designed to prevent accidental damage.

```mermaid
flowchart LR
    subgraph Destructive_Actions["Blocked without explicit approval"]
        D1["git push --force to main"]
        D2["git add -A / git add ."]
        D3["git commit --amend on pushed commits"]
        D4["git commit --no-verify"]
    end
    subgraph Safe_Practices["Claude Code Default"]
        S1["Regular push or forward-fix commit"]
        S2["Selective staging of specific files"]
        S3["Create clean subsequent commit"]
        S4["Fix linter/test errors cleanly"]
    end
    D1 -.-> S1
    D2 -.-> S2
    D3 -.-> S3
    D4 -.-> S4
```

### Four Golden Safety Rules of Claude Code

1. **No Destructive Force Push:** Claude never executes `git push --force` or `-f` against protected branches (`main`, `master`, `release`) without repeated, explicit confirmation.
2. **Selective Staging:** the agent avoids reckless `git add .` or `git add -A` calls. Each file is staged by exact path to prevent accidental leakage of `.env` credentials, cryptographic keys, or local database dumps.
3. **History Preservation:** the agent favors creating a new corrective commit over rewriting history with `git commit --amend`, particularly when commits have already been pushed upstream.
4. **Respect Pre-commit Hooks:** Claude will not use `--no-verify` to bypass Husky, ESLint, or Prettier checks. If a hook fails, Claude diagnoses the root cause, fixes the code, and re-runs the commit legitimately.

> [!WARNING]
> Never prompt an AI agent to run unverified `git reset --hard HEAD~N` commands on shared branches. Always create a temporary backup branch or use `git stash` before major historical refactorings.

---

## 9. Hands-on Workshop: From Feature Branch to PR

Let's walk through a complete, real-world development lifecycle with Claude Code — from receiving a requirement to submitting a verified Pull Request.

### Step 1. Working Tree Health Check and Branch Setup

Open your terminal in the repository, start `claude`, and run:

```bash
Check git status, pull latest changes from main, and create a feature branch called feature/user-avatar
```

Claude ensures your tree is clean, pulls upstream updates, and switches to your new branch.

### Step 2. Implementing the Feature

Provide the feature specification to Claude:

```bash
Add an Avatar component in src/components/Avatar.tsx that renders a user image with fallback initials if the image URL is missing.
```

### Step 3. Verification and Targeted Commit

Once the component is created, prompt Claude to verify and commit:

```bash
Review what was created, make sure tests pass, and commit only the avatar component files with a clear conventional commit message
```

Claude runs the test suite, adds `src/components/Avatar.tsx` and its test, then produces a clean commit:

```text
feat(ui): add Avatar component with initials fallback

- Render user image with rounded profile styling
- Fallback to calculated two-letter initials on missing src or error
- Add unit test coverage for invalid image source handling
```

### Step 4. Push and Open Pull Request

Finalize the workflow with a single instruction:

```bash
Push this branch to GitHub and create a draft PR using gh CLI describing the changes
```

---

## 10. Knowledge Check and Final Checklist

Reinforce the concepts learned in this guide with a quick self-assessment.

### Review Questions

> **1. Why does Claude Code stage files by specific paths rather than running `git add .`?**
>
> > [!TIP]
> > **Answer:** To prevent accidental exposure of sensitive environment variables (`.env`), system files (`.DS_Store`), or local build artifacts that might not be covered in `.gitignore`.

> **2. How does Claude Code determine the appropriate style for commit messages?**
>
> > [!TIP]
> > **Answer:** The agent automatically inspects recent repository commits via `git log`, aligning its output with established project conventions (Conventional Commits, Jira ticket IDs, or concise lowercase descriptions).

> **3. What happens if a pre-commit hook (Husky/ESLint) fails during a commit orchestrated by Claude?**
>
> > [!TIP]
> > **Answer:** Claude will not bypass the check with `--no-verify`. Instead, it reads the linter/test error log, fixes the offending code, and re-executes the commit safely.

### Daily Git with Claude Code Checklist

- [ ] Use `Commit these changes` instead of manual `status -> add -> commit` chains.
- [ ] Combine branch creation with feature prompts to maintain uninterrupted development context.
- [ ] Let Claude analyze and resolve complex merge conflicts after `rebase` or `merge`.
- [ ] Leverage `git stash` via Claude whenever you need to jump to an urgent task.
- [ ] Install `gh CLI` so Claude can draft complete, formatted Pull Request descriptions.
- [ ] Keep safety guardrails active: review final diffs before pushing to shared remotes.