/ git

git-history

修改最后一次提交

对于最近一次提交,我们往往想做两件事情:

  • 修改提交信息
  • 再添加文件、修改已经提交的文件、删除已经提交的文件
# 添加文件、修改已经提交的文件
git add file_modified file_new
# 删除已经提交的文件
git rm file_to_delete
修改提交的信息
git commit --amend

拆分最后一次提交

git reset HEAD^
git add file1
git commit -m 'Update the version1'
git add file2
git commit -m 'Update the version2'

修改多个提交

修改最后三次提交:

git rebase -i HEAD~3

可以进行的操作是

  • 重新排序提交
  • 压缩(合并)提交
  • 拆分提交

合并提交

为了便于他人阅读你的提交,也便于cherry-pick或撤销代码变化,在发起Pull Request之前,
应该把多个commit合并成一个。(前提是,该分支只有你一个人开发,且没有跟master合并过。)

当前我们有3个commit:

third  commit 32b1c2c13e055f089cef2edd393110ca13056e63
second commit 2b20ccfbf373a1210aadb75bcc310691b01bbcfd
first  commit fc280daf831b0306ade5908f5743eadb23ee80b8

如果需要将third commitsecond commit合并成一个,可以执行命令:

git rebase -i fc280da # first commit

其中 -i 的参数是操作范围的父commit(即first commit)的 hash 值

pick 2b20ccf second commit
pick 32b1c2c third commit

# Rebase fc280da..32b1c2c onto fc280da (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

合并,操作需要将 pick 改为 s 即可。其它操作可以按照 Commands 说明操作。

修改第一次提交

git rebase -i --root