六、高级技巧:让 Git 效率翻倍
6.1 储藏(Stash)
临时保存工作区的修改,去处理更紧急的事情。
# 保存当前修改
git stash
git stash save "正在开发支付功能" # 带描述
# 查看储藏列表
git stash list
# stash@{0}: On main: 正在开发支付功能
# stash@{1}: On main: 修复Bug
# 恢复最近的储藏(并保留)
git stash apply
# 恢复并删除
git stash pop
# 恢复指定的储藏
git stash apply stash@{1}
# 删除指定的储藏
git stash drop stash@{1}
# 清空所有储藏
git stash clear
# 创建分支从储藏
git stash branch new-feature
6.2 交互式 Rebase
交互式 rebase 可以在提交历史进入远程仓库前,对本地提交进行整理。
# 对最近3次提交进行操作
git rebase -i HEAD~3
交互式界面中可用的命令:
实战示例:合并多个提交
# 原始历史
a1b2c3d 添加支付功能(第三步)
e4f5g6h 添加支付功能(第二步)
i7j8k9l 添加支付功能(第一步)
# 执行 git rebase -i HEAD~3
# 编辑界面中修改:
pick i7j8k9l 添加支付功能(第一步)
squash e4f5g6h 添加支付功能(第二步)
squash a1b2c3d 添加支付功能(第三步)
# 保存后会弹出新界面让你编辑最终的提交信息
# 最终历史:
x9y8z7w 添加支付功能
6.3 Cherry-pick
选择性地将其他分支的某个提交应用到当前分支。
# 复制一个提交到当前分支
git cherry-pick <commit-hash>
# 复制多个提交
git cherry-pick <commit1> <commit2> <commit3>
# 复制一段连续的提交
git cherry-pick <start>..<end>
# 编辑提交信息
git cherry-pick -e <commit-hash>
# 不自动提交(方便调整)
git cherry-pick -n <commit-hash>
使用场景:
将修复 Bug 的提交应用到多个分支
从开发分支提取特定功能到主分支
恢复误删的提交
6.4 Bisect:二分查找 Bug
当你知道某个 Bug 存在,但不确定是哪个提交引入时,用 git bisect 二分查找。
# 开始二分查找
git bisect start
# 标记当前版本有问题
git bisect bad
# 标记已知的好版本
git bisect good <commit-hash>
# Git 会自动切换到一个中间版本,测试后标记
git bisect bad # 如果当前版本有问题
git bisect good # 如果当前版本正常
# 重复直到找到引入 Bug 的提交
# 找到后退出
git bisect reset
6.5 子模块(Submodule)
在一个 Git 仓库中引入另一个 Git 仓库。
# 添加子模块
git submodule add https://github.com/example/lib.git libs/example-lib
# 克隆包含子模块的仓库
git clone --recursive https://github.com/example/main-repo.git
# 更新子模块
git submodule update --init --recursive
# 更新子模块到最新
cd libs/example-lib
git pull origin main
cd ..
git add libs/example-lib
git commit -m "更新子模块"
# 查看子模块状态
git submodule status
6.6 钩子(Hooks)
Git 钩子是在特定事件发生时自动执行的脚本。
# 钩子存放在 .git/hooks/ 目录下
ls .git/hooks/
# pre-commit.sample
# commit-msg.sample
# post-commit.sample
# ...
# 创建 pre-commit 钩子(提交前运行测试)
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
npm run test
if [ $? -ne 0 ]; then
echo "测试失败,提交被阻止"
exit 1
fi
EOF
chmod +x .git/hooks/pre-commit
常用钩子:
来源:
https://hllft.cn