Git 忽略父目录中的 .gitignore 文件

Git ignoring .gitignore file in parent directory

我有这样的结构:

projects/
    .gitignore
    foo/
        some_file
    bar/
        another_file

foobar projects 是 git 个项目。在 .gitignore 我有 * (实际上我尝试了很多东西),但是当我在 projects/foo 里面 运行 git status 它仍然告诉我添加 some_file.如果我正确阅读 .gitignore 文档,它会说 Git 应该在所有父文件夹中查找 .gitignore 文件并使用它们。然而,它似乎完全忽略了 .gitignore 中的那个。这是怎么回事?

我试过 git check-ignore,它的表现就好像 .gitignore 不存在一样。

重现:

/ $ cd /tmp
/tmp $ mkdir projects
/tmp $ cd projects
/tmp/projects $ echo "*" > .gitignore
/tmp/projects $ git init
Initialized empty Git repository in /private/tmp/projects/.git/
/tmp/projects $ mkdir foo
/tmp/projects $ cd foo
/tmp/projects/foo $ git init
Initialized empty Git repository in /private/tmp/projects/foo/.git/
/tmp/projects/foo $ touch some_file
/tmp/projects/foo $ git status
On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    some_file

nothing added to commit but untracked files present (use "git add" to track)

哦...它只读取它们 up to the top level of the git repository:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory, with patterns in the higher level files (up to the toplevel of the work tree)

措辞不佳但还可以。

Git 仅使用 .gitignore 文件 当前存储库 中的规则。如果您希望它应用于所有子存储库,您可能需要 symlink 或 hard link 将 .gitignore 文件从父目录复制到所有子目录。

随着 Git 2.33(2021 年第 3 季度)阐明 .gitignore 检测:

参见 commit e041706 (06 Jul 2021) by Andrew Berry (deviantintegral)
(由 Junio C Hamano -- gitster -- in commit bb3a55f 合并,2021 年 7 月 22 日)

docs: .gitignore parsing is to the top of the repo

Signed-off-by: Andrew Berry

The current documentation reads as if .gitignore files will be parsed in every parent directory, and not until they reach a repository boundary.
This clarifies the current behaviour.

As well, this corrects 'toplevel' to 'top-level', matching usage for 'top-level domain'.

gitignore 现在包含在其 man page 中:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory (up to the top-level of the working tree), with patterns in the higher level files being overridden by those in lower level files down to the directory containing the file.

These patterns match relative to the location of the .gitignore file.

由于您在 /private/tmp/projects/foo/.git/ 中初始化了一个嵌套的 Git 存储库,projects/ 中的 .gitignore 本身将被忽略。