2010-02-11 71 views
328

我想在我的项目的第一次提交中更改某些内容,而不会丢失所有后续提交。有没有办法做到这一点?用Git改变项目的第一次提交?

我不小心在源代码中的评论中列出了我的原始电子邮件,我想更改它,因为我收到了垃圾邮件索引GitHub的垃圾邮件。

回答

484

正如ecdpalmabelow提到,git 1.7.12+(2012年8月),加强了选项--rootgit rebase

git rebase [-i] --root $tip”现在可用于将所有导致“$tip”的历史重写为根提交。

这种新的行为最初discussed here

我个人认为“git rebase -i --root”提出,而不需要“--onto”,只是工作,让你的“编辑”甚至在历史上是第一个。
可以理解的是,没有人会打扰,因为人们在历史的开端附近重写的次数比其他的次数少得多。

patch followed


(原来的答复,2010年2月)

正如Git FAQ(这SO question)提到,这个想法是:

  1. 创建新的临时党支部
  2. 倒到提交你想要改变使用git reset --hard
  3. 改变提交(这将是当前头顶,你可以修改任何文件上的改变提交顶部的内容)
  4. 衍合分支,使用:

    git rebase --onto <tmp branch> <commit after changed> <branch>` 
    

的窍门是一定要删除不是由一个重新的信息后提交您文件中的其他位置。如果您怀疑,那么您必须使用filter-branch --tree-filter以确保该文件的内容在任何提交中都不包含合理的信息。

在这两种情况下,最终都会重写每次提交的SHA1,因此如果您已经发布了要修改内容的分支,请注意。你可能不应该这样做,除非你的项目尚未公开,而其他人没有从你将要改写的提交中找到工作。

+4

在OS X山狮与系统安装的git 1.7.9.6(苹果的Git-31.1)我设置'<提交变更后>'来与'git reset --hard'命令中使用的相同。除了这样一个小小的改变之外,这个功能非常漂亮,可以在回购的所有提交中更新作者信息。 – berto 2012-12-30 01:28:46

+4

你可以提供什么应该是$提示的例子。 'git rebase -i --root'为我工作。 – 2015-06-04 17:12:33

+0

@RémiBenoit是的,'$ tip'可以是你想要的任何提交。 'master'(意思是'master HEAD' commit)很好。 – VonC 2015-06-04 17:13:51

71

git rebase -i可以让你方便地编辑任何以前提交,除了根提交。以下命令显示如何手动执行此操作。

# tag the old root, "git rev-list ..." will return the hash of first commit 
git tag root `git rev-list HEAD | tail -1` 

# switch to a new branch pointing at the first commit 
git checkout -b new-root root 

# make any edits and then commit them with: 
git commit --amend 

# check out the previous branch (i.e. master) 
git checkout @{-1} 

# replace old root with amended version 
git rebase --onto new-root root 

# you might encounter merge conflicts, fix any conflicts and continue with: 
# git rebase --continue 

# delete the branch "new-root" 
git branch -d new-root 

# delete the tag "root" 
git tag -d root 
+10

我像n00b一样遵循了这些指示,他们完美地工作 - 谢谢!你可能想提一下在'git commit --amend'中添加'-a'或者使用'git add',因为我第一次忘记了! – 2012-11-11 14:42:04

+1

这不再是真实的,请参阅接受的答案 – 2016-05-10 12:41:45

+0

非常感谢您的回答。我使用的是Centos 7,git版本是1.7.1,对命令有很多限制。 接受的答案不适用于我和这_ _ **如何** _工作像一个魅力来重建从_ **初始提交**版本库历史** _ – 2016-07-04 21:25:13

126

正如1.7.12 Release Notes说,你可以使用

$ git rebase -i --root 
+2

git版本1.7.9抱怨:'你必须指定 - - 使用时--root' – 2014-06-03 15:14:49

+2

它可以正常使用git 1.9.4 – 2014-09-17 20:06:00

+2

工作对我来说也很棒,使用git 1.9.4。 – 2014-11-17 06:27:04