git - 如何可靠地检查文件是否被 git 忽略?

标签 git bash gitignore

我遇到了一个问题 git check-ignore不尊重.gitignore的“不”(!)规则。如果文件与 .gitignore 中的任何条目匹配,它将返回“已忽略”文件,无论该条目是否告诉它不要忽略路径(通过 ! 运算符)

git check-ignore 's documentation声明返回代码映射如下:

EXIT STATUS

  • 0: One or more of the provided paths is ignored.
  • 1: None of the provided paths are ignored.
  • 128: A fatal error was encountered.

这与我在添加“请勿忽略”规则时看到的不符,即坚持 !在条目前面。

例如,让我们创建一个文件结构如下:

.gitignore
files/
    path-not-ignored
ignored-files/
    path-ignored
    path-not-ignored

和一个.gitignore包含:

ignored-files/*
!ignored-files/path-not-ignored

根据文档,我希望文件在 files/ 中和 ignored-files/path-not-ignored返回退出状态 1(未忽略)和 ignored-files/path-is-ignored返回 0(忽略)。

我在 ignored-files 中看到的不是所有内容返回退出状态 0(忽略):

File                             | Expected exit status | Actual exit status | Summary
-------------------------------- | -------------------- | ------------------ | -------
`files/path-not-ignored`         | 1 (Not ignored)      | 1 (Not ignored)    | Expected
`ignored-files/path-ignored`     | 0 (Ignored)          | 0 (Ignored)        | Expected
`ignored-files/path-not-ignored` | 1 (Not ignored)      | 0 (Ignored)        | Unexpected

(正在使用 git check-ignore <file>;echo $? 检查退出状态代码)

这不符合 Git 的内部行为,因为我可以 git add add ignored-files/path-not-ignored就好了:

File                             | `git add`?                   | Matches `git check-ignore` output?
-------------------------------- | ---------------------------- | ----------------------------------
`files/path-not-ignored`         | Adds file (as expected)      | Yes
`ignored-files/path-ignored`     | Throws warning (as expected) | Yes
`ignored-files/path-not-ignored` | Adds file (as expected)      | No


git status
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   files/path-not-ignored
    new file:   ignored-files/path-not-ignored

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

    .gitignore

作为git check-ignore在这种情况下是不可靠的,我可以使用任何其他命令来检查 Git 是否忽略/不忽略给定文件吗?

返回退出代码的东西是理想的,因为我在 bash 脚本中使用它。

最佳答案

使用 Git 2.18(2018 年 7 月)检查自 2017 年 7 月以来问题是否仍然存在。

Commit d60771e可能有助于消除误报。

check-ignore: fix mix of directories and other file types

In check_ignore(), the first pathspec item determines the dtype for any subsequent ones.
That means that a pathspec matching a regular file can prevent following pathspecs from matching directories, which makes no sense.

关于git - 如何可靠地检查文件是否被 git 忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45210790/

相关文章:

ios - Xcode 7 Git 找不到远程仓库

Git 生产/开发发布分支

string - 带引号和不带引号的 bash 字符串有什么区别

bash - 如何从 bash shell 脚本中的一行中提取一个单词

python - 类型错误:+ 不支持的操作数类型: 'int' 和 'NoneType'

visual-studio-2010 - Visual Studio gitignore 和 mdf、ldf 文件

git - 将克隆的 git 添加到个人 Gitlab

git - 忽略prepare-commit-msg git hook的 merge 提交

Git 忽略子目录中的文件

git - .gitignore,排除文件夹中的所有文件......但保留那些带有 .gitkeep 的子文件夹?