Claude Code Git 工作流实战: 干净分支、小提交、CI 与团队交接
面向 Claude Code 的 Git 实战流程: 分支、提交、rebase、CI、回滚和团队交接。
Claude Code 能很快写出代码,也能很快制造一个难以审查的 diff。真正的问题通常不是“代码能不能生成”,而是分支是否干净、哪些文件被放进下一次提交、冲突是否按业务意图解决、push 前有没有跑检查、第二天别人能不能接手。
这篇文章给出一套适合个人开发和团队开发的 Claude Code Git 工作流。我们会用初学者能理解的话解释 staging、commit、rebase,并给出可直接复制的命令、CLAUDE.md 规则、pre-commit、GitHub Actions、冲突处理、安全回滚和 daily handoff 模板。
建议搭配阅读: Claude Code Git 冲突解决、GitHub Actions 进阶、review workflow checklist。官方文档可以看 Claude Code hooks、Claude Code headless mode、Git user manual、Git rebase、GitHub Actions workflow syntax 和 pre-commit。
先把 Git 概念讲清楚
working tree 是你当前正在编辑的工作区,Claude Code 修改文件也发生在这里。staging area 可以理解成“下一次 commit 的购物篮”。git add 不是永久保存,而是把某些改动放进这个购物篮。
commit 是给购物篮里的改动拍一张快照,并留下说明。好的 commit 应该小到 reviewer 能一次读懂。rebase 是把你分支上的 commit 重新放到最新 main 之后,让历史更直;但如果这个分支已经被别人使用,随便 rebase 会改写共享历史。
Claude Code 不应该只负责写代码。更稳的做法是让它读 diff、提出应该 stage 的文件、生成 commit message、解释冲突两边的意图、运行本地检查,并在结束时留下 handoff。
flowchart LR
A["写清目标"] --> B["更新 main 并建分支"]
B --> C["让 Claude Code 做小步修改"]
C --> D["读 diff 并选择 staging"]
D --> E["review gate 与本地 CI"]
E --> F["小提交"]
F --> G["rebase 或开 PR"]
G --> H["留下 handoff 与 rollback"]
干净分支循环
每次开始前先确认工作区。这里的“干净”不一定是没有任何改动,而是没有和当前任务无关的改动混在一起。
git status --short
git fetch origin
git switch main
git pull --ff-only origin main
git switch -c feature/checkout-coupon-validation
git status --short
如果你在 Windows PowerShell 下工作,可以用日期避免多个 AI session 的分支名冲突。
$topic = "checkout-coupon-validation"
$date = Get-Date -Format "yyyyMMdd"
git fetch origin
git switch main
git pull --ff-only origin main
git switch -c "feature/$date-$topic"
git status --short
给 Claude Code 的第一条 prompt 应该先限制范围。
Goal: add coupon expiry validation to checkout.
Scope: edit only src/checkout, src/coupons, and matching tests.
Do not stage, commit, push, or edit unrelated files.
Before editing, read package.json and existing checkout tests.
After editing, show git diff --stat and the exact test commands you ran.
Masa 在维护 ClaudeCodeLab 内容时踩过一个很现实的坑: 本来只想改一篇文章,结果生成脚本、商品页草稿和本地报告也混进了 diff。模型并不是故意破坏,而是任务边界不够硬。把“不要碰什么”写清楚,review 时间会明显缩短。
staging 与小提交
git add -A 对人类很方便,但对 AI 辅助开发太宽。它可能把临时文件、本地配置、另一个任务的半成品一起放进 staging。
git diff --stat
git diff
git add src/checkout/validateCoupon.ts
git add tests/checkout/validateCoupon.test.ts
git diff --staged --stat
git diff --staged
commit message 建议使用 Conventional Commits 风格,方便以后搜索。
git commit -m "feat(checkout): validate coupon expiry before payment"
如果影响用户或内容导线,写上 body。
git commit -m "fix(content): keep Claude Code Git workflow CTA localized" -m "Updates the localized article body, internal links, and review checklist so translated pages follow the same Git workflow."
可以让 Claude Code 只生成 message,不让它提交。
Read only the staged diff.
Propose one Conventional Commits message.
Do not run git commit.
Mention the user impact in the body if the change affects readers or customers.
把 Git 规则写进 CLAUDE.md
CLAUDE.md 是给 Claude Code 看的项目操作说明。它不是面向用户的 README,而是告诉 AI 在这个仓库里应该怎样工作。
# Claude Code Git rules
- Start every coding task with `git status --short` and report unrelated dirty files.
- Do not run `git add -A`, `git commit`, `git push`, `git reset --hard`, or `git clean -fd` unless the user explicitly asks.
- Keep commits small: one behavior change, one test update, or one content slug at a time.
- Before proposing a commit, show `git diff --stat` and `git diff --staged --stat`.
- If a conflict appears, explain both sides before editing the conflicted file.
- Run the closest local checks before push: lint, typecheck, test, build, or article metadata checks.
- Leave a handoff note with changed files, commands run, failing checks, and rollback option.
团队可以再加一个 Claude Code hook。hook 是在工具调用前后自动执行的命令。下面的例子会拦截危险 Git 命令。
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(git *)",
"command": "node .claude/hooks/block-dangerous-git.mjs"
}
]
}
]
}
}
// .claude/hooks/block-dangerous-git.mjs
import process from "node:process";
let raw = "";
for await (const chunk of process.stdin) raw += chunk;
const input = JSON.parse(raw || "{}");
const command = input.tool_input?.command ?? "";
const blocked = [
/git\s+reset\s+--hard\b/,
/git\s+clean\s+-[^\s]*f/,
/git\s+push\s+--force(?!-with-lease)/,
/git\s+checkout\s+--\s+\./,
/git\s+restore\s+\.\b/
];
if (blocked.some((pattern) => pattern.test(command))) {
process.stderr.write(`Blocked risky Git command: ${command}\n`);
process.exit(2);
}
hook 不是万能安全系统。人类可以绕过它,其他终端也可以直接执行命令。但它能防止 Claude Code 在上下文不清楚时执行高风险操作。
push 前先跑本地 CI
不要等 push 后才让远端 CI 报错。先给项目一个本地 preflight。
// scripts/claude-git-preflight.mjs
import { execSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
const run = (command) => {
console.log(`\n$ ${command}`);
execSync(command, { stdio: "inherit", shell: true });
};
run("git diff --check");
run("git diff --cached --check");
run("git status --short");
const pkg = existsSync("package.json")
? JSON.parse(readFileSync("package.json", "utf8"))
: { scripts: {} };
for (const script of ["lint", "typecheck", "test", "build"]) {
if (pkg.scripts?.[script]) run(`npm run ${script}`);
}
node scripts/claude-git-preflight.mjs
给 Claude Code 的检查指令也要明确。
After implementation, run the local preflight.
If a command fails, stop and explain the first failing command, likely cause, and smallest next fix.
Do not push until the preflight is green.
pre-commit 与 GitHub Actions
pre-commit 可以在 commit 前运行检查,让人和 Claude Code 都经过同一套门槛。
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: git-diff-check
name: git diff whitespace check
entry: git diff --check
language: system
pass_filenames: false
- id: npm-test
name: npm test when available
entry: node scripts/claude-git-preflight.mjs
language: system
pass_filenames: false
python -m pip install pre-commit
pre-commit install
pre-commit run --all-files
PR 上再用 GitHub Actions 复跑关键检查。
# .github/workflows/claude-code-pr-gate.yml
name: Claude Code PR Gate
on:
pull_request:
branches: [main]
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: git diff --check origin/main...HEAD
- run: npm run lint --if-present
- run: npm run typecheck --if-present
- run: npm test --if-present
- run: npm run build --if-present
冲突、rebase 与安全回滚
冲突不是简单的文本问题,而是两个分支的意图发生了碰撞。先让 Claude Code 解释双方改了什么,再解决。
git fetch origin
git rebase origin/main
git status --short
git diff --name-only --diff-filter=U
We are in a rebase conflict.
For each conflicted file, explain what our branch changed and what origin/main changed.
Resolve only after explaining the business intent.
After editing, run the narrowest relevant test.
Do not continue the rebase until I approve the resolved diff.
git add src/checkout/validateCoupon.ts
npm test -- --runInBand validateCoupon
git rebase --continue
如果方向不对,先停止。
git rebase --abort
共享出去的改动要回滚时,优先用 git revert,因为它会留下新的“撤销提交”。
git log --oneline -5
git revert --no-edit HEAD
git status --short
未提交的文件则精确恢复路径。
git restore --staged src/checkout/validateCoupon.ts
git restore src/checkout/validateCoupon.ts
具体使用场景与失败模式
个人功能开发: 新建 feature/yyyyMMdd-topic,只让 Claude Code 修改目标文件和测试,commit 只包含一个行为变化,push 前跑 preflight。
团队 PR: 实现 session 不提交,review session 只看 staged diff,人类最后确认 PR title、CI、风险和 rollback。这样可以防止 AI 的速度直接变成 main 分支风险。
内容和商品页更新: ClaudeCodeLab 的文章、Gumroad 链接、培训 CTA 和内部链接会影响收入。按 slug 和 locale 建分支,检查 description 长度、hero、CTA、乱码和本地化正文。
长期重构: 先加测试,再改内部实现,最后删除旧代码。不要让 Claude Code 在一个 commit 里完成所有迁移。
| 失败 | 原因 | 预防 |
|---|---|---|
git add -A 混入无关文件 | AI 修改范围比任务大 | 读 git diff --stat 后按路径 stage |
| commit 过大 | 实现、测试、配置、文案混在一起 | 一个 commit 只解决一个目的 |
| 冲突乱合并 | 没有理解双方意图 | 先解释 ours/theirs |
| rebase 后错误 push | 本地历史和远端不一致 | 只在团队规则下用 --force-with-lease |
| PR 一 push 就红 | 本地检查没跑 | 使用 preflight |
| 回滚破坏证据 | 使用 reset --hard | 共享提交优先 git revert |
每日交接
handoff 不需要像日报一样长,只要让明天的自己或 reviewer 能继续。
## Handoff: 2026-06-02
Branch: feature/20260602-checkout-coupon-validation
Goal: validate coupon expiry before payment authorization
Changed:
- src/checkout/validateCoupon.ts
- tests/checkout/validateCoupon.test.ts
Checks:
- npm run lint: passed
- npm test -- --runInBand validateCoupon: passed
- npm run build: not run, no UI/build config touched
Risk:
- Coupon timezone boundary still needs one integration test.
Rollback:
- Revert commit `abc1234` if production checkout rejects valid coupons.
下一步
如果你是个人开发者,可以先从免费 Claude Code cheatsheet开始,把日常 Git 检查命令放在手边。需要可复用 prompt、CLAUDE.md、review 模板时,可以看ClaudeCodeLab 产品与模板。
团队导入时,真正要设计的是分支命名、commit 粒度、CI、权限、review owner、rollback 和 handoff。需要把这些落到真实仓库上时,可以通过Claude Code 培训与导入咨询一起整理。
实际试用结果
ClaudeCodeLab 用这套流程更新文章后,review 从“重新读完整文章”变成了“检查 slug、locale、metadata、CTA 和 diff 范围”。git diff --staged --stat 与 handoff 最有价值,因为它们能证明哪些内容真的被检查过。Claude Code 的价值不只是写得快,而是把下一位接手者需要的证据留下来。
免费 PDF: Claude Code 速查表
输入邮箱即可获取一页 PDF,整理常用命令、审查习惯和安全工作流。
我们会妥善保护你的信息,不发送垃圾邮件。
把 Claude Code 变成真正能带来结果的工作流
先领取中文说明的免费 PDF,再进入英文商品页选择合适的教材。如果你需要团队落地、流程设计或内容变现支持,也可以直接咨询。
关于作者
Masa
专注 Claude Code 实务流程、团队导入和内容转化的工程师。
相关文章
Claude Code权限安全阶梯:逐步放开访问而不失控
从只读到有限编辑、验证命令和部署检查的 Claude Code 权限升级流程。
Claude Code 小PR证据包:让小改动真正可审查
用差异、验证命令、公开URL、CTA路径和回滚说明,把Claude Code的小PR变得可审查。
Claude Code 提交前 Review Gate:同时检查差异、测试、公开 URL 和 CTA
提交前用 Claude Code 审查差异范围、build、公开 URL、Gumroad 链接、咨询 CTA、缺少测试和无关文件。