菜鸟笔记
提升您的技术认知

git 简洁提交——合并多个commit

  • 本地开发,服务器上编译、运行。
  • 多台电脑间同步代码
  • 不放心本地,为了备份经常push到代码服务器上。

因为以上等原因,我需要经常执行git commit,这就导致git的历史中包含很多无效的提交。
简洁的git log和工整的代码同样重要,所以我需要合并多个commit。

简洁提交

git checkout master
git merge --squash feature
git commit
git push

squash命令可以将整个feature分支压缩为master分支上的一个commit。

下面这条命令也可以达到类似的效果:

git merge --no-ff --no-commit

但还是有一点细微的差别
--squash
If you checkout master and then git merge --squash topic; git commit -m topic

--no-ff --no-commit
Instead, if you do git merge --no-ff --no-commit; git commit -m topic

修改提交历史

git rebase -i HEAD~5

-i, –interactive表示使用“交互式”的方法修改。这个命令会列出最近5个commit。
大致如下:

pick 6e53cd0 update
pick 446e6ce update
pick b1ec2c4 update
pick 366dfac update
pick 04bf27b for clear script
# Rebase 574d47f..04bf27b onto 574d47f (5 command(s))
#
# 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
# d, drop = remove commit
#
# 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

将pick改squash或fixup就可以将对应的commit合并到前一个commit中。
区别是squash会保留commit message而fixup不会。

pick 6e53cd0 update
f 446e6ce update
f b1ec2c4 update
f 366dfac update
pick 04bf27b for clear script

保存退出后就会生效。