用Git更改项目的第一次提交?

Mic*_*ael 476 git rebase git-filter-branch

我希望在我的项目的第一次提交中更改某些内容而不会丢失所有后续提交.有没有办法做到这一点?

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

Von*_*onC 724

正如提到的ecdpalma 下面,GIT中1.7.12+(2012年8月)具有增强的选项--rootgit rebase:

" git rebase [-i] --root $tip"现在可用于重写所有导致" $tip"到根提交的历史记录.

这个新行为最初在这里讨论:

我个人认为" git rebase -i --root"应该只是工作而不需要" --onto",让你"编辑"甚至是历史上的第一个.
可以理解的是,没有人会感到困扰,因为人们在历史的最初阶段重写的次数要少得多.

随后是补丁.


(原答案,2010年2月)

正如Git FAQ(和这个SO问题)中提到的,这个想法是:

  1. 创建新的临时分支
  2. 将其回滚到您要使用的更改提交 git reset --hard
  3. 更改提交(它将是当前HEAD的顶部,您可以修改任何文件的内容)
  4. Rebase分支在更改提交之上,使用:

    git rebase --onto <tmp branch> <commit after changed> <branch>`
    
    Run Code Online (Sandbox Code Playgroud)

诀窍是确保您要删除的信息不会被文件中其他位置的后续提交重新引入.如果您怀疑,那么您必须使用filter-branch --tree-filter以确保该文件的内容在任何提交中都不包含敏感信息.

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

  • 在OS X Mountain Lion上安装了系统安装的git 1.7.9.6(Apple Git-31.1)我将`<commit after changed>`设置为与我在`git reset --hard`命令中使用的哈希相同.除了一个小的改动之外,这可以很好地在回购中的所有提交中更新作者信息. (5认同)
  • 你能提供一些应该是$ tip的例子吗?`git rebase -i --root`为我工作. (4认同)

cmc*_*nty 81

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
Run Code Online (Sandbox Code Playgroud)

  • 我按照这些说明就像一个n00b,他们工作得很完美 - 谢谢!您可能想提及将`-a`添加到`git commit --amend`或使用`git add`,因为我第一次忘记了! (11认同)
  • 这不再是真实的,请参考已接受的答案 (2认同)