从未推送的Git提交中删除文件(但不是最后一个)

时间:2013-10-28 07:35:54

标签: git

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

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

2 个答案:

答案 0 :(得分:2)

您的情况

我用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

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

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

$ git rm .\webstormfile

提交清理后的索引:

$ git commit --amend --no-edit

完成变基:

$ git rebase --continue

答案 1 :(得分:0)

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

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