LMLPHP后院

git使用之rebase合并提交技术

maybe yes 发表于 2015-03-15 22:43

对于版本控制系统 GIT ,一直没有深入研究,只是从日常使用方面入手,能解决平常使用出现的问题就可以了。GIT 的版本控制,有三种后悔方式:reset、revert 和 rebase,本文主要讲述 rebase 的使用。

使用场景:当在新分支开发一个新功能的过程中,开发期间涉及的文件数比较多,提交的次数也非常多,同时整个提交的过程非常的复杂,在最后合并的时候,需要移除某些修改文件并且将提交次数整理为一次 commit。

使用下面的命令,显示所有提交记录,找出第一次 {commit} 的前一个 {commit} 的哈希值并复制。

git log --pretty=oneline

使用 rebase 命令加上 -i 参数,合并提交到指定位置,如下示例。

git rebase -i f7d0bd75c8dabe127d8cbd2c1d70ff188ff83392

运行后,进入 VIM 模式,除第一个 pick 外,其余的全部修改成 squash,也可以缩写为 s,如下示例。

pick 4f11983 add update method in mysql driver class;
squash aa8576a add attachEvent method
squash e6e8db4 modify default_theme_name constant name
squash f7d0bd7 fix method logPre;

# Rebase 6a2eb6d..f7d0bd7 onto 6a2eb6d
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out 

接下来,使用 :wq 保存确认后,会进入编辑 comment 模式下,此处只需要将多个提交的 comments 进行编辑,然后 :wq 保存即可。通常情况下,只要恢复到了第一次提交,就不会出现冲突。若 GIT 在 rebase 的过程中产生冲突,会进入一个临时分支,只需要将该分支中被修改的文件编辑后提交,使用 git rebase --continue 完成 rebase 的过程,或者使用 git rebase --abort 取消操作最后 push 的时候需要加上参数 -f,否则不能推送到远程库。

如果提交了很多次以后,并不想擦除提交记录,只想将部分需要移除的文件内容恢复到创建分支前的状态,可以使用 checkout 命令,指定某个 commit 和某个文件。内容恢复后,再进行一次提交即可,团队人数很少的时候,可以这样做,如果项目开发成员比较多,为避免提交纪录太乱,rebase 还是最好的方案。

相关文章
2024-04-24 19:13:20 1713957200 0.036000