在開發過程中,大家都遇到過bug,並且有些bug是需要緊急修復的。
當開發人員遇到這樣的問題時,首先想到的是我新切一個分支,把它修復了,再合並到master上。
當時問題來了,你當前正在開發的分支上面,還有未提交的代碼,你又不想把代碼提交了,怎么辦呢?
git提供了stash
功能,把當前工作目錄現場給存儲起來,等修復完bug,再切回來。
比如,我當前在dev分支上,我修改了hello.py文件
wangkongming@Vostro ~/babytree/github/test_git $ git st
On branch dev
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: hello.py
no changes added to commit (use "git add" and/or "git commit -a")
執行git stash
命令后,再查看分支狀態
wangkongming@Vostro ~/babytree/github/test_git $ git stash
Saved working directory and index state WIP on dev: a9c8783 *modify dev 1
HEAD is now at a9c8783 *modify dev 1
wangkongming@Vostro ~/babytree/github/test_git $ git st
On branch dev
nothing to commit, working directory clean
從master上新切分支hot_fix
來處理bug
wangkongming@Vostro ~/babytree/github/test_git $ git co master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
wangkongming@Vostro ~/babytree/github/test_git $ git co -b hot_fix
Switched to a new branch 'hot_fix'
修改了test/readme.txt文件
wangkongming@Vostro ~/babytree/github/test_git $ git st
On branch hot_fix
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: test/readme.txt
no changes added to commit (use "git add" and/or "git commit -a")
添加到版本庫,提交
wangkongming@Vostro ~/babytree/github/test_git $ git add .
wangkongming@Vostro ~/babytree/github/test_git $ git ci -m 'fix bug'
[hot_fix 7b3948b] fix bug
1 file changed, 1 insertion(+)
切回master,合並hot_fix分支
wangkongming@Vostro ~/babytree/github/test_git $ git co master
Already on 'master'
Your branch is up-to-date with 'origin/master'.
wangkongming@Vostro ~/babytree/github/test_git $ git merge hot_fix
Updating 1ebc483..7b3948b
Fast-forward
test/readme.txt | 1 +
1 file changed, 1 insertion(+)
ok,到此,這個緊急的bug,已經合並到master分支上。現在可以回到dev分支上繼續開發了。
用stash list
來查看已經存儲的工作現場。
wangkongming@Vostro ~/babytree/github/test_git $ git stash list
stash@{0}: WIP on dev: a9c8783 *modify dev 1
如何恢復工作現場呢?
- 第一種方案,用
git stash apply
恢復,但是恢復后,stash內容不刪除,需要用git stash drop
來刪除 - 第二種方案,用
git stash pop
,恢復的同時把stash內容也刪除了。
wangkongming@Vostro ~/babytree/github/test_git $ git stash pop
On branch dev
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: hello.py
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (d658ee3001b54567337fe7fe522e6fd813fd73ae)
總結###
修復bug時,通過新建分支,去修復bug,然后合並分支,刪除分支。
當前工作沒有完成,先把現場git stash
存儲一下,去修復bug,修復完后,在git stash pop
,回到工作現場。
參考文章:Bug分支