问题中的两个例子实际上都是非常糟糕的例子,可能导致数据丢失!
我的建议是:永远不要在.gitignore文件的目录中添加/*,除非你有很好的理由!
一个很好的理由是,例如,Jefromi写道:“如果您打算随后取消忽略目录中的某些内容”。
不应该这样做的原因是,向目录追加/*一方面可以正确地忽略目录中的所有内容,但另一方面它有一个危险的副作用:
如果你在你的存储库中执行git stash -u(临时保存被跟踪和未跟踪的文件)或git clean -df(删除未跟踪的文件,但保留被忽略的文件),所有被忽略的目录加上/*将被不可逆地删除!
一些背景知识
I had to learn this the hard way. Somebody in my team was appending /* to some directories in our .gitignore. Over the time I had occasions where certain directories would suddenly disappear. Directories with gigabytes of local data needed by our application. Nobody could explain it and I always hat to re-download all data. After a while I got a notion that it might have to do with git stash. One day I wanted to clean my local repo (while keeping ignored files) and I was using git clean -df and again my data was gone. This time I had enough and investigated the issue. I finally figured that the reason is the appended /*.
我假设它可以通过以下事实来解释:目录/*忽略了目录的所有内容,而不是目录本身。因此,当内容被删除时,它既不会被认为是跟踪的,也不会被忽略。尽管git status和git status——ignored给出的图像略有不同。
如何繁殖
下面是如何重现这种行为。我目前使用的是Git 2.8.4。
将在本地git存储库中创建一个名为localdata/的目录,其中包含一个虚拟文件(important.dat),通过将/localdata/*放入.gitignore文件中,内容将被忽略。当现在执行上述两个git命令中的一个时,目录将(意外地)丢失。
mkdir test
cd test
git init
echo "/localdata/*" >.gitignore
git add .gitignore
git commit -m "Add .gitignore."
mkdir localdata
echo "Important data" >localdata/important.dat
touch untracked-file
如果你执行git status,这里忽略,你会得到:
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
untracked-file
Ignored files:
(use "git add -f <file>..." to include in what will be committed)
localdata/
现在不管怎样
git stash -u
git stash pop
or
git clean -df
在这两种情况下,据称被忽略的目录localdata将消失!
不确定这是否可以被认为是一个bug,但我猜它至少是一个没有人需要的功能。
我会把这个报告给git开发列表,看看他们是怎么想的。