git-rebase
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGit Rebase with Intelligent Conflict Resolution
Git Rebase 智能冲突解决
Quick Start
快速开始
For most rebases with multiple commits, use the squash-first strategy to resolve conflicts only once:
bash
undefined对于涉及多个提交的大多数变基场景,优先使用先压缩(squash)的策略,只需解决一次冲突即可:
bash
undefinedStep 1: Backup current state
Step 1: Backup current state
bash scripts/pre-rebase-backup.sh
bash scripts/pre-rebase-backup.sh
Step 2: Squash commits (interactive rebase on current branch)
Step 2: Squash commits (interactive rebase on current branch)
git rebase -i $(git merge-base HEAD origin/main)
git rebase -i $(git merge-base HEAD origin/main)
Step 3: Rebase onto target
Step 3: Rebase onto target
git rebase origin/main
git rebase origin/main
Step 4: If conflicts, resolve them once (see workflow below)
Step 4: If conflicts, resolve them once (see workflow below)
Then continue: git rebase --continue
Then continue: git rebase --continue
Step 5: Force push safely
Step 5: Force push safely
git push origin $(git rev-parse --abbrev-ref HEAD) --force-with-lease
This approach resolves conflicts once instead of per-commit, saving time and mental overhead.git push origin $(git rev-parse --abbrev-ref HEAD) --force-with-lease
这种方法只需一次性解决冲突,无需逐个提交处理,能够节省时间和精力成本。Core Workflow: Conflict Analysis & Resolution
核心工作流:冲突分析与解决
Copy this checklist and mark progress:
Rebase Workflow:
- [ ] Step 1: Create safety backup
- [ ] Step 2: Fetch latest from target branch
- [ ] Step 3: Analyze conflict scope
- [ ] Step 4: Choose resolution strategy
- [ ] Step 5: Apply conflict resolutions
- [ ] Step 6: Validate merged code
- [ ] Step 7: Run tests
- [ ] Step 8: Force push safely复制以下检查清单,标记进度:
Rebase Workflow:
- [ ] Step 1: Create safety backup
- [ ] Step 2: Fetch latest from target branch
- [ ] Step 3: Analyze conflict scope
- [ ] Step 4: Choose resolution strategy
- [ ] Step 5: Apply conflict resolutions
- [ ] Step 6: Validate merged code
- [ ] Step 7: Run tests
- [ ] Step 8: Force push safelyStep 1: Create Safety Backup
步骤1:创建安全备份
ALWAYS do this first. If rebase goes wrong, you can recover:
bash
undefined务必首先执行此操作。如果变基过程出错,你可以通过备份恢复:
bash
undefinedUse the bundled script
Use the bundled script
bash scripts/pre-rebase-backup.sh
bash scripts/pre-rebase-backup.sh
Or manually create timestamped backup branch
Or manually create timestamped backup branch
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
git branch backup-rebase-$TIMESTAMP
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
git branch backup-rebase-$TIMESTAMP
Alternative: Create temporary ref to your current commit
Alternative: Create temporary ref to your current commit
git reflog # Note your current HEAD SHA for manual recovery
This costs nothing and saves hours of work if something goes wrong.git reflog # Note your current HEAD SHA for manual recovery
这个操作没有任何成本,但如果出现问题可以为你节省数小时的工作时间。Step 2: Fetch Latest Changes
步骤2:拉取最新变更
Ensure you have the most recent remote state:
bash
undefined确保你拥有最新的远程分支状态:
bash
undefinedFetch without modifying local branches
Fetch without modifying local branches
git fetch origin
git fetch origin
View the divergence
View the divergence
git log --oneline origin/main..HEAD # Your commits
git log --oneline HEAD..origin/main # New commits on main
Understand how many commits you're rebasing and how much main has changed.git log --oneline origin/main..HEAD # Your commits
git log --oneline HEAD..origin/main # New commits on main
明确你要变基的提交数量,以及main分支有多少新变更。Step 3: Analyze Conflict Scope
步骤3:分析冲突范围
Before starting the rebase, predict conflicts:
bash
undefined在开始变基前,预判可能出现的冲突:
bash
undefinedSee which files you changed
See which files you changed
git diff --name-only origin/main...HEAD
git diff --name-only origin/main...HEAD
See which files main changed
See which files main changed
git diff --name-only origin/main HEAD
git diff --name-only origin/main HEAD
Likely conflict areas: files changed in both
Likely conflict areas: files changed in both
**Key insight**: If you changed `auth.ts` and so did main, you WILL get conflicts in `auth.ts`.
Anticipating conflicts helps you understand how to resolve them.
**核心要点**:如果你修改了`auth.ts`,同时main分支也修改了这个文件,那么`auth.ts`一定会出现冲突。
提前预判冲突可以帮助你更好地制定解决策略。Step 4: Choose Resolution Strategy
步骤4:选择解决策略
For detailed strategy comparison and decision matrix, see references/strategies.md.
如需查看详细的策略对比和决策矩阵,请参阅references/strategies.md。
Strategy A: Squash First (Recommended for 3+ commits)
策略A:优先压缩(推荐提交数≥3的场景使用)
When to use: Multiple feature commits with many conflicts expected
Why: Reduces conflicts to one resolution phase instead of per-commit
bash
undefined适用场景:多个功能提交,预期会出现大量冲突
优势:只需一次冲突解决阶段,无需逐个提交处理冲突
bash
undefinedInteractive rebase on current branch first
Interactive rebase on current branch first
git rebase -i $(git merge-base HEAD origin/main)
git rebase -i $(git merge-base HEAD origin/main)
In editor, change all "pick" to "squash" (or 's') except first commit
In editor, change all "pick" to "squash" (or 's') except first commit
Save and exit - commits are squashed into one
Save and exit - commits are squashed into one
Edit commit message to describe the entire feature
Edit commit message to describe the entire feature
Now rebase the squashed commit
Now rebase the squashed commit
git rebase origin/main
git rebase origin/main
Resolve conflicts once, then git rebase --continue
Resolve conflicts once, then git rebase --continue
**Tradeoffs**: Lose individual commit history, but simpler conflict resolution
**权衡**:会丢失单独的提交历史,但冲突解决过程更简单Strategy B: Interactive Rebase with Conflict Awareness
策略B:带冲突感知的交互式变基
When to use: 1-2 commits, clean history, or complex per-commit logic
bash
git rebase -i origin/main适用场景:1-2个提交、提交历史干净,或者每个提交包含复杂的独立逻辑
bash
git rebase -i origin/mainIn editor, you can:
In editor, you can:
- Reorder commits to isolate conflict-prone ones
- Reorder commits to isolate conflict-prone ones
- Drop commits that are already in main (git detects this)
- Drop commits that are already in main (git detects this)
- Combine related commits before rebasing
- Combine related commits before rebasing
Save and exit - rebase proceeds, stopping at conflicts
Save and exit - rebase proceeds, stopping at conflicts
**Tradeoffs**: More control, but more conflict-resolution iterations
**权衡**:可控性更高,但需要多次处理冲突Strategy C: Simple Linear Rebase (Fastest, Auto-Resolution)
策略C:简单线性变基(最快,自动解决)
When to use: Simple cases, no critical decisions, or in automated pipelines
bash
undefined适用场景:简单场景、无需复杂决策,或者在自动化流水线中使用
bash
undefinedRebase all commits at once
Rebase all commits at once
git rebase origin/main
git rebase origin/main
If no conflicts, done
If no conflicts, done
If conflicts, you resolve each one
If conflicts, you resolve each one
**Warning**: Not recommended for complex scenarios. Use Strategies A or B instead.
**警告**:不推荐用于复杂场景,请优先使用策略A或B。Step 5: Apply Conflict Resolutions
步骤5:执行冲突解决
When pauses with conflicts, use the analysis script:
git rebasebash
undefined当因冲突暂停时,使用分析脚本:
git rebasebash
undefinedAnalyze conflicts
Analyze conflicts
bash scripts/analyze-conflicts.sh
bash scripts/analyze-conflicts.sh
See which files conflict
See which files conflict
git status
git status
For each conflicted file:
For each conflicted file:
- RECOMMENDED: Use merge tool for visual clarity
- RECOMMENDED: Use merge tool for visual clarity
git mergetool --no-prompt
git mergetool --no-prompt
- ALTERNATIVE: Manual edit in your editor
- ALTERNATIVE: Manual edit in your editor
Search for conflict markers: <<<<<<, ======, >>>>>>
Search for conflict markers: <<<<<<, ======, >>>>>>
undefinedundefinedConflict Marker Anatomy
冲突标记结构
javascript
<<<<<<< HEAD
// Your current feature code
function authenticate(token) {
validateToken(token);
return true;
}
=======
// Main branch code (incoming)
function authenticate(token) {
if (!token) throw new Error("No token");
validateToken(token);
setSession(token);
return true;
}
>>>>>>> origin/mainDecision framework (before deleting markers):
-
Can you keep both? YES → Merge them intelligentlyjavascript
function authenticate(token) { if (!token) throw new Error("No token"); // Keep main's validation validateToken(token); setSession(token); // Keep main's session setup return true; // Keep feature's return } -
Conflicting logic? Understand WHY they differ, then decide
- Did main add critical security checks? → Keep main's version
- Did your feature add essential functionality? → Keep feature's version
- Are they trying to do different things? → Combine intentionally
-
Lost features? NEVER let a feature silently disappear
- If you added authentication logic, ensure it's in final version
- If main improved database access, ensure that's preserved
For detailed resolution patterns, see references/resolution-patterns.md.
javascript
<<<<<<< HEAD
// Your current feature code
function authenticate(token) {
validateToken(token);
return true;
}
=======
// Main branch code (incoming)
function authenticate(token) {
if (!token) throw new Error("No token");
validateToken(token);
setSession(token);
return true;
}
>>>>>>> origin/main决策框架(删除冲突标记前):
-
是否可以同时保留两个版本的逻辑? 是 → 智能合并两者javascript
function authenticate(token) { if (!token) throw new Error("No token"); // Keep main's validation validateToken(token); setSession(token); // Keep main's session setup return true; // Keep feature's return } -
逻辑存在冲突? 先理解两者产生差异的原因,再做决策
- main分支是否新增了关键的安全检查?→ 保留main分支的版本
- 你的功能分支是否新增了核心功能?→ 保留功能分支的版本
- 两者是否要实现不同的功能?→ 针对性合并
-
功能丢失? 绝对不要让功能被静默删除
- 如果你新增了认证逻辑,确保它存在于最终版本中
- 如果main分支优化了数据库访问,确保这部分改动被保留
如需查看详细的解决模式,请参阅references/resolution-patterns.md。
Key Resolution Principles
核心解决原则
✅ DO:
- Keep both versions' important functionality when possible
- Use the merge tool for visual representation
- Add comments explaining merged conflicts:
// Merged from both versions: main's validation + feature's session setup - Test each file after resolution
❌ DON'T:
- Mindlessly pick one version without understanding both
- Delete conflict markers without understanding the conflict
- Keep duplicate code - merge intelligently
- Skip testing before continuing
✅ 推荐操作:
- 尽可能保留两个版本的重要功能
- 使用合并工具获得可视化的冲突展示
- 添加注释说明合并逻辑:
// 合并两个版本:main分支的校验 + 功能分支的会话设置 - 每个文件解决冲突后都进行测试
❌ 禁止操作:
- 不理解两个版本的逻辑就随意选择其中一个
- 不理解冲突原因就直接删除冲突标记
- 保留重复代码,要进行智能合并
- 继续变基前跳过测试
Step 6: Validate Merged Code
步骤6:验证合并后的代码
After resolving conflicts, validate the merged code:
bash
undefined解决冲突后,验证合并后的代码:
bash
undefinedUse the validation script
Use the validation script
bash scripts/validate-merge.sh
bash scripts/validate-merge.sh
Manual checks:
Manual checks:
1. Check syntax
1. Check syntax
npm run lint # or eslint, pylint, etc.
npm run lint # or eslint, pylint, etc.
2. Check types (if TypeScript)
2. Check types (if TypeScript)
npm run type-check # or tsc --noEmit
npm run type-check # or tsc --noEmit
3. Spot-check key files
3. Spot-check key files
git diff HEAD origin/main -- <conflicted-file>
git diff HEAD origin/main -- <conflicted-file>
If validation fails:
If validation fails:
1. Fix the issue in the file
1. Fix the issue in the file
2. git add <file>
2. git add <file>
3. git rebase --continue
3. git rebase --continue
**Important**: Validation catches mistakes BEFORE you commit them.
**重要提示**:验证可以在提交前捕获错误。Step 7: Run Tests
步骤7:运行测试
This is your safety net:
bash
undefined这是你的安全网:
bash
undefinedRun full test suite
Run full test suite
npm test
npm test
Or specific tests for changed areas
Or specific tests for changed areas
npm test -- --testPathPattern=auth # If auth.ts was changed
npm test -- --testPathPattern=auth # If auth.ts was changed
If tests fail:
If tests fail:
1. Understand what broke
1. Understand what broke
2. Fix in the files
2. Fix in the files
3. git add <files>
3. git add <files>
4. git rebase --continue
4. git rebase --continue
**Rule**: Never force-push code that fails tests.
**规则**:永远不要强制推送测试不通过的代码。Step 8: Force Push Safely
步骤8:安全强制推送
Use instead of . It protects against accidentally overwriting others' work:
--force-with-lease--forcebash
undefined使用替代,可以避免意外覆盖他人的提交:
--force-with-lease--forcebash
undefinedSAFE: Protects others' commits
SAFE: Protects others' commits
git push origin $(git rev-parse --abbrev-ref HEAD) --force-with-lease
git push origin $(git rev-parse --abbrev-ref HEAD) --force-with-lease
UNSAFE: Can overwrite others' work
UNSAFE: Can overwrite others' work
git push origin your-branch -f # Don't do this
git push origin your-branch -f # Don't do this
If force-with-lease fails:
If force-with-lease fails:
Someone else pushed to your branch
Someone else pushed to your branch
Coordinate with them before forcing
Coordinate with them before forcing
undefinedundefinedCommon Scenarios & Strategies
常见场景与策略
Scenario 1: Many Small Conflicts Across 5+ Commits
场景1:跨5个以上提交存在大量小型冲突
Use: Squash-first strategy
bash
git rebase -i $(git merge-base HEAD origin/main)使用:优先压缩策略
bash
git rebase -i $(git merge-base HEAD origin/main)Mark all but first commit as 's' (squash)
Mark all but first commit as 's' (squash)
Save - commits squash into one
Save - commits squash into one
git rebase origin/main
git rebase origin/main
Resolve conflicts once
Resolve conflicts once
git rebase --continue
git rebase --continue
Only one conflict-resolution phase!
Only one conflict-resolution phase!
**Why**: Each commit might have conflicts. Squashing before rebasing means one pass.
**原因**:每个提交都可能产生冲突,变基前先压缩只需处理一次冲突。Scenario 2: One Specific Commit Has Conflicts
场景2:某个特定提交存在冲突
Use: Target that commit with interactive rebase
bash
git rebase -i origin/main使用:通过交互式变基定位该提交
bash
git rebase -i origin/mainIn editor, move the problematic commit to the end
In editor, move the problematic commit to the end
Save - rebase proceeds, stopping at that commit
Save - rebase proceeds, stopping at that commit
When it stops, you know exactly which commit conflicts
When it stops, you know exactly which commit conflicts
git status # See what changed in this commit
git status # See what changed in this commit
Resolve, then continue
Resolve, then continue
git rebase --continue
**Why**: Isolating the commit helps you understand what it's trying to do.git rebase --continue
**原因**:隔离冲突提交可以帮助你理解该提交要实现的功能。Scenario 3: Conflicts Keep Repeating (Same File, Different Commits)
场景3:冲突重复出现(同一个文件,不同提交)
Use: Git rerere (reuse recorded resolution)
bash
undefined使用:Git rerere(复用已记录的解决策略)
bash
undefinedEnable rerere globally (one-time setup)
Enable rerere globally (one-time setup)
git config --global rerere.enabled true
git config --global rerere.enabled true
Now when you hit the same conflict in a second commit,
Now when you hit the same conflict in a second commit,
Git automatically applies the first commit's resolution
Git automatically applies the first commit's resolution
git rebase origin/main
git rebase origin/main
Git remembers your first conflict resolution
Git remembers your first conflict resolution
and replays it automatically for similar conflicts
and replays it automatically for similar conflicts
**Why**: When rebasing and hitting the same file repeatedly, rerere saves manual work.
**原因**:当变基过程中反复遇到同一个文件的冲突时,rerere可以节省手动处理的工作量。Scenario 4: Rebase Conflicts Are Too Complex
场景4:变基冲突过于复杂
Emergency escape plan:
bash
undefined紧急退出方案:
bash
undefinedAbort the rebase - return to original state
Abort the rebase - return to original state
git rebase --abort
git rebase --abort
Fall back to merge (safer for complex scenarios)
Fall back to merge (safer for complex scenarios)
git merge origin/main
git merge origin/main
Or try a different approach:
Or try a different approach:
- Squash your entire feature branch first
- Squash your entire feature branch first
- Cherry-pick main's critical changes selectively
- Cherry-pick main's critical changes selectively
**Important**: It's okay to abort and rethink. Better than a broken rebase.
**重要提示**:可以中止变基后重新思考方案,这比产生一个损坏的变基结果要好。Bundled Scripts
内置脚本
This skill includes helper scripts in :
scripts/- : Creates a safety backup before rebasing
pre-rebase-backup.sh - : Analyzes current conflicts and provides detailed information
analyze-conflicts.sh - : Validates that merge/rebase is clean and ready for testing
validate-merge.sh
Run scripts with .
bash scripts/<script-name>.sh本技能在目录下包含辅助脚本:
scripts/- :变基前创建安全备份
pre-rebase-backup.sh - :分析当前冲突并提供详细信息
analyze-conflicts.sh - :验证合并/变基结果干净,可进入测试阶段
validate-merge.sh
使用运行脚本。
bash scripts/<脚本名称>.shReference Files
参考文件
For detailed information on specific topics:
- Strategies: references/strategies.md - Complete strategy comparison and decision matrix
- Resolution Patterns: references/resolution-patterns.md - Common conflict resolution patterns and heuristics
- Troubleshooting: references/troubleshooting.md - Solutions to common rebase problems
- Automation: references/automation.md - Automated conflict resolution for CI/CD
- Scripts & Tools: references/scripts-tools.md - Additional git commands and tool usage
如需查看特定主题的详细信息:
- 策略:references/strategies.md - 完整的策略对比和决策矩阵
- 解决模式:references/resolution-patterns.md - 常见冲突解决模式和启发式规则
- 问题排查:references/troubleshooting.md - 常见变基问题的解决方案
- 自动化:references/automation.md - 适用于CI/CD的自动冲突解决
- 脚本与工具:references/scripts-tools.md - 额外的git命令和工具使用方法
Checklist: Before You Commit to Rebasing
检查清单:变基前确认
- Understand why you're rebasing (cleaner history, syncing with main, etc.)
- Backup your current branch:
bash scripts/pre-rebase-backup.sh - Run tests on current branch - they should pass
- Fetch latest:
git fetch origin - Understand what you'll be rebasing (5 commits? 50?)
- Understand main's recent changes (1 commit? Major refactor?)
- Choose your strategy (see references/strategies.md)
- Have your merge tool ready (if using GUI)
- Block 30 mins - don't rush conflict resolution
- Have tests ready to run after rebase
- 明确你进行变基的原因(更干净的历史、与main分支同步等)
- 备份当前分支:
bash scripts/pre-rebase-backup.sh - 在当前分支运行测试,确保测试全部通过
- 拉取最新变更:
git fetch origin - 明确你要变基的提交数量(5个?50个?)
- 了解main分支的近期变更(1个提交?大规模重构?)
- 选择你的变基策略(参阅references/strategies.md)
- 准备好你的合并工具(如果使用GUI工具)
- 预留30分钟时间,不要急于处理冲突
- 准备好变基后要运行的测试用例
When NOT to Rebase
不适合使用变基的场景
- Shared branches (use merge instead: )
git merge origin/main - Critical production code without comprehensive tests
- When multiple people are pushing to the same branch
- If you don't understand the conflicts you're seeing
Default to merge if uncertain. Merge is safer for collaborative work.
Use rebase when: Solo feature branch, clean history matters, no shared dependencies.
- 共享分支(请使用merge:)
git merge origin/main - 没有完善测试覆盖的关键生产代码
- 多个人正在向同一个分支推送提交
- 你无法理解遇到的冲突原因
不确定时优先使用merge。对于协作场景,merge更安全。
适合使用变基的场景:个人功能分支、需要干净的提交历史、没有共享依赖。
Summary: The Rebase Philosophy
总结:变基理念
Rebasing is a tool for creating clean, linear commit history. Used well, it makes debugging and code review easier. Used poorly, it loses work.
The key principle: Understand every conflict before resolving it. Don't automate away the thinking.
With this Skill, you can rebase with confidence, understanding each decision and protecting your code throughout the process.
变基是用于创建干净线性提交历史的工具。使用得当,它可以让调试和代码评审更简单。使用不当,会导致代码丢失。
核心原则:解决每个冲突前都要理解冲突原因,不要用自动化代替思考。
使用本技能,你可以自信地进行变基操作,理解每一个决策,在整个过程中保护你的代码。