合并整理 Git commit

57 阅读2分钟

1.背景

现在代码仓库基本都在使用Git管理代码,常常是git commit -m后,就执行 git push.为了能够实时更新代码或者修改一些小的bug,会存在很多毫无意义的git commit,导致 branch 看到的 'git log' 都是杂乱无章的.

2.如何合并整理多个commit

2.1 使用git log命令查看commit记录

可以加上参数git log --pretty=oneline, 只会显示版本号和提交时的备注信息, 看起来更加简洁.注意vim模式下按q退出.

git log --pretty=oneline

2.2 使用git rebase -i HEAD~X命令合并commit

git rebase -i HEAD~X命令含义是合并前X次提交的内容

比如说合并前五次提交的内容.

git rebase -i HEAD~5
此命令等效于git rebase -i c854a42 f69e8d8
其中c854a42为commit_1的前一个提交 f69e8d8为commit_5
pick 5eef5f7 commit_1
pick a3285df commit_2
pick fc34dw2 commit_3
pick ghw23h5 commit_4
pick f69e8d8 commit_5
# Rebase c854a42..f69e8d8 onto c854a42
#
# 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

看 Commands 的解释

p, pick 使用这条 commit

r, reword 使用这条 commit 但是要修改 commit message

e, edit 使用这条 commit 但是要修改 commit messaage // 这里和 reword 使用方法一样,
但 reword 在 :wq 后会直接让你进入修改编辑, edit :wq 后要再使用 git commit --amend 进入修改

s, squash 使用这条 commit, 但是要与上一条 commit 合并, 并保留自身 commit message

f, fixup 与 squash 一样, 但是舍弃 自身 commit message

x, exec 执行命令

2.3 vim编辑结果如下

将vim编辑结果如下,可以将5个提交合并成1个,(其中这里也可以调整commit顺序或选取部分commit记录,灵活度大)

pick 5eef5f7 commit_1
s a3285df commit_2
s fc34dw2 commit_3
s ghw23h5 commit_4
s f69e8d8 commit_5

2.4 保存执行

wq保存后,自动执行,出现执行结果交互界面

image.png 这里会把5个历史提交的的内容都合并在一起,这里可以重新编辑,简洁提交内容,如简洁为:

image.png

2.4 wq再次保存执行,变基完成

如果看到如下提示,表示合并成功

Successfully rebased and updated refs/heads/分支名

2.5 如果是已经push过的commit,再force push一次