这个问题在这里已经有答案了:

我想在项目的第一次提交中更改某些内容,而不丢失所有后续提交。有什么办法可以做到这一点吗?

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

有帮助吗?

解决方案

正如所提到的 外皮帕尔马 以下, git 1.7.12+ (2012 年 8 月)增强了选项 --root 为了 git rebase:

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

这种新行为最初是 在这里讨论:

我个人认为“git rebase -i --root“应该让其正常工作而不需要”--onto”,甚至让你“编辑”历史上的第一个。
没有人打扰是可以理解的,因为人们在历史刚开始时重写的次数比其他时候要少得多。

补丁已跟进.


(原始答案,2010 年 2 月)

正如在 Git 常见问题解答 (和这个 那么问题),其思路是:

  1. 创建新的临时分支
  2. 将其倒回到您想要更改的提交 git reset --hard
  3. 更改该提交(它将位于当前 HEAD 的顶部,您可以修改任何文件的内容)
  4. 使用以下命令在更改的提交之上重新设置分支:

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

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

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

其他提示

如中所述 1.7.12 发行说明, ,你可以使用

$ git rebase -i --root

git rebase -i 允许您方便地编辑任何以前的提交, 除了 root 提交. 。以下命令向您展示如何手动执行此操作。

# 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

如果你只想修改第一个提交,你可以尝试 git rebase 并修改提交,类似于这篇文章:如何修改git中指定的commit?

如果您想修改包含原始电子邮件的所有提交,filter-branch 是最佳选择。书上有一个如何全局更改电子邮件地址的示例 专业版 Git, ,您可能会发现此链接很有用 http://git-scm.com/book/en/Git-Tools-Rewriting-History

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top