如何在Git中编辑合并提交的消息?

时间:2014-02-15 05:15:48

标签: git

浏览我的Git存储库的历史记录,我发现了一条错误的提交消息。 如何更改提交消息。

包含提交的分支已合并到另一个分支。 以下是简化模型库的历史记录:

*  (HEAD, A) Merge branch 'B' into A
|\  
| * (B) 3rd
| * 2nd [wrong]
|/  
* (master) 1st

我尝试了rebase,但它没有按预期工作:

$ git checkout B
$ git rebase -i HEAD~2

edit 2nd [wrong]
pick 3rd

$ git commit –-amend

2nd [correct]

$ git rebase --continue

结果是:

* (HEAD, B) 3rd
* 2nd [correct]
| *   (A) Merge branch 'B' into A
| |\  
|/ /  
| * 3rd
| * 2nd [wrong]
|/  
* (master) 1st

期望的结果是:

*  (HEAD, A) Merge branch 'B' into A
|\  
| * (B) 3rd
| * 2nd [correct]
|/  
* (master) 1st

1 个答案:

答案 0 :(得分:1)

git filter-branch如果你真的需要它。请记住,您将获得不同的提交图表上方2nd提交,并且您的所有用户都必须重新提交它。

您需要的命令如下所示(将< BAD COMMIT ID>替换为错误提交的实际sha1):

git filter-branch --msg-filter '
    if test "$GIT_COMMIT" = <BAD_COMMIT_ID>; then cat <<EOF
This is a fixed commit message summary

This is a body
EOF
else cat; fi'

使用gitk --all仔细检查结果。之前的git提交图保存在original/前缀下,如果需要,可以恢复。

这是我在一个简单的例子中所得到的:

alex@rhyme ~/tmp/git_repo $ git log --graph --oneline --all                               
*   3397c0e Merge 'B' into 'A'
|\  
| * 706c199 The third commit
| * c777ae4 The second commit
|/  
* 69e2e53 Initial commit

master位于69e2e53,B位于706c199,A位于3397c0e。

命令后

alex@rhyme ~/tmp/git_repo $ git filter-branch --msg-filter '                              
    if test "$GIT_COMMIT" = c777ae4b35f07f5cebcde93d4c716bfca9fdea94; then cat <<EOF
This is a fixed commit message summary

This is a body
EOF
else cat; fi' A B
Rewrite 3397c0e62f155d6273186a2120667517e60519dd (4/4)
Ref 'refs/heads/A' was rewritten
Ref 'refs/heads/B' was rewritten
alex@rhyme ~/tmp/git_repo $ _

我得到了以下图片:

*   5e1db15 Merge 'B' into 'A'
|\  
| * d238654 The third commit
| * 2f0fb9f This is a fixed commit message summary
|/  
| *   3397c0e Merge 'B' into 'A'
| |\  
|/ /  
| * 706c199 The third commit
| * c777ae4 The second commit
|/  
* 69e2e53 Initial commit

具有以下分支布局:

  1. master完好无损
  2. A重写为5e1db15
  3. B改写为d238654
  4. 3397c0e(以前的A)保存为original/refs/heads/A
  5. 706c199(以前的B)保存为original/refs/heads/B
  6. 请注意,由于其父提交已更改,因此在任何情况中A点和B点的更改都会更改。这就是为什么你得到原始提交图的副本。当您确保正确修改分支时,您可以删除original/*分支