🔍 二分查找:git bisect
一句话理解
你有 500 个提交,某个 bug 是最近才出现的。git bisect 用二分法帮你自动定位是哪个提交引入了这个 bug——从 500 个提交里找到罪魁祸首,最多只需要测试 9 次(log₂500 ≈ 9)。
基本用法
bash
# 开始二分查找
git bisect start
# 标记当前版本是"坏的"(有 bug)
git bisect bad
# 标记一个已知"好的"版本(没有 bug)
git bisect good v1.0 # 用标签
git bisect good abc1234 # 用 commit hash
git bisect good HEAD~200 # 用相对引用
Bisecting: 100 revisions left to test after this (roughly 7 steps)
[def4567890123456789012345678901234567890] fix: update dependencies
# Git 自动 checkout 到中间的提交
# 现在你来测试这个版本有没有 bug
# 如果这个版本是好的:
git bisect good
# 如果这个版本是坏的:
git bisect bad
# Git 会继续二分,直到找到引入 bug 的那个提交
abc1234 is the first bad commit
commit abc1234
Author: Someone
Date: Mon Jan 20 10:00:00 2025 +0800
refactor: rewrite authentication module
# 结束二分,回到原来的分支
git bisect reset自动化 bisect(更强大)
如果你有一个测试脚本能判断版本好坏,可以让 git bisect 全自动运行:
bash
# 写一个测试脚本(退出码 0=好,非0=坏)
cat > /tmp/test.sh << 'EOF'
#!/bin/bash
npm test 2>&1 | tail -5
# 如果测试通过(exit 0),git 认为是 good
# 如果测试失败(exit 非0),git 认为是 bad
EOF
chmod +x /tmp/test.sh
# 自动二分查找
git bisect start HEAD v1.0
git bisect run /tmp/test.sh
# Git 会自动 checkout、运行测试、标记 good/bad
# 几分钟后告诉你结果:
abc1234 is the first bad commit
bisect run success
git bisect reset
# 也可以用一条命令直接跑
git bisect start HEAD v1.0 -- npm test💡 提示: 💡 实战场景:性能回归:写脚本测试响应时间,git bisect run ./test-perf.shUI 回归:用 Selenium 截图对比编译失败:写脚本make && echo OK || exit 1