天天看點

Git Bug分支

軟體開發中,bug就像家常便飯一樣。有了bug就需要修複,在Git中,由于分支是如此的強大,是以,每個bug都可以通過一個新的臨時分支來修複,修複後,合并分支,然後将臨時分支删除。

當你接到一個修複一個代号101的bug的任務時,很自然地,你想建立一個分支issue-101來修複它,但是,等等,目前正在dev上進行的工作還沒有送出:

$ git status
On branch dev
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

  new file:   hello.py

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

  modified:   readme.txt      

并不是你不想送出,而是工作隻進行到一半,還沒法送出,預計完成還需1天時間。但是,必須在兩個小時内修複該bug,怎麼辦?

幸好,Git還提供了一個stash功能,可以把目前工作現場“儲藏”起來,等以後恢複現場後繼續工作:

$ git stash
Saved working directory and index state WIP on dev: f52c633 add merge      

現在,用​

​git status​

​檢視工作區,就是幹淨的(除非有沒有被Git管理的檔案),是以可以放心地建立分支來修複bug。

首先确定要在哪個分支上修複bug,假定需要在master分支上修複,就從master建立臨時分支:

$ git checkout master
Switched to branch 'master'
Your branch is ahead of 'origin/master' by 6 commits.
  (use "git push" to publish your local commits)

$ git checkout -b issue-101
Switched to a new branch 'issue-101'      

現在修複bug,需要把“Git is free software …”改為“Git is a free software …”,然後送出:

$ git add readme.txt 
$ git commit -m "fix bug 101"
[issue-101 4c805e2] fix bug 101
 1 file changed, 1 insertion(+), 1 deletion(-)      

修複完成後,切換到master分支,并完成合并,最後删除issue-101分支:

$ git checkout master
Switched to branch 'master'
Your branch is ahead of 'origin/master' by 6 commits.
  (use "git push" to publish your local commits)

$ git merge --no-ff -m "merged bug fix 101" issue-101
Merge made by the 'recursive' strategy.
 readme.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)      

太棒了,原計劃兩個小時的bug修複隻花了5分鐘!現在,是時候接着回到dev分支幹活了!

$ git checkout dev
Switched to branch 'dev'

$ git status
On branch dev
nothing to commit, working tree clean      

工作區是幹淨的,剛才的工作現場存到哪去了?用git stash list指令看看:

$ git stash list
stash@{0}: WIP on dev: f52c633 add merge      

工作現場還在,Git把stash内容存在某個地方了,但是需要恢複一下,有兩個辦法:

一是用git stash apply恢複,但是恢複後,stash内容并不删除,你需要用git stash drop來删除;

另一種方式是用git stash pop,恢複的同時把stash内容也删了:

$ git stash pop
On branch dev
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

  new file:   hello.py

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

  modified:   readme.txt

Dropped refs/stash@{0} (5d677e2ee266f39ea296182fb2354265b91b3b2a)      

再用​

​git stash list​

​​檢視,就看不到任何​

​stash​

​内容了:

$ git stash list      

你可以多次stash,恢複的時候,先用git stash list檢視,然後恢複指定的stash,用指令:

$ git stash apply stash@{0}