关于 git-advanced
面向有经验的 Git 用户,提供处理复杂历史和分支操作的指导,涵盖变基、提交修改、合并、冲突解决、暂存及相关工作流。
主要功能
- 01交互式变基与提交重排
- 02压缩、拆分、修改和编辑提交
- 03高级摘取提交与合并策略
- 04冲突解决与 rerere
- 05部分暂存、重置和暂存操作
- 06分支、子模块与历史管理
适用场景
- 01分享前重写本地提交历史
- 02整理提交时拆分或合并提交
- 03跨分支应用提交并解决冲突
- 04恢复丢失提交或检查历史
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ geoffjay/ claude-plugins --skill git-advanced安装后在 Claude Code 中输入/git-advanced确认已加载。
详细介绍
Git 高级操作技能
此技能为经验丰富的 Git 用户提供全面指导,涵盖高级 Git 操作、复杂的变基策略、提交修整技巧以及复杂的历史记录操作。
使用时机
在以下情况下启用此技能:
- 执行复杂的交互式变基
- 重写提交历史
- 拆分或合并提交
- 使用高级合并策略
- 跨分支执行 Cherry-pick
- 编辑历史记录中的提交消息
- 更改作者信息
- 解决复杂冲突
交互式变基策略
基本交互式变基
# Rebase last 5 commits
git rebase -i HEAD~5
# Rebase from specific commit
git rebase -i abc123^
# Rebase entire branch
git rebase -i main
变基命令
# Interactive rebase editor commands:
# p, pick = use commit
# r, reword = use commit, but edit commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like squash, but discard commit message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
压缩提交
# Example: Squash last 3 commits
git rebase -i HEAD~3
# In editor:
pick abc123 feat: add user authentication
squash def456 fix: resolve login bug
squash ghi789 style: format code
# Squash all commits in feature branch
git rebase -i main
# Mark all except first as 'squash'
Fixup 工作流
# Create fixup commit automatically
git commit --fixup=abc123
# Autosquash during rebase
git rebase -i --autosquash main
# Set autosquash as default
git config --global rebase.autosquash true
# Example workflow:
git log --oneline -5
# abc123 feat: add authentication
# def456 feat: add authorization
git commit --fixup=abc123
git rebase -i --autosquash HEAD~3
重新排列提交
# Interactive rebase
git rebase -i HEAD~5
# In editor, change order:
pick def456 feat: add database migration
pick abc123 feat: add user model
pick ghi789 feat: add API endpoints
# Reorder by moving lines:
pick abc123 feat: add user model
pick def456 feat: add database migration
pick ghi789 feat: add API endpoints
拆分提交
# Start interactive rebase
git rebase -i HEAD~3
# Mark commit to split with 'edit'
edit abc123 feat: add user and role features
# When rebase stops:
git reset HEAD^
# Stage and commit parts separately
git add user.go
git commit -m "feat: add user management"
git add role.go
git commit -m "feat: add role management"
# Continue rebase
git rebase --continue
编辑旧提交
# Start interactive rebase
git rebase -i HEAD~5
# Mark commit with 'edit'
edit abc123 feat: add authentication
# When rebase stops, make changes
git add modified-file.go
git commit --amend --no-edit
# Or change commit message
git commit --amend
# Continue rebase
git rebase --continue
提交修整
修改提交
# Amend last commit (add changes)
git add forgotten-file.go
git commit --amend --no-edit
# Amend commit message
git commit --amend -m "fix: correct typo in feature"
# Amend author information
git commit --amend --author="John Doe <[email protected]>"
# Amend date
git commit --amend --date="2024-03-15 10:30:00"
更改提交消息
# Change last commit message
git commit --amend
# Change older commit messages
git rebase -i HEAD~5
# Mark commits with 'reword'
# Change commit message without opening editor
git commit --amend -m "new message" --no-edit
更改多个作者
# Filter-branch (legacy method, use filter-repo instead)
git filter-branch --env-filter '
if [ "$GIT_COMMITTER_EMAIL" = "[email protected]" ]; then
export GIT_COMMITTER_NAME="New Name"
export GIT_COMMITTER_EMAIL="[email protected]"
fi
if [ "$GIT_AUTHOR_EMAIL" = "[email protected]" ]; then
export GIT_AUTHOR_NAME="New Name"
export GIT_AUTHOR_EMAIL="[email protected]"
fi
' --tag-name-filter cat -- --branches --tags
# Modern method with git-filter-repo
git filter-repo --email-callback '
return email.replace(b"[email protected]", b"[email protected]")
'
从历史记录中移除文件
# Remove file from all history
git filter-branch --tree-filter 'rm -f passwords.txt' HEAD
# Better performance with index-filter
git filter-branch --index-filter 'git rm --cached --ignore-unmatch passwords.txt' HEAD
# Modern method with git-filter-repo (recommended)
git filter-repo --path passwords.txt --invert-paths
# Remove large files
git filter-repo --strip-blobs-bigger-than 10M
BFG Repo-Cleaner
# Install BFG
# brew install bfg (macOS)
# apt-get install bfg (Ubuntu)
# Remove files by name
bfg --delete-files passwords.txt
# Remove large files
bfg --strip-blobs-bigger-than 50M
# Replace passwords in history
bfg --replace-text passwords.txt
# After BFG cleanup
git reflog expire --expire=now --all
git gc --prune=now --aggressive
高级 Cherry-pick
基本 Cherry-pick
# Cherry-pick single commit
git cherry-pick abc123
# Cherry-pick multiple commits
git cherry-pick abc123 def456 ghi789
# Cherry-pick range of commits
git cherry-pick abc123..ghi789
# Cherry-pick without committing (stage only)
git cherry-pick -n abc123
处理冲突的 Cherry-pick
# When conflicts occur
git cherry-pick abc123
# CONFLICT: resolve conflicts
# After resolving conflicts
git add resolved-file.go
git cherry-pick --continue
# Or abort cherry-pick
git cherry-pick --abort
# Skip current commit
git cherry-pick --skip
Cherry-pick 选项
# Edit commit message during cherry-pick
git cherry-pick -e abc123
# Sign-off cherry-picked commit
git cherry-pick -s abc123
# Keep original author date
git cherry-pick --ff abc123
# Apply changes without commit attribution
git cherry-pick -n abc123
git commit --author="New Author <[email protected]>"
为合并提交选择主线
# Cherry-pick merge commit (specify parent)
git cherry-pick -m 1 abc123
# -m 1 = use first parent (main branch)
# -m 2 = use second parent (merged branch)
# Example workflow:
git log --graph --oneline
# * abc123 Merge pull request #123
# |\
# | * def456 feat: feature commit
# * | ghi789 fix: main branch commit
# To cherry-pick the merge keeping main branch changes:
git cherry-pick -m 1 abc123
高级合并
合并策略
# Recursive merge (default)
git merge -s recursive branch-name
# Ours (keep our changes on conflict)
git merge -s ours branch-name
# Theirs (keep their changes on conflict)
git merge -s theirs branch-name
# Octopus (merge 3+ branches)
git merge -s octopus branch1 branch2 branch3
# Subtree merge
git merge -s subtree branch-name
合并策略选项
# Ours (resolve conflicts with our version)
git merge -X ours branch-name
# Theirs (resolve conflicts with their version)
git merge -X theirs branch-name
# Ignore whitespace
git merge -X ignore-space-change branch-name
git merge -X ignore-all-space branch-name
# Patience algorithm (better conflict detection)
git merge -X patience branch-name
# Renormalize line endings
git merge -X renormalize branch-name
三方合并
# Standard three-way merge
git merge feature-branch
# With custom merge message
git merge feature-branch -m "Merge feature: add authentication"
# No fast-forward (always create merge commit)
git merge --no-ff feature-branch
# Fast-forward only (fail if merge commit needed)
git merge --ff-only feature-branch
# Squash merge (combine all commits)
git merge --squash feature-branch
git commit -m "feat: add complete authentication system"
高级冲突解决
了解冲突标记
<<<<<<< HEAD (Current Change)
int result = add(a, b);
=======
int sum = calculate(a, b);
>>>>>>> feature-branch (Incoming Change)
冲突解决工具
# Use mergetool
git mergetool
# Specify merge tool
git mergetool --tool=vimdiff
git mergetool --tool=meld
git mergetool --tool=kdiff3
# Configure default merge tool
git config --global merge.tool vimdiff
git config --global mergetool.vimdiff.cmd 'vimdiff "$LOCAL" "$MERGED" "$REMOTE"'
# Check out specific version
git checkout --ours file.go # Keep our version
git checkout --theirs file.go # Keep their version
git checkout --merge file.go # Recreate conflict markers
Rerere(重用已记录的解决方案)
# Enable rerere
git config --global rerere.enabled true
# Rerere will automatically resolve previously seen conflicts
git merge feature-branch
# Conflict occurs and is resolved
git add file.go
git commit
# Later, same conflict:
git merge another-branch
# Rerere automatically applies previous resolution
# View rerere cache
git rerere status
git rerere diff
# Clear rerere cache
git rerere forget file.go
git rerere clear
交互式暂存
暂存文件的部分内容
# Interactive staging
git add -p file.go
# Patch commands:
# y - stage this hunk
# n - do not stage this hunk
# q - quit (do not stage this and remaining hunks)
# a - stage this and all remaining hunks
# d - do not stage this and all remaining hunks
# s - split the current hunk into smaller hunks
# e - manually edit the current hunk
交互式添加
# Interactive mode
git add -i
# Commands:
# 1: status - show paths with changes
# 2: update - stage paths
# 3: revert - unstage paths
# 4: add untracked - stage untracked files
# 5: patch - partial staging
# 6: diff - show staged changes
# 7: quit - exit
部分提交
# Stage part of file interactively
git add -p file.go
# Create commit with partial changes
git commit -m "feat: add validation logic"
# Stage remaining changes
git add file.go
git commit -m "feat: add error handling"
高级重置操作
重置模式
# Soft reset (keep changes staged)
git reset --soft HEAD~1
# Mixed reset (keep changes unstaged, default)
git reset --mixed HEAD~1
git reset HEAD~1
# Hard reset (discard all changes)
git reset --hard HEAD~1
# Reset to specific commit
git reset --hard abc123
重置与还原
# Reset (rewrites history, use for local changes)
git reset --hard HEAD~3
# Revert (creates new commit, safe for shared history)
git revert HEAD
git revert HEAD~3
git revert abc123..def456
高级分支操作
从指定提交创建分支
# Create branch from commit
git branch new-branch abc123
git checkout new-branch
# Or in one command
git checkout -b new-branch abc123
# Create branch from remote commit
git checkout -b local-branch origin/remote-branch
孤立分支
# Create orphan branch (no parent)
git checkout --orphan new-root
git rm -rf .
# Useful for gh-pages, documentation, etc.
echo "# Documentation" > README.md
git add README.md
git commit -m "docs: initialize documentation"
分支跟踪
# Set upstream branch
git branch -u origin/main
# Push and set upstream
git push -u origin feature-branch
# Change upstream
git branch -u origin/develop
# View tracking information
git branch -vv
高级暂存操作
暂存指定文件
# Stash specific files
git stash push -m "WIP: feature work" file1.go file2.go
# Stash with pathspec
git stash push -p
# Stash untracked files
git stash -u
# Stash including ignored files
git stash -a
将暂存内容保存到分支
# Create branch from stash
git stash branch new-branch stash@{0}
# Creates new branch and applies stash
git stash branch feature-work
部分应用暂存内容
# Apply specific files from stash
git checkout stash@{0} -- file.go
# Apply stash without dropping
git stash apply stash@{0}
# Apply and drop
git stash pop stash@{0}
子模块管理
高级子模块操作
# Update submodule to specific commit
cd submodule-dir
git checkout abc123
cd ..
git add submodule-dir
git commit -m "chore: update submodule to version 1.2.3"
# Update all submodules to latest
git submodule update --remote --merge
# Update specific submodule
git submodule update --remote --merge path/to/submodule
# Run command in all submodules
git submodule foreach 'git checkout main'
git submodule foreach 'git pull'
# Clone with submodules at specific depth
git clone --recurse-submodules --depth 1 repo-url
将子模块迁移为子树
# Remove submodule
git submodule deinit path/to/submodule
git rm path/to/submodule
rm -rf .git/modules/path/to/submodule
# Add as subtree
git subtree add --prefix=path/to/submodule \
https://github.com/user/repo.git main --squash
# Update subtree
git subtree pull --prefix=path/to/submodule \
https://github.com/user/repo.git main --squash
高级日志与历史记录
自定义日志格式
# One-line format with custom fields
git log --pretty=format:"%h - %an, %ar : %s"
# Full custom format
git log --pretty=format:"%C(yellow)%h%C(reset) %C(blue)%ad%C(reset) %C(green)%an%C(reset) %s" --date=short
# Aliases for common formats
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"
查找丢失的提交
# Find commits not in any branch
git log --all --oneline --no-walk --decorate $(git fsck --no-reflog | grep commit | cut -d' ' -f3)
# Find dangling commits
git fsck --lost-found
# Search commit messages
git log --all --grep="search term"
# Find commits by author
git log --author="John Doe"
# Find commits modifying specific code
git log -S "function_name"
git log -G "regex_pattern"
自动化二分查找
# Start bisect
git bisect start
git bisect bad HEAD
git bisect good abc123
# Automate bisect with script
git bisect run ./test.sh
# test.sh example:
#!/bin/bash
make && make test
exit $?
# Bisect will automatically find first bad commit
最佳实践
- 重写历史前备份: 执行复杂操作前创建备份分支
- 切勿重写已发布的历史: 仅重写本地提交
- 沟通变基操作: 强制推送时通知团队
- 使用描述性提交消息: 即使在交互式变基期间也应如此
- 变基后进行测试: 确保历史记录更改后代码仍能正常工作
- 本地分支优先使用变基: 保持历史记录线性
- 共享分支使用合并: 保留完整历史记录
- 签署重要提交: 使用 GPG 签名发布版本
- 记录复杂操作: 留下注释以供日后参考
- 知道何时停止: 有时合并提交比变基后的历史记录更清晰
资源
更多指南和示例请参阅 assets/ 目录:
examples/- 复杂的变基和合并场景scripts/- 常见操作的自动化脚本workflows/- 高级工作流模式
references/ 目录中包含:
- Git 内部机制文档
- 高级变基策略
- filter-branch 的替代方案
- 冲突解决技巧
评论
支持 Markdown