Git 编辑历史提交的 Commit

做一个功能,可能提交了 10 多次,会不会有一些崩溃?单纯这么多次的 commit 就可能出现有无用,或者可以合并的 commit,就很让人不舒服。

基于上面所说问题,不难想到:每一次功能开发, 对多个 commit 进行合并或者删除处理,这时候就需要用到 git rebase 修改提交的历史 Commit

Eg:

修改最近的 4 次提交纪录

git rebase -i HEAD~4
  • -i--interactive 的缩写 - 交互的意思;
  • HEAD~4 修改最近的 4 次提交记录; 然后在弹出的编辑器中显示 git-rebase-todo 文件,在 rebase-todo 中修改列表中的 pick 命令。
pick f77a6e7 version 0.1.3
pick 434a2f2 version 0.1.4
pick 094263b version 0.1.5
pick 9135476 version 0.1.5 change XXXX

# Rebase 50adf2a..9135476 onto 50adf2a (4 commands)
#
# Commands:
# p, pick <commit> = use commit   // 保留该commit
# r, reword <commit> = use commit, but edit the commit message  // 保留该commit,但修改该commit的注释
# e, edit <commit> = use commit, but stop for amending  // 保留该commit, 但我要停下来修改该commit
# s, squash <commit> = use commit, but meld into previous commit  // 将该commit合并到前一个commit
# f, fixup <commit> = like "squash", but discard this commit's log message  // 将该commit合并到前一个commit,并不要保留该提交的注释信息
# x, exec <command> = run command (the rest of the line) using shell  // 执行后边的shell命令
# b, break = stop here (continue rebase later with 'git rebase --continue')   //在这里停止,稍后使用 --continue 继续
# d, drop <commit> = remove commit  // 清除该commit
# l, label <label> = label current HEAD with a name // 使用label标记当前HEAD
# t, reset <label> = reset HEAD to a label  // 设置HEAD到标记的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.
#
# Note that empty commits are commented out

Eg:

我需要修改第二行和第三行的 Commit,那我将第二行和第三行的 pick 改成 edit 或 e,保存并退出。

git 会依次执行上面的操作,当操作为 pick 时,直接 commit。当操作为 edit 时,会中断,并提示

You can amend the commit now, with  // 你可以使用 git commit --amend 来修改此次提交

    git commit --amend

Once you are satisfied with your changes, run // 修改以后满意了,执行 git rebase --continue 继续剩下的流程

    git rebase --continue

全部修改完成以后提示如下:

$ git rebase --continue
Successfully rebased and updated refs/heads/master.

如果需要把修改的历史 commit push 到远程库中

使用 git push -f 命令即可

如果意外关闭了弹出的编辑窗口

如果 git 没有执行完操作,git rebase --edit-todo 命令可以返回编辑