2010-01-22 105 views
237

有办法更改消息从后承诺:在Git中编辑根提交?

git commit --amend     # for the most recent commit 
git rebase --interactive master~2  # but requires *parent* 

如何改变提交的消息,第一个提交(它没有父)?

+0

参见http://stackoverflow.com/questions/11987914/how-do-i-reword -th-first-git-commit-message – fork0

+0

特别是:在g脚本中使用GIT_COMMIT环境变量它过滤器分支--msg过滤器 – fork0

回答

221

假设你有一个干净的工作树,你可以做到以下几点。

# checkout the root commit 
git checkout <sha1-of-root> 

# amend the commit 
git commit --amend 

# rebase all the other commits in master onto the amended root 
git rebase --onto HEAD HEAD master 
+20

我相信这应该是'git rebase - 头HEAD master'。 – Andrew

+1

@Andrew:在这个例子中,“HEAD”是修改后的根提交。 –

+3

没错,但是你想让'git rebase'的的_original_ root提交。 'git rebase'应用('master')中的不在中的提交; 'HEAD'不在'master'中,所以你的版本试图应用所有'master'。 – Andrew

3

你可以使用git filter-branch

cd test 
git init 

touch initial 
git add -A 
git commit -m "Initial commit" 

touch a 
git add -A 
git commit -m "a" 

touch b 
git add -A 
git commit -m "b" 

git log 

--> 
8e6b49e... b 
945e92a... a 
72fc158... Initial commit 

git filter-branch --msg-filter \ 
"sed \"s|^Initial commit|New initial commit|g\"" -- --all 

git log 
--> 
c5988ea... b 
e0331fd... a 
51995f1... New initial commit 
+0

我使用过滤器分支更改作者/提交者,和' - --all'选项的确是在这种情况下的关键,能够也处理根提交。 – sschuberth

428

由于Git版本1.7.12,你现在可以使用

git rebase -i --root 
+23

我相信这应该是“接受的答案”,特别是它的简洁和清晰。 – Atcold

+5

同意,这应该是公认的答案。感谢你! –

+6

请接受此答案,而不是:) – marcio

53

要扩大ecdpalma's answer,你现在可以使用--root选项告诉rebase要重写根/第一承诺:

git rebase --interactive --root 

然后根承诺将在底垫TODO列表中显示出来,你可以选择要编辑或改写它:

reword <root commit sha> <original message> 
pick <other commit sha> <message> 
... 

这是--rootthe Git rebase docs(重点煤矿)的解释:

所有衍合提交可达来自<branch>,而不是用一个<upstream>限制他们。 这允许您重定义分支上的根提交

7

另一种方法来避免这个问题,如果你知道你上的在未来的“第一”的承诺,就是让空提交之初顶部基础重建:

git commit --allow-empty -m "Initial commit" 

和只有然后开始做“真正的”承诺,那么你可以很容易地重新分配上面的承诺标准方式使用......如git rebase -i HEAD^

+2

这不是说为了这个工作起作用,你需要有先见之明(或者是通灵)才能在你的项目开始时做出一个空的提交*?这对我来说似乎是***非常情境化的,而且一般来说***不实用***。你怎么看?如果我已经提交了100次提交,会发生什么,并且我突然需要编辑根提交。在这种情况下,如果我一开始并没有做出那么空的承诺,这仍然会起作用吗? – 2014-07-20 06:58:46

+1

编辑根提交的消息可能不是你在完成100次后执行的操作。我有时碰巧想要一个git repo,做一些无用的提交,知道一旦达到某种可用状态,我就会将它们压缩成一个,然后重新输入消息。 无论如何,现在我改变了主意,我认为对于第一次提交绝对最有用的事情是将'.gitattributes'文件替换为空提交。 –