本地开发时,可以随时去提交写好的代码,但这样会导致提交历史比较多,推送到远端或者发起Pull Request显得比较杂乱,这时就可以将几次提交或者全部提交合并成一次提交。

第一步:执行git log或git status查看代码的提交状况。

git status可以看到本地有2次commit:

(base) appledeMacBook-Pro-2:beta-parent apple$ git status
On branch master
Your branch is ahead of 'origin/master' by 2 commits.
(use "git push" to publish your local commits)

git log可以查看每次提交的注释信息:

(base) appledeMacBook-Pro-2:beta-parent apple$ git log
commit 23bad176cc6dfc95ab63b90c365a636143a865c2 (HEAD -> master)
Author: secbro <xxx@126.com>
Date:   Wed Sep 8 15:10:04 2021 +0800

  优化代码-业务逻辑判断

commit f29b55dcf832fab9ef94df06dc4b17d1dc4e273f
Author: secbro <xxx@126.com>
Date:   Wed Sep 8 15:08:02 2021 +0800

  优化代码-移除无用代码

查看到有2次提交,现将将这2次提交的注释进行合并。

第二步:修改提交注释命令

输入git rebase -i HEAD~N(N=需要合并的最后几次提交)。

git rebase -i HEAD~2

输出如下:

pick f29b55dc 优化代码-移除无用代码
pick 23bad176 优化代码-业务逻辑判断

# Rebase 227b1465..23bad176 onto 227b1465 (2 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 <commit> = like "squash", but discard this commit's log message
# 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

第三步:根据Commands注释修改成预期效果

将第二次提交注释命令改为squash:

pick f29b55dc 优化代码-移除无用代码
squash 23bad176 优化代码-业务逻辑判断

第四步:保存退出

输入:wq保存退出,出现如下提交信息:

# This is a combination of 2 commits.
# This is the 1st commit message:

优化代码-移除无用代码

# This is the commit message #2:

优化代码-业务逻辑判断

第五步:修改实际提交信息

其中#开头的为注释,可以不用管。将上面两行注释修改为一行:

# This is a combination of 2 commits.
# This is the 1st commit message:

优化代码-移除无用代码和添加TODO

第六步:再次保存退出

再次输入:wq就会看到合并完毕的提示信息:

(base) appledeMacBook-Pro-2:beta-parent apple$ git rebase -i HEAD~2
[detached HEAD e509fc87] 优化代码-移除无用代码和添加TODO
Date: Wed Sep 8 15:08:02 2021 +0800
2 files changed, 19 insertions(+), 31 deletions(-)
Successfully rebased and updated refs/heads/master.

再次执行git log或git status查看代码的提交状况会发现已经变为1次提交了。说明Rebase合并成功,2次提交合并成一次提交;

第七步:提交代码

此时可通过git push提交代码了。



Git提交合并提交及注释插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:http://www.choupangxia.com/2021/09/08/git-rebase-comments/