将多个提交合并为一个(git rebase -i)【Git技巧!】
首先
在将在本地详细提交之前,想要整理并清理一下,类似这种情况是很常见的。这时,git rebase 命令非常有用。
步骤
首先确认提交
可以使用git log命令进行确认。使用–oneline选项可以将每个日志以一行的形式显示,并使用-n选项指定日志的数量。在这里,我们想要汇总这五个提交。
$ git log --oneline -n 5
o91ref1 (HEAD -> #117_お気に入り機能対応) refs #117 パ
7148d3d refs #117 パ(ry
kc5345f refs #117 パッケージのたm(ry
c231b7f refs #117 パッケージのためにいったんコミット
sb5ex3b refs #117 パッケージを作るためにいったんコミット
将提交合并为一个
使用”git rebase”命令将提交合并为一个。执行”git rebase -i HEAD~5″命令后,将会打开以下文本编辑器。通过使用”HEAD~5″指定最新版本的前五个提交作为目标。
pick sb5ex3b refs #117 パッケージを作るためにいったんコミット
pick c231b7f refs #117 パッケージのためにいったんコミット
pick kc5345f refs #117 パッケージのたm(ry
pick 7148d3d refs #117 パ(ry
pick o91ref1 refs #117 パ
# Rebase 1a0f7bd..o91ref1 onto 1a0f7bd (5 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
# commit's log message, unless -C is used, in which case
# keep only this commit's message; -c is same as -C but
# opens the editor
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# . create a merge commit using the original merge commit's
# . message (or the oneline, if no original merge commit was
# . specified); use -c <commit> to reword the commit message
#
# 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.
在这里重要的是上面的五行。这次我想将五个部分合并为一个,所以下面将进行如下修改。
对于vim来说,按下i键可以进入编辑模式(– INSERT –)。
pick sb5ex3b refs #117 パッケージを作るためにいったんコミット
s c231b7f refs #117 パッケージのためにいったんコミット
s kc5345f refs #117 パッケージのたm(ry
s 7148d3d refs #117 パ(ry
s o91ref1 refs #117 パ
将基准提交选择为pick,其余为s(=squash)。
编辑完成后,按下Esc键退出编辑模式,输入:wq保存并退出编辑。
接下来是编辑提交信息。我们按照相同的步骤继续进行。
# This is a combination of 5 commits.
# This is the 1st commit message:
refs #117 パッケージを作るためにいったんコミット
# This is the commit message #2:
refs #117 パッケージのためにいったんコミット
# This is the commit message #3:
refs #117 パッケージのたm(ry
# This is the commit message #4:
refs #117 パ(ry
# This is the commit message #5:
refs #117 パ
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# ...(以降コミットについての説明なので割愛)
我已经将下面的内容进行了编辑。以 # 开头的行不会被视为评论,可以保持原样。
refs #117 お気に入り機能対応
编辑完成后,再次使用:wq进行保存。这样就将提交合并为一个了。
确认操作结果
使用git log命令进行确认时,会显示如下内容,可确认只有一个提交记录。
$ git log --oneline -n 5
7455ff1 (HEAD -> #117_お気に入り機能対応) refs #117 お気に入り機能対応
1a0f7bd ...
11er987 ...
最后
將多個提交合併為一個的方法如上所述。
由于这并不是一个经常进行的任务,所以很容易忘记步骤对吧?希望在你们这种时候能够参考一下。