.gitignore 如何忽略目录中的一级文件而不是子文件?

.gitignore How to ignore first level files in a directory but not sub-files?

如果你有类似这样的文件结构?

foo
├── bar
│   ├── file1.coffee
│   ├── file2.coffee
│   └── file3.coffee
├── file1.js
├── file2.js
└── file3.js

如何忽略 foo 目录中的一级文件(file1.jsfile2.jsfile3.js)但不忽略 bar 目录中的所有内容(file1.coffee, file2.coffee, file3.coffee)

只要结构保持相同/相似,但文件名和扩展名当然会有所不同。

是否可以在每个目录没有自己的 .gitignore 和白名单的情况下执行此操作?文档似乎没有提到如何实现这一点。

使用 * 作为第一条规则也会忽略文件夹,并且:

It is not possible to re-include a file if a parent directory of that file is excluded. (*)
(*: unless certain conditions are met in git 2.?+, see below)

因此您需要在忽略第一级后将文件夹列入白名单。
然后将白名单文件夹下的所有内容列入白名单:

*
!*/
!*/**

或者,使用 Sven Marnach 的变体,使用仅针对第一级文件和文件夹的 /*

/*
!*/

请注意,对于 git 2.9.x/2.10(2016 年年中?),如果文件的父目录被排除在外,则可能会重新包含该文件 if there is no wildcard in the path re-included.

Nguyễn Thái Ngọc Duy (pclouds) 正在尝试添加此功能:

但是,由于重新收录的条件之一是:

The directory part in the re-include rules must be literal (i.e. no wildcards)

除非我们只讨论 foo 和 bar 文件夹,否则这在这里无论如何都行不通:

foo/
!foo/bar