Git 是開發(fā)者的好幫手,今天跟大家分享的是用 git bisect 來找到你代碼中的 bad commit 。
背景
你可能遇到過這種情況, 昨天下班前把模塊開發(fā)完了, 單元測試驗證通過, git commmit
蓋上電腦 開開心心下班啦 ??
第二天啥上午來了,繼續(xù)開發(fā),提交了幾個 commit ,下午部署了一個版本,發(fā)現(xiàn)昨天測試通過的代碼出現(xiàn)了 BUG ??
這個時間你會怎么做, 可能的翻出現(xiàn) BUG 代碼文件的 git log
一翻發(fā)現(xiàn) 有20個 commit ???
此時你的心情可能是崩潰的 ??
告別人肉排查 bad commit 借助 git bisect
找 BUG ??
具體方法
先通過 git log
命令 找到你確定代碼是 OK 的 git hash 再找到你當(dāng)前出現(xiàn) BUG 的 git hash
然后 使用 git bisect start
開始咱們的奇妙 debug 之旅 ??
開始對 commit 做標記
告訴 git 這個 commit(剛才找出來確定代碼是OK的 commit hash) 是 OK 的 git bisect good 5d5dba7
告訴 git 當(dāng)前最后一個 commit 代碼是有 BUG 的 git bisect bad 692ac39
git 會進行二分查找
然后開始開始 test 驗證當(dāng)前 hash 的 commit 的代碼是不是 OK 的
如果當(dāng)前代碼 test 不通過 就標記為 bad git bisect bad
反之如果當(dāng)前代碼 test 通過 就標記為 good git bisect good
反復(fù)的進行 test 和標記 直到找出那個 bad commit 為止
然后退出 git bisect 模式 git bisect reset
附上操作流程圖 git bisect
附上官方文檔 Git Docs
附上二分查找可視化動畫 binary search visualization
附上我的命令行操作記錄
wujunze@Mac: ~/monkey/code/monkey-api develop
$ git bisect start [20:31:46]
wujunze@Mac: ~/monkey/code/monkey-api develop
$ git logg [20:31:50]
wujunze@Mac: ~/monkey/code/monkey-api develop
$ git bisect good 16e91a8 [20:31:54]
wujunze@Mac: ~/monkey/code/monkey-api develop
$ git logg [20:31:59]
wujunze@Mac: ~/monkey/code/monkey-api develop
$ git bisect bad 692ac39 [20:32:04]
Bisecting: 9 revisions left to test after this (roughly 3 steps)
[cd1a0814fe21aa3e06020efb5aa4118ead17acce] not filter
wujunze@Mac: ~/monkey/code/monkey-api cd1a081
$ git bisect bad [20:32:07]
Bisecting: 4 revisions left to test after this (roughly 2 steps)
[63bf3176854a4fe112d612cee3f6bacce9e77e7d] fix merge
wujunze@Mac: ~/monkey/code/monkey-api 63bf317
$ git bisect good [20:32:11]
Bisecting: 2 revisions left to test after this (roughly 1 step)
[798239a0397c52127c721b8b84bb430b5fd0e83b] debug
wujunze@Mac: ~/monkey/code/monkey-api 798239a
$ git bisect bad [20:32:14]
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[5d5dba7c3fc947768cc609493de9808f3d9cf635] fix assert logic
wujunze@Mac: ~/monkey/code/monkey-api 5d5dba7
$ git bisect bad [20:32:23]
5d5dba7c3fc947768cc609493de9808f3d9cf635 is the first bad commit
commit 5d5dba7c3fc947768cc609493de9808f3d9cf635
Author: wujunze <itwujunze@163.com>
Date: Tue Oct 29 18:20:36 2019 +0800
fix assert logic
:040000 040000 b5d77b6ac82d8427d1bc3a9db2213f6c10ea0d63 3f49c18b6569282f7fa2a2c935b9ba73d6d0fbc0 M app
wujunze@Mac: ~/monkey/code/monkey-api 5d5dba7
$ git bisect reset [20:32:27]
Previous HEAD position was 5d5dba7 fix assert logic
Switched to branch 'develop'
Your branch is up to date with 'origin/develop'.
wujunze@Mac: ~/monkey/code/monkey-api develop
$ [20:36:38]
百聞不如一 Run 大家可以自己試一下 有什么問題可以在文章下面評論
筆者才疏學(xué)淺,倉促成文,如有不當(dāng)之處,還請大家斧正.
本文由 吳鈞澤博客 發(fā)布!