Bug分支
当线上出现Bug需要修复,而手上的工作只进行了一般不想提交;此时可以通过一个新的临时分支来修复,修复后合并分支,然后将临时分支删除。
当前正在 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
git stash 存储工作区、git stash pop 恢复工作区、git cherry-pick 复制特定提交
Git 提供了 stash 功能,将当前工作 “储存” 起来,等以后恢复后继续工作:
$ git stash
Saved working directory and index state WIP on dev: f52c633 add merge
步骤如下:
-
先使用 git status 查看工作区,确保干净(除非有没有被 Git 管理的文件),创建分支来修复 bug:
$ 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-bug Switched to a new branch 'issue-bug'
-
修复 bug,然后提交:
$ git add readme.txt $ git commit -m "fix bug 101" [issue-bug 4c805e2] fix bug 101 1 file changed, 1 insertion(+), 1 deletion(-)
-
切到 master 分支,完成合并,然后删除 issue-bug 分支:
$ 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-bug Merge made by the 'recursive' strategy. readme.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
-
切回到 dev 继续工作,但现在的工作区是干净的;先执行 git stash list 命令查看以下之前存储的工作区:
$ git checkout dev Switched to branch 'dev' $ git status On branch dev nothing to commit, working tree clean $ git stash list stash@{0}: WIP on dev: f52c633 add merge
-
有两种方法恢复之前的工作区:
- 执行 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)
-
由于 bug 有另一个分支处理的,当前恢复的分支没有修复的内容,执行 git cherry-pick 命令,复制一个特定的提交(4c805e2 fix bug 101)到当前分支:
$ git branch * dev master $ git cherry-pick 4c805e2 [master 1d4b803] fix bug 101 1 file changed, 1 insertion(+), 1 deletion(-)
注意:执行 git cherry-pick 命令时,Git 自动给 dev 做了一次提交;此次提交的 1d4b803 与上次提交的 4c805e2,可以明显看出是两次不同提交,不需要在dev分支上手动再把修bug的过程重复一遍。
Feature分支
实验性代码不予主分支混合,避免混乱;采用上述方法可以完成。
但是实验性代码被取消时,需要把其分支进行删除,此时执行 git branch -d feature-vulcan 会报错:
$ git branch -d feature-vulcan
error: The branch 'feature-vulcan' is not fully merged.
If you are sure you want to delete it, run 'git branch -D feature-vulcan'.
由于 feature-vulcan 分支还没有被合并,删除会丢失修改;此时根据报错的提示内容,执行 git branch -D feature-vulcan 命令进行强制删除:
$ git branch -D feature-vulcan
Deleted branch feature-vulcan (was 287773e).