【问题标题】:Remove files from un-pushed Git commit (but not last one)从未推送的 Git 提交中删除文件(但不是最后一个)
【发布时间】:2013-11-06 21:37:33
【问题描述】:

我刚刚发现,在过去的提交中,我包含了不应该在存储库中的文件(.idea Webstorm 文件和其他文件)。这个提交“位于中间”,在它之前和之后都有未推送的提交。此外,在此提交中确实需要提交并在以后(未推送)提交中进一步修改的文件。

我已经看到了这些答案:Completely remove file from all Git repository commit historyRemove files from Git commit,但它们似乎没有回答我的具体问题。解决办法是什么?

【问题讨论】:

    标签: git


    【解决方案1】:

    你的情况

    我正在使用 3 个未推送的提交来创建您描述的情况:

    $ git clone <url>
    $ touch file1
    $ git add file1
    $ git commit -m "Correct 1st commit"
    $ touch file2
    $ touch webstormfile
    $ git add .
    $ git commit -m "Wrong 2nd commit with by mistake included WebStorm file"
    $ touch file3
    $ git add file3
    $ git commit -m "Correct 3rd commit"
    $ git log --oneline
    $
    $ ad73bfa Correct 3rd commit
    $ eddae38 Wrong 2nd commit with by mistake included WebStorm file
    $ ad219bf Correct 1st commit
    

    删除提交的 WebStorm 文件

    注意:以下步骤将更改历史记录,这意味着,如果提交已被推送,更改历史记录将破坏所有团队成员的存储库。如果您还没有推送,您可以按照步骤操作,而不会打扰您的团队成员。

    开始交互式变基,包括错误提交的哈希 eddae38

    $ git rebase -i eddae38^
    

    文本编辑器弹出如下内容:

    pick eddae38 Wrong 2nd commit with by mistake included WebStorm file
    pick ad73bfa Correct 3rd commit
    
    # Rebase ad219bf..ad73bfa onto ad219bf
    #
    # Commands:
    #  p, pick = use commit
    #  r, reword = use commit, but edit the commit message
    #  e, edit = use commit, but stop for amending
    #  s, squash = use commit, but meld into previous commit
    #  f, fixup = like "squash", but discard this commit's log message
    #  x, exec = run command (the rest of the line) using shell
    #
    # These lines can be re-ordered; they are executed from top to bottom.
    #
    # If you remove a line here THAT COMMIT WILL BE LOST.
    #
    # However, if you remove everything, the rebase will be aborted.
    #
    # Note that empty commits are commented out
    

    在第一行,将pick更改为edit,保存文件并关闭文本编辑器。

    注意!如果要保留它,请复制您的 WebStorm 文件。然后,从提交中删除 WebStorm 文件:

    $ git rm .\webstormfile
    

    提交清理后的索引:

    $ git commit --amend --no-edit
    

    完成变基:

    $ git rebase --continue
    

    【讨论】:

    • 或者使用git rm --cached .\webstormfile 代替,这样它就不会在本地被删除。很好的答案!
    【解决方案2】:

    使用另一个提交删除文件,然后在最后一次推送的提交上运行 git rebase -i 并用删除文件的提交压缩错误的提交

    请务必备份您的文件,因为您将需要它们。提交修复后,恢复文件并将它们添加到.gitignore 以防止进一步提交

    【讨论】:

    • 不要轻易这样做;它会重写历史,其他任何使用你的仓库的人都会非常困惑和恼火。
    • @Eevee,你是对的,但是 OP 指定了错误的提交和周围的提交是 unpushed ...我认为这里没有问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 2019-11-28
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多