LY Front-end Dev Engineer

git的使用——修改commit历史纪录

2017-12-15
LY

主要针对项目版本控制器Git的使用中遇到的有关提交历史纪录的问题,进行实践总结。在项目开发中经常会需要修改提交commit信息,合并多个提交commit,甚至放弃当前修改回退至某一历史提交的需求,那我们到底该如何操作呢?

我现在有一个叫newchongou的分支,进行了多次提交,因为当前写得匆忙,commits看起来又多又乱,想将多个commits合并成一个,这样让分支看起来更干净一些。

查看历史纪录

git log: 查看提交历史纪录
git log -{n}: 查看指定条数的提交历史纪录
git log -p -{n}: -p 选项展开显示每次提交的内容差异
git reflog: 查看当前分支的所有操作纪录,包括提交、撤销、合并历史纪录

合并多个commits

git log -3我现在查看我最新的三次提交

commit bc7d06d1dd0acd14ca2f79728c7a7e266d20365e
Author: 刘燕 <liuyan@liuyandeMacBook-Pro-2.local>
Date:   Thu Dec 14 20:54:54 2017 +0800

    code review

commit 9be80c166e42ac1d258435bbfdb91b685f6f80d2
Author: 刘燕 <liuyan@liuyandeMacBook-Pro-2.local>
Date:   Thu Dec 14 16:03:46 2017 +0800

    第一次合并commit

commit 4267aef00ae81d12e7af364ce01ca869b3e5b91c
Merge: 990e426 cc8e6fb
Author: 刘燕 <liuyan@liuyandeMacBook-Pro-2.local>
Date:   Thu Dec 14 15:18:44 2017 +0800

    .

我现在要把4267aef00ae81d12e7af364ce01ca869b3e5b91c这次的提交合并到第一个

git rebase -i 4267aef00ae81d12e7af364ce01ca869b3e5b91c

执行后的内容是这样的:

pick 9be80c1 第一次合并commit
pick bc7d06d code review

# Rebase 4267aef..bc7d06d onto 4267aef (2 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

我们看到了在4267aef00ae81d12e7af364ce01ca869b3e5b91c之前的上两次提交纪录,前面pick代表的默认使用该提交commit,我们现在可以按i进入编辑模式,修改该字段值,值可以如图中描述,经常使用的如下:

pick:简写p,启用该commit;
reword:简写r,使用该commit,但是修改提交信息,修改后可以继续编辑后面的提交信息;
edit:简写e,使用commit,停止合并该commit;
squash:简写s,使用该commit,并将该commit并入前一commit;
drop:简写d,移除该commit;

我们把4267aef00ae81d12e7af364ce01ca869b3e5b91c上一条纪录的pick改成squash

pick 9be80c1 第一次合并commit
squash bc7d06d code review

然后esc退出编辑,输入:wq保存并退出。

接着会让你输入新的commit message ,建议你把原本的提交信息注释掉。在第一行写入新的。

第二次合并commit
# This is a combination of 2 commits.
# The first commit's message is:

# 第一次合并commit

# This is the 2nd commit message:

# code review

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Thu Dec 14 16:03:46 2017 +0800
# Committer: 刘燕 <liuyan@liuyandeMacBook-Pro-2.local>
#
# interactive rebase in progress; onto 4267aef
# Last commands done (2 commands done):
#    pick 9be80c1 第一次合并commit
#    squash bc7d06d code review
# No commands remaining.
# You are currently editing a commit while rebasing branch 'newchongou' on '4267aef'.

编辑完保存离开,不出意外的话会提示Successfully rebased and updated refs/heads/newchongou.就表示合并成功了。

如果失败了,可以用git rebase --abort来终止rebase行动。


Similar Posts

Comments