Git 重写历史


1. 重写历史

1.1. 修改最后一次提交

  • git commit –amend:修改最后一次提交并修改提交信息
  • git commit –amend –no-edit:修改最后一次提交,但是不改提交信息

1.2. 修改多个提交

使用 git commit –amend 只能修改最后一次提交,如果想要修改最近三次提交,或者最近三次提交中的任意一个提交,可以使用交互式变基:

1
git rebase -i HEAD~3

需要注意的是,交互式变基命令,会使得最近三次提交被重写,无论你是否修改信息。所以变基命令不要涉及到已经推送到远程仓库的提交!

运行这个命令会在文本编辑器上给你一个提交的列表,看起来像下面这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
pick 93b2809 Initial commit
pick 76da34e macair add 1.txt
pick 3c7f123 macair add 4.txt

# Rebase 73b2649..3c7f123 onto 73b2649 (3 command(s))
#
# 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
# d, drop = remove commit
#
# 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

会从旧到新展示最近3次提交信息(最老提交的在最上面,与git log 命令的输出顺序正好相反),如果想要修改某一次提交,就将这次提交前面的『pick』改为『edit』或者『e』。

举例来说,假设说我们想要修改『76da34e』这次提交,那么就将前面的『pick』改为『e』,保存退出后,会有如下输出:

1
2
3
4
5
Stopped at 76da34e1331826c594351381279f4bb99f14e9fc... macair add 1.txt
You can amend the commit now, with
git commit --amend
Once you are satisfied with your changes, run
git rebase --continue

可以看到提示,现在你可以对这次提交做改动,改完以后,运行『git commit –amend』来修改这一次提交,即『76da34e』。修改这次提交后,使用『git rebase –continue』来完成交互式变基。

步骤总结如下:

  1. 修改内容
  2. git commit –amend
  3. git rebase –continue

假设我们现在修改下文件,然后将commit msg改为『rebase test』。
完成之后,我们用git log来看下:

  • 132e4b3 - (HEAD -> macair) macair add 4.txt (4 seconds ago)
  • 0750efb - rebase test (16 seconds ago)
  • 93b2809 - Initial commit (22 minutes ago)

可以看到,我们已经对历史提交做了修改,需要注意的是,交互式rebase,会产生新的commit(可以看到提交前面的哈希变成了0750efb)。

2. 更多交互式变基的demo

2.1. 合并多次提交

1
2
3
4
5
6
7
8
9
# 合并多次提交
pick f7f3f6d v1.1 changed my name a bit
pick 310154e v1.2 updated README formatting and added blame
pick a5f4a0d v1.3 added cat-file

# 改为下面的:
pick f7f3f6d v1.1 changed my name a bit
squash 310154e v1.2 updated README formatting and added blame
squash a5f4a0d v1.3 added cat-file

2.2. 调整提交顺序

1
2
3
4
5
6
7
8
9
# 调整提交顺序,本来是 v1.1 -> v1.2 -> v1.3,想要调整为  v1.1 -> v1.3 -> v1.2
pick f7f3f6d v1.1 changed my name a bit
pick 310154e v1.2 updated README formatting and added blame
pick a5f4a0d v1.3 added cat-file

# 改为下面的:(即调整顺序,其他不变)
pick f7f3f6d v1.1 changed my name a bit
pick a5f4a0d v1.3 added cat-file
pick 310154e v1.2 updated README formatting and added blame