在.gitignore路径匹配语法中,前导星号“** /”是多余的吗?

时间:2017-01-20 10:16:39

标签: git gitignore glob

是否存在任何不能用没有星号的等价物替换的用法?

Two consecutive asterisks ("**") in patterns matched against full
pathname may have special meaning:

A leading "**" followed by a slash means match in all directories.
For example, "**/foo" matches file or directory "foo" anywhere,
the same as pattern "foo". "**/foo/bar" matches file or directory
"bar" anywhere that is directly under directory "foo".

A trailing "/**" matches everything inside. For example, "abc/**"
matches all files inside directory "abc", relative to the location
of the .gitignore file, with infinite depth.

A slash followed by two consecutive asterisks then a slash matches
zero or more directories. For example, "a/**/b" matches "a/b",
"a/x/b", "a/x/y/b" and so on.

Other consecutive asterisks are considered invalid.

https://git-scm.com/docs/gitignore#_pattern_format

让我指出,我只询问领先的星号/斜线冗余。由于似乎任何**/foo/bar都可以被简单的foo/bar

取代

例如,我的.gitignore文件中包含以下内容:

# NuGet Packages

# The packages folder can be ignored because of Package Restore
**/packages/*

# except build/, which is used as an MSBuild target.
!**/packages/build/

# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config

我想知道,为什么他们不能简单地写:

# NuGet Packages

# The packages folder can be ignored because of Package Restore
packages/*

# except build/, which is used as an MSBuild target.
!packages/build/

# Uncomment if necessary however generally it will be regenerated when needed
#!packages/repositories.config

https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

2 个答案:

答案 0 :(得分:4)

不,如果剩余的模式不包含斜杠,则前导**/只会过时。

https://git-scm.com/docs/gitignore中的文档在我看来有点误导,因为它声明了

If the pattern does not contain a slash /, Git treats it as a shell glob
pattern and checks for a match against the pathname relative to the
location of the .gitignore file (relative to the toplevel of the work
tree if not from a .gitignore file).

但实际上只匹配文件或目录的名称,而不是整个路径。

所以**/packages/build在任何深度都匹配packages/build packages/build因为它包含斜杠实际上与/packages/build相同,并且只在与忽略文件相同的级别上匹配packages/build

另一方面,build匹配任何深度的build,因此实际上与**/build相同。
/build仅匹配与忽略文件相同级别的build

它总是取决于模式(在删除尾部斜杠后如果存在)是否包含任何斜杠。

答案 1 :(得分:0)

该问题中存在一个错误的假设(但由于编辑而不再存在)。演示问题:

$ mkdir tignore
$ cd tignore
$ git init
Initialized empty Git repository in .../tignore/.git
$ git status -uall --short
$ mkdir sub sub/foo; touch sub/foo/bar; echo foo/bar > .gitignore; git status -uall -s
?? .gitignore
?? sub/foo/bar
$ echo '**/foo/bar' > .gitignore; git status -uall -s
?? .gitignore
$ 

换句话说,要让Git忽略子目录foo/bar中的文件sub,我们必须在顶层**/foo/bar中写.gitignore,因为{{1 }} 不匹配foo/bar匹配。

请注意,规则不包含不包含斜杠的忽略条目。即:

sub/foo/bar

在这里,我们不需要需要前导$ echo bar > .gitignore $ git status -uall -s ?? .gitignore $ 。因此,当要忽略的名称​​不包含其自己的嵌入式**/时,前导**/是多余的,但是当要被忽略的名称时,不是多余被忽略的 包含其自己的嵌入式/

要进一步处理有些奇怪的/规则,请参阅gitignore rules (applied to a codeigniter stack)