Git stash 恢复被忽略的文件

4

我之前在git上提交了一些错误的文件。之后,我将这些文件排除和忽略:

git rm --cached -r config.php
git reset config.php
echo "config.php" >> .gitignore
git update-index --assume-unchanged config.php

现在git commit很好用。config.php中的更改不会被提交。
但是:如果我储藏工作目录,例如切换分支,那么config.php会从本地存储库中恢复。
如何在不更改被忽略(并从索引中排除)的文件的情况下使用git stash?

你在将config.php添加到.gitignore后进行了提交吗? - usha
是的,.gitignore已经提交。 - dieisraels
2个回答

0

编辑回答

你使用了 git rm --cached -r config.php,但没有提交这个更改。

接下来你执行了 git reset config.php,这清除了之前的 git rm 的效果,导致现在回到了起点。

然后,你将 config.php 添加到了 .gitignore,但由于 config.php 目前仍被跟踪,所以这不会有任何影响。

最后,你执行了 git update-index --assume-unchanged config.php,这使得如果你执行 git statusgit diff 命令时本地看不到任何更改。这些步骤让你误以为 git rm.gitignore 起作用了,但实际上并没有。

相反,请按照以下步骤操作(-r 标志是多余的,因为它不是一个目录)

git rm --cached config.php
echo config.php >> .gitignore && git add .gitignore
git commit -m "removing config.php"

原始答案

但是:如果我将工作目录存储起来以切换分支,那么 config.php 将从本地仓库中恢复。

好的,你刚刚从当前分支(我们称其为 master)中删除了 config.php,但另一个分支 other 仍然在跟踪它。这就是为什么你能看到它。这与 git stash 没有任何关系。

你应该将分支 master 合并到 other 分支中,以将提交合并到 other 分支中。


我认为不是这样的:在第二个分支上运行 git status 没有列出更改的文件。此外,忽略该文件后才创建了第二个分支。 - dieisraels

0
我在https://help.github.com/articles/remove-sensitive-data找到了一个解决方案:
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch config.php' \
--prune-empty --tag-name-filter cat -- --all

可能需要进行一次 reset 操作,以将其从未来的提交中排除:

git reset config.php

在删除了本地分支中的config.php的所有信息后,我进行了强制推送以更新远程仓库:

git push origin master --force

现在,我的暂存区正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接