查找空的、未忽略的目录

Find empty, non-ignored directories

我想将 .gitkeep 文件添加到我的存储库中的所有空目录,但 到忽略的目录。我已经可以找到空目录:

$ find . -type d -empty

但是我怎么知道哪些被忽略了呢?它们可以被直接忽略,或者是被忽略目录的子目录......有没有办法直接从 git 获取此信息?类似于:

$ find . -type d -empty | git classify --stdin

ignored     : xxx
non-ignored : yyy

那就太好了。

您可以使用 git check-ignore 完成此任务。


假设您有一个具有以下结构的存储库:

foo/a.tmp
foo/b
bar/test/
baz/

还有这个.gitignore

foo/*.tmp
bar/

如果现在将 find . -type d -empty 的输出传递给 git check-ignore,您将收到以下输出:

$ find . -type d -empty | git check-ignore --stdin
./bar/test

您可以看到 git check-ignore returns 与您的 .gitignore 匹配的文件夹。更详细的输出可以使用-n(--non-matching)选项,需要结合-v(--verbose).

$ find . -type d -empty | git check-ignore --stdin -nv
::  ./.git/branches
::  ./.git/objects/info
::  ./.git/objects/pack
::  ./.git/refs/tags
.gitignore:1:bar/   ./bar/test
::  ./baz

要从搜索中排除 .git 文件夹,您可以向 find (documentation) 提供更多参数。

$ find . -type d -empty -not -path "./.git/*" | git check-ignore --stdin -nv
.gitignore:1:bar/   ./bar/test
::  ./baz

从这里开始,您可以简单地 grep 与您的 .gitignore 不匹配的文件夹并删除前导 :::

$ find . -type d -empty -not -path "./.git/*" | git check-ignore --stdin -nv | grep '::' | sed -E 's/::[[:space:]]*//'
./baz