我有以下提交历史记录:
头部头部~头部~2头部~3
gitcommit--修改当前HEAD提交。但是如何修改HEAD~3?
我有以下提交历史记录:
头部头部~头部~2头部~3
gitcommit--修改当前HEAD提交。但是如何修改HEAD~3?
当前回答
如果您还没有推送提交,则可以使用git reset HEAD^[1,2,3,4…]返回到上一次提交
例如
git commit <file1> -m "Updated files 1 and 2"
git commit <file3> -m "Updated file 3"
抱歉,忘记在第一次提交时添加file2。。。
git reset HEAD^1 // because I only need to go back 1 commit
git add <file2>
这将在第一次提交时添加file2。
其他回答
当我需要更深入地修复历史中以前的提交时,我经常使用交互式rebase和--autosquash。它本质上加快了ZelluX的回答所说明的过程,当您需要编辑多个提交时,它特别方便。
根据文档:
--自动撤销当提交日志消息以“squash…“(或”修复…“),并且有一个提交的标题以相同的开头…, 自动修改rebase-i的todo列表,以便标记为挤压的提交在要修改的提交之后立即出现
假设您的历史记录如下:
$ git log --graph --oneline
* b42d293 Commit3
* e8adec4 Commit2
* faaf19f Commit1
并且您有要修改为Commit2的更改,然后使用
$ git commit -m "fixup! Commit2"
或者,您可以使用commit sha而不是commit消息,因此“fixup!e8adec4”或甚至只是commit消息的前缀。
然后在提交之前启动交互式重新基础
$ git rebase e8adec4^ -i --autosquash
编辑器将打开已正确排序的提交
pick e8adec4 Commit2
fixup 54e1a99 fixup! Commit2
pick b42d293 Commit3
你只需要保存并退出
如果出于某种原因,您不喜欢交互式编辑器,可以使用gitrebase--on。
假设您要修改Commit1。首先,从Commit1之前分支:
git checkout -b amending [commit before Commit1]
第二,用樱桃核抓取Commit1:
git cherry-pick Commit1
现在,修改您的更改,创建Commit1':
git add ...
git commit --amend -m "new message for Commit1"
最后,在隐藏了任何其他更改后,将其余的提交移植到master之上新提交:
git rebase --onto amending Commit1 master
阅读:“将Commit1(不包括在内)和master(包括在内)之间的所有提交重新纳入修改分支”。即Commit2和Commit3,将旧的Commit1完全删除。你可以随便摘,但这样更容易。
记得清理你的树枝!
git branch -d amending
git存储+再基础自动化
因为当我需要多次修改Gerrit审查的旧提交时,我一直在做:
git-amend-old() (
# Stash, apply to past commit, and rebase the current branch on to of the result.
current_branch="$(git rev-parse --abbrev-ref HEAD)"
apply_to="$1"
git stash
git checkout "$apply_to"
git stash apply
git add -u
git commit --amend --no-edit
new_sha="$(git log --format="%H" -n 1)"
git checkout "$current_branch"
git rebase --onto "$new_sha" "$apply_to"
)
GitHub上游。
用法:
修改源文件,如果已在repo中,则无需gitaddgit修改旧$old_sha
我很喜欢这一点,因为它不会挤压其他无关的修复。
更改上次提交:
git commit --amend
// or
git commit --amend -m "an updated commit message"
不修改公共承诺修改后的提交实际上是全新的提交,以前的提交将不再位于当前分支上。
例如,如果您想更改最后三个提交消息或该组中的任何一个提交消息,您可以向git rebase-i提供一个参数,该参数是您要编辑的最后一个提交的父级,即HEAD~2^或HEAD~3。记住~3可能更容易,因为您正在尝试编辑最后三次提交,但请记住,您实际上是在指定四次提交之前,即您要编辑的最后一次提交的父级:
$ git rebase -i HEAD~3
了解更多信息
基于文档
修改旧的或多个提交消息的消息
git rebase -i HEAD~3
上面显示了当前分支上最后3次提交的列表,如果需要更多,请将3更改为其他内容。列表将类似于以下内容:
pick e499d89 Delete CNAME
pick 0c39034 Better README
pick f7fde4a Change the commit message but push the same commit.
将pick替换为要更改的每个提交消息之前的改写。假设您更改了列表中的第二个提交,您的文件将如下所示:
pick e499d89 Delete CNAME
reword 0c39034 Better README
pick f7fde4a Change the commit message but push the same commit.
保存并关闭提交列表文件,这将弹出一个新的编辑器,供您更改提交消息、更改提交消息并保存。
最后,强制推行修改后的承诺。
git push --force