整洁的commit 之 git rebase 的使用

干净利索是一种态度,避免出现无用的 commit 。学习使用 git rebase 命令,真的会爱上ta。

合并最近俩条commit

1
git rebase -i HEAD~2

需要合并几条数据,数字改为几即可。

自动进入 vi 编辑模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
pick e0b28b9 test 1
pick 670239a test 2

# Rebase 4195fd7..670239a onto 4195fd7 (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
# . 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.

输入i进入编辑模式, 把除第一行的pick改为s

1
2
pick e0b28b9 test 1
s 670239a test 2

按esc键退出输入模式,输入:(英文冒号)进入底线命令模式
在这里插入图片描述

输入wq,会自动进入下一个 vi 编辑模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# This is a combination of 2 commits.
# This is the 1st commit message:

test 1

# This is the commit message #2:

test 2

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date: Fri Sep 18 14:27:13 2020 +0800
#
# interactive rebase in progress; onto 4195fd7
# Last commands done (2 commands done):
# pick e0b28b9 test 1
# squash 670239a test 2
# No commands remaining.
# You are currently rebasing branch 'master' on '4195fd7'.
#
# Changes to be committed:
# new file: demo.txt
#

输入i进入编辑模式, 修改注释信息

第四行为第一条 commit 的注释信息。第六行可以删除掉,是无用信息。第八行是第二条 commit 的注释信息,可以选择删除掉,或合并如第一条。

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

test 1 && test 2

按esc键退出输入模式,输入:(英文冒号)进入底线命令模式,输入 wq 退出编辑。

git log 查看日志

在这里插入图片描述

git push origin master -f 推送分支到远程

加入 -f 是因为使用 rebase 后必须强制推送才可以推送到远程。