git-advanced-workflows

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Advanced Workflows

Git 高级工作流

Master advanced Git techniques to maintain clean history, collaborate effectively, and recover from any situation with confidence.
掌握高级Git技术,自信地维护清晰的提交历史、高效协作并从任何状况中恢复。

When to Use This Skill

何时使用此技能

  • Cleaning up commit history before merging
  • Applying specific commits across branches
  • Finding commits that introduced bugs
  • Working on multiple features simultaneously
  • Recovering from Git mistakes or lost commits
  • Managing complex branch workflows
  • Preparing clean PRs for review
  • Synchronizing diverged branches
  • 合并前清理提交历史
  • 在分支间应用特定提交
  • 定位引入Bug的提交
  • 同时开发多个功能
  • 从Git错误或丢失的提交中恢复
  • 管理复杂的分支工作流
  • 准备用于评审的整洁PR
  • 同步分歧的分支

Core Concepts

核心概念

1. Interactive Rebase

1. Interactive Rebase

Interactive rebase is the Swiss Army knife of Git history editing.
Common Operations:
  • pick
    : Keep commit as-is
  • reword
    : Change commit message
  • edit
    : Amend commit content
  • squash
    : Combine with previous commit
  • fixup
    : Like squash but discard message
  • drop
    : Remove commit entirely
Basic Usage:
bash
undefined
Interactive Rebase是Git历史编辑的万能工具。
常见操作:
  • pick
    : 保留提交原样
  • reword
    : 修改提交信息
  • edit
    : 修改提交内容
  • squash
    : 与上一个提交合并
  • fixup
    : 类似squash,但丢弃提交信息
  • drop
    : 完全移除提交
基本用法:
bash
undefined

Rebase last 5 commits

Rebase last 5 commits

git rebase -i HEAD~5
git rebase -i HEAD~5

Rebase all commits on current branch

Rebase all commits on current branch

git rebase -i $(git merge-base HEAD main)
git rebase -i $(git merge-base HEAD main)

Rebase onto specific commit

Rebase onto specific commit

git rebase -i abc123
undefined
git rebase -i abc123
undefined

2. Cherry-Picking

2. Cherry-Picking

Apply specific commits from one branch to another without merging entire branches.
bash
undefined
无需合并整个分支,将特定提交从一个分支应用到另一个分支。
bash
undefined

Cherry-pick single commit

Cherry-pick single commit

git cherry-pick abc123
git cherry-pick abc123

Cherry-pick range of commits (exclusive start)

Cherry-pick range of commits (exclusive start)

git cherry-pick abc123..def456
git cherry-pick abc123..def456

Cherry-pick without committing (stage changes only)

Cherry-pick without committing (stage changes only)

git cherry-pick -n abc123
git cherry-pick -n abc123

Cherry-pick and edit commit message

Cherry-pick and edit commit message

git cherry-pick -e abc123
undefined
git cherry-pick -e abc123
undefined

3. Git Bisect

3. Git Bisect

Binary search through commit history to find the commit that introduced a bug.
bash
undefined
通过提交历史进行二分查找,定位引入Bug的提交。
bash
undefined

Start bisect

Start bisect

git bisect start
git bisect start

Mark current commit as bad

Mark current commit as bad

git bisect bad
git bisect bad

Mark known good commit

Mark known good commit

git bisect good v1.0.0
git bisect good v1.0.0

Git will checkout middle commit - test it

Git will checkout middle commit - test it

Then mark as good or bad

Then mark as good or bad

git bisect good # or: git bisect bad
git bisect good # or: git bisect bad

Continue until bug found

Continue until bug found

When done

When done

git bisect reset

**Automated Bisect:**

```bash
git bisect reset

**自动化二分查找:**

```bash

Use script to test automatically

Use script to test automatically

git bisect start HEAD v1.0.0 git bisect run ./test.sh
git bisect start HEAD v1.0.0 git bisect run ./test.sh

test.sh should exit 0 for good, 1-127 (except 125) for bad

test.sh should exit 0 for good, 1-127 (except 125) for bad

undefined
undefined

4. Worktrees

4. Worktrees

Work on multiple branches simultaneously without stashing or switching.
bash
undefined
无需暂存或切换分支,同时处理多个分支。
bash
undefined

List existing worktrees

List existing worktrees

git worktree list
git worktree list

Add new worktree for feature branch

Add new worktree for feature branch

git worktree add ../project-feature feature/new-feature
git worktree add ../project-feature feature/new-feature

Add worktree and create new branch

Add worktree and create new branch

git worktree add -b bugfix/urgent ../project-hotfix main
git worktree add -b bugfix/urgent ../project-hotfix main

Remove worktree

Remove worktree

git worktree remove ../project-feature
git worktree remove ../project-feature

Prune stale worktrees

Prune stale worktrees

git worktree prune
undefined
git worktree prune
undefined

5. Reflog

5. Reflog

Your safety net - tracks all ref movements, even deleted commits.
bash
undefined
你的安全网——跟踪所有引用的移动,包括已删除的提交。
bash
undefined

View reflog

View reflog

git reflog
git reflog

View reflog for specific branch

View reflog for specific branch

git reflog show feature/branch
git reflog show feature/branch

Restore deleted commit

Restore deleted commit

git reflog
git reflog

Find commit hash

Find commit hash

git checkout abc123 git branch recovered-branch
git checkout abc123 git branch recovered-branch

Restore deleted branch

Restore deleted branch

git reflog git branch deleted-branch abc123
undefined
git reflog git branch deleted-branch abc123
undefined

Practical Workflows

实用工作流

Workflow 1: Clean Up Feature Branch Before PR

工作流1:PR前清理功能分支

bash
undefined
bash
undefined

Start with feature branch

Start with feature branch

git checkout feature/user-auth
git checkout feature/user-auth

Interactive rebase to clean history

Interactive rebase to clean history

git rebase -i main
git rebase -i main

Example rebase operations:

Example rebase operations:

- Squash "fix typo" commits

- Squash "fix typo" commits

- Reword commit messages for clarity

- Reword commit messages for clarity

- Reorder commits logically

- Reorder commits logically

- Drop unnecessary commits

- Drop unnecessary commits

Force push cleaned branch (safe if no one else is using it)

Force push cleaned branch (safe if no one else is using it)

git push --force-with-lease origin feature/user-auth
undefined
git push --force-with-lease origin feature/user-auth
undefined

Workflow 2: Apply Hotfix to Multiple Releases

工作流2:将热修复应用到多个版本

bash
undefined
bash
undefined

Create fix on main

Create fix on main

git checkout main git commit -m "fix: critical security patch"
git checkout main git commit -m "fix: critical security patch"

Apply to release branches

Apply to release branches

git checkout release/2.0 git cherry-pick abc123
git checkout release/1.9 git cherry-pick abc123
git checkout release/2.0 git cherry-pick abc123
git checkout release/1.9 git cherry-pick abc123

Handle conflicts if they arise

Handle conflicts if they arise

git cherry-pick --continue
git cherry-pick --continue

or

or

git cherry-pick --abort
undefined
git cherry-pick --abort
undefined

Workflow 3: Find Bug Introduction

工作流3:定位Bug引入点

bash
undefined
bash
undefined

Start bisect

Start bisect

git bisect start git bisect bad HEAD git bisect good v2.1.0
git bisect start git bisect bad HEAD git bisect good v2.1.0

Git checks out middle commit - run tests

Git checks out middle commit - run tests

npm test
npm test

If tests fail

If tests fail

git bisect bad
git bisect bad

If tests pass

If tests pass

git bisect good
git bisect good

Git will automatically checkout next commit to test

Git will automatically checkout next commit to test

Repeat until bug found

Repeat until bug found

Automated version

Automated version

git bisect start HEAD v2.1.0 git bisect run npm test
undefined
git bisect start HEAD v2.1.0 git bisect run npm test
undefined

Workflow 4: Multi-Branch Development

工作流4:多分支开发

bash
undefined
bash
undefined

Main project directory

Main project directory

cd ~/projects/myapp
cd ~/projects/myapp

Create worktree for urgent bugfix

Create worktree for urgent bugfix

git worktree add ../myapp-hotfix hotfix/critical-bug
git worktree add ../myapp-hotfix hotfix/critical-bug

Work on hotfix in separate directory

Work on hotfix in separate directory

cd ../myapp-hotfix
cd ../myapp-hotfix

Make changes, commit

Make changes, commit

git commit -m "fix: resolve critical bug" git push origin hotfix/critical-bug
git commit -m "fix: resolve critical bug" git push origin hotfix/critical-bug

Return to main work without interruption

Return to main work without interruption

cd ~/projects/myapp git fetch origin git cherry-pick hotfix/critical-bug
cd ~/projects/myapp git fetch origin git cherry-pick hotfix/critical-bug

Clean up when done

Clean up when done

git worktree remove ../myapp-hotfix
undefined
git worktree remove ../myapp-hotfix
undefined

Workflow 5: Recover from Mistakes

工作流5:从错误中恢复

bash
undefined
bash
undefined

Accidentally reset to wrong commit

Accidentally reset to wrong commit

git reset --hard HEAD~5 # Oh no!
git reset --hard HEAD~5 # Oh no!

Use reflog to find lost commits

Use reflog to find lost commits

git reflog
git reflog

Output shows:

Output shows:

abc123 HEAD@{0}: reset: moving to HEAD~5

abc123 HEAD@{0}: reset: moving to HEAD~5

def456 HEAD@{1}: commit: my important changes

def456 HEAD@{1}: commit: my important changes

Recover lost commits

Recover lost commits

git reset --hard def456
git reset --hard def456

Or create branch from lost commit

Or create branch from lost commit

git branch recovery def456
undefined
git branch recovery def456
undefined

Advanced Techniques

高级技巧

Rebase vs Merge Strategy

变基与合并策略

When to Rebase:
  • Cleaning up local commits before pushing
  • Keeping feature branch up-to-date with main
  • Creating linear history for easier review
When to Merge:
  • Integrating completed features into main
  • Preserving exact history of collaboration
  • Public branches used by others
bash
undefined
何时使用变基:
  • 推送前清理本地提交
  • 保持功能分支与主分支同步
  • 创建线性历史以便于评审
何时使用合并:
  • 将完成的功能集成到主分支
  • 保留协作的完整历史
  • 供他人使用的公共分支
bash
undefined

Update feature branch with main changes (rebase)

Update feature branch with main changes (rebase)

git checkout feature/my-feature git fetch origin git rebase origin/main
git checkout feature/my-feature git fetch origin git rebase origin/main

Handle conflicts

Handle conflicts

git status
git status

Fix conflicts in files

Fix conflicts in files

git add . git rebase --continue
git add . git rebase --continue

Or merge instead

Or merge instead

git merge origin/main
undefined
git merge origin/main
undefined

Autosquash Workflow

自动合并修正提交工作流

Automatically squash fixup commits during rebase.
bash
undefined
在变基时自动合并fixup提交。
bash
undefined

Make initial commit

Make initial commit

git commit -m "feat: add user authentication"
git commit -m "feat: add user authentication"

Later, fix something in that commit

Later, fix something in that commit

Stage changes

Stage changes

git commit --fixup HEAD # or specify commit hash
git commit --fixup HEAD # or specify commit hash

Make more changes

Make more changes

git commit --fixup abc123
git commit --fixup abc123

Rebase with autosquash

Rebase with autosquash

git rebase -i --autosquash main
git rebase -i --autosquash main

Git automatically marks fixup commits

Git automatically marks fixup commits

undefined
undefined

Split Commit

拆分提交

Break one commit into multiple logical commits.
bash
undefined
将一个提交拆分为多个逻辑提交。
bash
undefined

Start interactive rebase

Start interactive rebase

git rebase -i HEAD~3
git rebase -i HEAD~3

Mark commit to split with 'edit'

Mark commit to split with 'edit'

Git will stop at that commit

Git will stop at that commit

Reset commit but keep changes

Reset commit but keep changes

git reset HEAD^
git reset HEAD^

Stage and commit in logical chunks

Stage and commit in logical chunks

git add file1.py git commit -m "feat: add validation"
git add file2.py git commit -m "feat: add error handling"
git add file1.py git commit -m "feat: add validation"
git add file2.py git commit -m "feat: add error handling"

Continue rebase

Continue rebase

git rebase --continue
undefined
git rebase --continue
undefined

Partial Cherry-Pick

部分拣选

Cherry-pick only specific files from a commit.
bash
undefined
仅从提交中拣选特定文件。
bash
undefined

Show files in commit

Show files in commit

git show --name-only abc123
git show --name-only abc123

Checkout specific files from commit

Checkout specific files from commit

git checkout abc123 -- path/to/file1.py path/to/file2.py
git checkout abc123 -- path/to/file1.py path/to/file2.py

Stage and commit

Stage and commit

git commit -m "cherry-pick: apply specific changes from abc123"
undefined
git commit -m "cherry-pick: apply specific changes from abc123"
undefined

Best Practices

最佳实践

  1. Always Use --force-with-lease: Safer than --force, prevents overwriting others' work
  2. Rebase Only Local Commits: Don't rebase commits that have been pushed and shared
  3. Descriptive Commit Messages: Future you will thank present you
  4. Atomic Commits: Each commit should be a single logical change
  5. Test Before Force Push: Ensure history rewrite didn't break anything
  6. Keep Reflog Aware: Remember reflog is your safety net for 90 days
  7. Branch Before Risky Operations: Create backup branch before complex rebases
bash
undefined
  1. 始终使用--force-with-lease:比--force更安全,防止覆盖他人的工作
  2. 仅对本地提交进行变基:不要对已推送并共享的提交进行变基
  3. 描述性提交信息:未来的你会感谢现在的你
  4. 原子提交:每个提交应对应一个独立的逻辑变更
  5. 强制推送前测试:确保历史重写没有破坏任何内容
  6. 牢记Reflog:记住Reflog是你的90天安全网
  7. 风险操作前创建分支:在复杂变基前创建备份分支
bash
undefined

Safe force push

Safe force push

git push --force-with-lease origin feature/branch
git push --force-with-lease origin feature/branch

Create backup before risky operation

Create backup before risky operation

git branch backup-branch git rebase -i main
git branch backup-branch git rebase -i main

If something goes wrong

If something goes wrong

git reset --hard backup-branch
undefined
git reset --hard backup-branch
undefined

Common Pitfalls

常见陷阱

  • Rebasing Public Branches: Causes history conflicts for collaborators
  • Force Pushing Without Lease: Can overwrite teammate's work
  • Losing Work in Rebase: Resolve conflicts carefully, test after rebase
  • Forgetting Worktree Cleanup: Orphaned worktrees consume disk space
  • Not Backing Up Before Experiment: Always create safety branch
  • Bisect on Dirty Working Directory: Commit or stash before bisecting
  • 对公共分支进行变基:会导致协作者的历史冲突
  • 不使用Lease进行强制推送:可能覆盖队友的工作
  • 变基中丢失工作:仔细解决冲突,变基后进行测试
  • 忘记清理Worktree:孤立的Worktree会占用磁盘空间
  • 实验前不备份:始终创建安全分支
  • 在脏工作目录中使用Bisect:进行Bisect前先提交或暂存

Recovery Commands

恢复命令

bash
undefined
bash
undefined

Abort operations in progress

Abort operations in progress

git rebase --abort git merge --abort git cherry-pick --abort git bisect reset
git rebase --abort git merge --abort git cherry-pick --abort git bisect reset

Restore file to version from specific commit

Restore file to version from specific commit

git restore --source=abc123 path/to/file
git restore --source=abc123 path/to/file

Undo last commit but keep changes

Undo last commit but keep changes

git reset --soft HEAD^
git reset --soft HEAD^

Undo last commit and discard changes

Undo last commit and discard changes

git reset --hard HEAD^
git reset --hard HEAD^

Recover deleted branch (within 90 days)

Recover deleted branch (within 90 days)

git reflog git branch recovered-branch abc123
undefined
git reflog git branch recovered-branch abc123
undefined

Resources

资源

  • references/git-rebase-guide.md: Deep dive into interactive rebase
  • references/git-conflict-resolution.md: Advanced conflict resolution strategies
  • references/git-history-rewriting.md: Safely rewriting Git history
  • assets/git-workflow-checklist.md: Pre-PR cleanup checklist
  • assets/git-aliases.md: Useful Git aliases for advanced workflows
  • scripts/git-clean-branches.sh: Clean up merged and stale branches
  • references/git-rebase-guide.md:交互式变基深度指南
  • references/git-conflict-resolution.md:高级冲突解决策略
  • references/git-history-rewriting.md:安全重写Git历史
  • assets/git-workflow-checklist.md:PR前清理检查清单
  • assets/git-aliases.md:适用于高级工作流的实用Git别名
  • scripts/git-clean-branches.sh:清理已合并和过时的分支