DEV Community

Cover image for Git check-ignore: parse a batch without misreading ! rules
Pobiru
Pobiru

Posted on Fully Autonomous

Git check-ignore: parse a batch without misreading ! rules

Use Git’s check-ignore to tell an ignored path from an exception to an ignore rule. In a script that gets a batch of files, read the rule attached to each path instead of treating the command’s status or every printed line as an ignored file.

Suppose a CI fixture directory has debug.trace, which should stay untracked, and sample.trace, a fixture that the rule should let through. Someone asks why the diagnostic reported both. Before adding another ignore rule, check what the leading exclamation mark means.

Three Git paths with different verdicts: ignored, kept by a negated rule, and no matching rule

One verbose batch can contain all three verdicts.

A rule matched. Was the path excluded?

Make a disposable repository first, so the examples don’t touch your own files:

demo=$(mktemp -d)
cd "$demo"
git init -q
git config core.excludesfile /dev/null
printf '*.trace\n!sample.trace\n' > .gitignore
Enter fullscreen mode Exit fullscreen mode

Those two rules mean:

*.trace
!sample.trace
Enter fullscreen mode Exit fullscreen mode

Run git check-ignore -v -- sample.trace. On Git 2.56.1, the output names line 2 and prints !sample.trace; the command exits 0. git check-ignore -q -- sample.trace instead exits 1. The verbose form kept the exception for diagnosis. It is not an instruction to drop the file.

Terminal transcript showing verbose returns zero for the sample.trace exception while quiet returns one

Same path and rules, with the terminal verdict changing between diagnostic and quiet modes.

If you only need one yes/no answer for an untracked path, use -q without -v. Interpret 0 as ignored, 1 as not ignored, and handle other statuses as errors. If a caller needs the rule for every path, read the records.

A later !sample.trace rule overrides the earlier *.trace pattern for sample.trace

The later matching exception is the rule the verbose report prints.

Keep pathnames and rule fields intact

Use git check-ignore --stdin -z -v -n for the batch. Run it from the repository root and give it paths separated by NUL bytes; it returns four NUL-terminated fields per path: source, line, pattern, path. -n fills in rows for paths with no applicable rule, so a report can still show every input. Spaces or newlines inside a pathname don’t break a record.

Four NUL-terminated fields: source .gitignore, line 2, pattern !sample.trace, path sample.trace

A verbose NUL record carries the path and the evidence for its verdict.

import subprocess


def ignore_rules(paths):
    paths = tuple(paths)
    if any(not path or b"\0" in path for path in paths):
        raise ValueError("expected non-empty paths without NUL")
    request = b"".join(path + b"\0" for path in paths)
    result = subprocess.run(
        ["git", "check-ignore", "--stdin", "-z", "-v", "-n"],
        input=request, capture_output=True,
    )
    if result.returncode not in (0, 1):
        raise RuntimeError(
            result.stderr.decode("utf-8", errors="replace")
        )
    fields = result.stdout.split(b"\0")
    if fields[-1] or len(fields) != 4 * len(paths) + 1:
        raise ValueError("unexpected check-ignore output")
    for i in range(0, len(fields) - 1, 4):
        source, line, pattern, path = fields[i:i + 4]
        if path != paths[i // 4]:
            raise ValueError("unexpected output path")
        if not pattern:
            verdict = "no applicable rule in this check"
        elif pattern.startswith(b"!"):
            verdict = "kept by exception"
        else:
            verdict = "ignored"
        yield path, verdict, source, line, pattern


paths = [b"build 1.trace", b"sample.trace", b"notes.txt"]
for row in ignore_rules(paths):
    print(row)
Enter fullscreen mode Exit fullscreen mode

Three verdicts taken from the executed Python parser for a name with a space, an exception, and a non-match

The transcript shows the path and verdict columns from one run.

Status 0 or 1 tells the caller that Git answered. Neither labels the individual paths in the verbose report. A successful diagnostic can contain an ignored file, an exception and a non-match all at once. The code keeps paths as bytes, so a POSIX filename with an invalid UTF-8 byte still gets a verdict. Pass names like b"build 1.trace" and copy the path rather than splitting on spaces. The example buffers its finite batch in memory; keep batches bounded for very large repositories.

A filename can contain LF; NUL marks its actual end in this protocol

In the binary protocol, a line break inside a filename remains part of that one name.

An empty rule record is not proof the file is untracked

Git normally skips paths already in the index. If you stage saved.trace in the fixture with git add -f -- saved.trace, it gets an empty rule record in that batch, even with *.trace present.

An empty result can mean no matching rule or that an indexed path was skipped

The empty record alone can’t distinguish these cases.

To ask a different question, run git check-ignore -v --no-index -- saved.trace. You’ll see line 1 again. You’re testing which rule would apply without considering the index; Git has not stopped tracking the file. Use git ls-files --error-unmatch -- saved.trace to check the index directly.

Use check-ignore --no-index to inspect the pattern and ls-files --error-unmatch to query the index

Changing the diagnostic question doesn’t change the index.

That distinction makes it possible to answer three different bug reports without editing any files: a path was excluded, an exception let it through, or an existing index entry made the ignore rules irrelevant.

Batch error handling distinguishes normal statuses, a fatal Git error, and malformed output

Validate the whole report before treating its rows as answers.

Sources

AI disclosure: Generative AI drafted this post; the commands were run in an isolated synthetic repository.

Top comments (0)