从忘记恢复.gitignore

Ben*_*jol 9 git

git newbies似乎是一个常见的问题.

我忘了.gitignore一个特定的文件,并在提交之后将它添加到.gitignore没有任何区别.

在gitready上找到了这个页面,它解释了如何从存储库中删除文件而不将其从工作树中删除(通过使用命令git rm --cached <file>,该工作正常,但如果我然后尝试将其合并回另一个分支,则文件在工作树被删除.

在空文件夹上重现的步骤:

git init
touch want.txt
touch wantnot.txt
git add .
git commit -m "Initial"
git checkout -b BranchForIgnore
git rm --cached wantnot.txt
cat > .gitignore
wantnot.txt  [Ctrl-D Ctrl-D here to exit cat]
git add .
git commit -m "Ignoring file"
Run Code Online (Sandbox Code Playgroud)

到此为止,一切都很好

git checkout master
git merge BranchForIgnore
Run Code Online (Sandbox Code Playgroud)

此时,我的wantnot.txt文件不再是我的主人,显然,检查BranchForIgnore也无济于事.

该怎么办?

Jak*_*ski 7

我忘了.gitignore一个特定的文件,并.gitignore在提交后添加它没有任何区别.

嗯,当然不是.忽略是关于未跟踪文件(这意味着文件不受版本控制).

我在gitready上找到了一个页面,它解释了如何从存储库中删除文件而不将其从工作树中删除(通过使用命令git rm --cached <file>,该工作正常,但如果我然后尝试将其合并回另一个分支,那么文件在工作树被删除.

Git删除文件是因为你可以恢复它,因为它是在一个分支中跟踪的.

解决方案是在所有分支中提交"取消跟踪"文件(从版本控制中删除文件),使用git cherry-pickgit rm --cached <file> && git commit -a在单独的提交分支上进行,然后在所有分支中合并此主题分支(然后从跟踪版本恢复文件) .


Gre*_*ill 5

将文件重命名为临时名称(不使用 git),提交删除加上 .gitignore 文件,然后将文件重命名回其原始名称。

mv wantnot.txt wantnot.txt.tmp
git rm wantnot.txt
echo wantnot.txt >.gitignore
git add .gitignore
git commit -m "remove mistakenly committed wantnot.txt"
mv wantnot.txt.tmp wantnot.txt
Run Code Online (Sandbox Code Playgroud)

您为此使用单独的分支可能会不必要地混淆问题。