Git修改/合并 提交历史
修改最后一次提交
场景:用户新增文件a,做了一次提交,提交消息为:“add file a”。
之后用户新增文件b。此时用户可以再次做一次提交,比如提交消息为“add file b”, 但这样做就有两条类似的消息,过于冗余可简化。
用户在第二次提交时执行 git commit --amend ,此刻能修改上次提交的消息,保存后两次提交会合并为一次提交。
合并提交
git rebase -i HEAD~3
运行这个命令会在文本编辑器上会看到一个 vim 界面
pick f7f3f6d changed my name a bit pick 310154e updated README formatting and added blame pick a5f4a0d added cat-file # Rebase 710f0f8..a5f4a0d onto 710f0f8 # # 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 # # 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
如果指定 “squash” 而不是 “pick” 或 “edit”,Git 将应用两者的修改并合并提交信息在一起。如果想把这三次提交变为一个提交,可以这样修改:
# 记住不要动最上面的那行 vim修改后记得保存 pick f7f3f6d changed my name a bit squash 310154e updated README formatting and added blame squash a5f4a0d added cat-file
:wq 保存并退出编辑器时,会显示另一个 vim 界面,Git 应用所有的三次修改放到编辑器中来合并三次提交信息:
# This is a combination of 3 commits. # The first commit's message is: changed my name a bit # This is the 2nd commit message: updated README formatting and added blame # This is the 3rd commit message: added cat-file
保存后就拥有了一个包含前三次提交的全部变更的提交。
最后使用 git log --oneline 确认所有这次开发中的 commit message 都被压缩成了一个。