rebase 重置

作用: 是重置提效记录。
本质是,当合并其它分支的提交记录后,重整提交记录。
不论是自己开发,还是参加开源项目,有很多时间,需要重整提交记录。美化一下,这时候就很有用了。

需要强调一点:一定是在你自己的分支上rebase,别把master之类的分支rebase掉了。

git rebase

假设你在test_rebase分支进行开发,现在master分支已经有新的提交,test有多次提交,现在你想合并master分支,并提交推送到远程仓库中看起来只有一次提交。

提交记录分别是:

test_rebase分支:

rebase: test commit2
rebase: test commit1

master分支:

master: test commit2
master: test commit1

test_rebase分支下执行:

1
git rebase -i master

-i: --interactive,即交互式的界面

进入交互模式,用vim来编辑,下面这个内容是:

pick: 要保留的掉交commit 和 message,如果要重写commit message用 reword。
e1164ca: 我执行 rebase 之前的commit
# Rebase 27a682f..: 这部份是注释,不用改也不会被提交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
pick e1164ca rebase: test commit1
pick 221d61d rebase: test commit2


# Rebase 27a682f..221d61d onto 27a682f (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 [-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

接下来要怎么做?

接下来保留一个主要commit,把其他commit合入主要commit。
保留一个主commit用:pick,其它的commit都用s,如下:
写完wq保存后,还有一次本次的commit message要写。

1
2
pick e1164ca rebase: test commit1
s 221d61d rebase: test commit2

写本次的 commit message:
注意看下面,是把两次commit message 都给带上了,删掉一条重写即可,不然提交易去就是两条message。
# 井号的内容不会被提交,最简单的方式,全删除,再写。
保存,退出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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

rebase: test commit1

# This is the commit message #2:

rebase: test commit2

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date: Wed Dec 7 00:43:42 2022 +0800
#

看下结果,原来的:

rebase: test commit1
rebase: test commit2

被合并成一条了

git-rebase结果

中断 rebase

如果过程中退出了,但又不想继续了,执行:

1
git rebase --abort

如果保存后出现冲空,解决后,再执行一下 rebase:

1
git rebase --continue

总结

rebase 操作比较简单,主要作用就是修剪提交的commit、重写新的message,这在平时多分支开发的时候,非常好用。