Skip to content

Resolve .gitignore files the way git does (#5376) - #5453

Open
santhosh220z wants to merge 6 commits into
psf:mainfrom
santhosh220z:fix/nested-gitignore-negation
Open

santhosh220z wants to merge 6 commits into
psf:mainfrom
santhosh220z:fix/nested-gitignore-negation

Conversation

@santhosh220z

@santhosh220z santhosh220z commented Sep 29, 2026 •

Copy link
Copy Markdown

Summary

Fixes the silent-skip bug in #5376 (and #3694): a negation in a nested .gitignore can never re-include something an ancestor excluded, so black --check . exits 0 without a word about files git actually tracks.

This now also covers the case raised in review, where a nested negation that re-includes a directory must not speak for the files inside it.

Credit

KaizenShogun identified the divergence in #5376, proposed the approach, measured it against a fuzz harness (4,938 queries over 500 generated nested-gitignore trees, 99.96% agreement with git check-ignore), and offered to file this PR themselves. I didn't see that offer until after I had implemented and verified the first version, so this is their approach rather than an independent one, and their writeup in the issue thread is better than mine. What this PR adds: Black's test suite actually run, the in-review gap closed, and the reviewer-reported case pinned as a fixture.

The change

_path_is_ignored in src/black/files.py walked gitignore_dict shallowest-first and returned on the first hit. That had two defects, addressed in two commits.

1. Which file decides. An ancestor's exclusion short-circuited before any nested file could vote, so ! was unreachable. Also, a nested negation fell through, because match_file returns a plain bool and can't tell "negated" from "no pattern matched", so a re-inclusion could be overridden by a shallower file. Fixed by walking in reverse and letting the closest .gitignore that names the path decide.

2. What counts as a match. pathspec reports a match when a pattern matches the path or a directory above it, because git prunes an excluded directory rather than testing the files inside it. That is right for the combined list of every pattern git consults, but wrong for asking whether one .gitignore has an opinion about one path:

.gitignore     ->  build_cache
                  *_pb2.py
pkg/.gitignore ->  !playground/build_cache
pkg/playground/build_cache/msg_pb2.py

!playground/build_cache matches every file under playground/build_cache, so commit 1 returned there and never asked the root about *_pb2.py. git ignores that file — the root pattern is the only one that names it. Commit 2 requires a pattern to name the path itself before it gets a say.

pathspec's compiled regex already distinguishes the two: it matches ^pattern(?:(?P<ps_d>/)|$), so a match that captured the ps_d separator only covered a prefix of the path, while one that did not reached the end of it. The catch-all patterns (*, **, */, **/) are special-cased by pathspec into a bare regex with no such group and always name their path directly.

I did not take the "concatenate the patterns and do one last-match-wins pass" alternative floated in the thread: it does not fix this, because check_file applies the same directory propagation internally, so the deep negation still overrides the shallow direct exclusion.

Why directory pruning stays

_path_is_ignored also decides directories, so the re-inclusion works without touching gen_python_files: a directory is skipped only when nothing deeper re-included it, and descended into when a nested .gitignore does. That preserves git's rule that a path under an excluded parent cannot be re-included, so a .gitignore inside an ignored directory stays inert.

Verification

Ground truth is git add --dry-run (git 2.55.0), diffed against Black's collected sources. All 6 fixture trees and 17 of 18 constructed trees agree.

root .gitignore nested .gitignore path git before after
.vscode !playground/.vscode playground/.vscode/settings.py tracked skipped collected
.vscode build plain/.vscode/other.py skipped skipped skipped
.vscode build, !playground/.vscode plain/.vscode/other.py skipped skipped skipped
.vscode !*.vscode plain/.vscode/other.py tracked skipped collected
build !keep.py in build/ build/keep.py skipped skipped skipped
build, !keep.py other.py in build/ build/keep.py skipped skipped skipped
build_cache, *_pb2.py !playground/build_cache …/msg_pb2.py skipped collected skipped
build_cache, *_pb2.py !playground/build_cache …/msg_other.py tracked skipped collected

Rows 1 and 7–8 are the two bugs. Rows 2–3 are the "just reverse the loop" trap. Rows 5–6 are why pruning stays. Row 8 is also wrong on main, in the other direction: main ignored msg_other.py, because it took the root's transitive build_cache match as an answer about a file that pattern does not name.

The three real-world shapes named in the report — facebook/react (!playground/.vscode), python/cpython (!.idea/), supabase/supabase (!volumes/functions/deno.json*) — all agree now. One caveat on the last: it diverges only for deno.json files, which Black doesn't format, so my reconstruction yields no .py files before or after. It confirms Black isn't over-including rather than that repo being unblocked.

Tests

480 passed, 4 skipped, 3 failed, 8 subtests. The 3 failures need a Windows symlink privilege this machine lacks and fail identically on main. black --check, ruff and mypy are unchanged from baseline.

⚠️ If you run the tests locally: a separately installed mypyc-compiled black in site-packages shadows src/, so you would be testing the released binary. Use PYTHONPATH=src.

Known remaining divergence, pre-existing

**/gen/** in the root plus !gen/keep.py in pkg/, file pkg/gen/keep.py: git tracks it, Black does not, and this is unchanged from main — I verified by stashing the change.

Black evaluates a directory by appending / to its path, which is required for dir-only patterns (build/ matches nothing otherwise) but makes dir/** patterns match the directory itself, which git does not do — git's abc/** matches everything inside abc, not abc. pathspec actually agrees with git on the bare path here (check_file("pkg/gen") → no match; check_file("pkg/gen/") → match), so the trailing slash is the whole cause. No single convention satisfies both cases — build/ needs the slash and **/gen/** must not have it — so a fix has to choose per pattern. That is a separate bug from this issue and I have deliberately left it alone rather than widen the diff.

I also did not add the "negated re-include of a file whose directory is excluded" case proposed earlier in the thread: that expectation is the opposite of git, and selfneg/ in the first fixture pins the correct behaviour instead.

santhosh220z added a commit to santhosh220z/black that referenced this pull request Sep 29, 2026
@mathewOracle

Copy link
Copy Markdown

Thanks for this, the deepest-file-wins direction looks right for the #5376 case. While checking it against git check-ignore, I hit a case where this PR goes the other way and un-ignores files that git ignores, and that main currently ignores correctly.

The cause is that returning on the first .gitignore with a non-None result stops the walk. A nested negation that re-includes a directory then decides everything under that directory, including files that a separate, unrelated pattern in an ancestor .gitignore excludes.

Repro (pathspec 1.1.1):

.gitignore        ->  build_cache
                      *_pb2.py
pkg/.gitignore    ->  !playground/build_cache
pkg/playground/build_cache/msg_pb2.py
pkg/playground/build_cache/msg_pb2.py
git check-ignore -v ignored (.gitignore:2:*_pb2.py)
main (_path_is_ignored) ignored
this PR (_path_is_ignored, logic copied verbatim) not ignored (Black would now format it)

check_file("playground/build_cache/msg_pb2.py") on pkg/.gitignore returns include=False, because !playground/build_cache (no trailing slash, no anchoring after the first /) also matches paths under it. The loop returns there and never asks the root file about *_pb2.py.

What git actually does, as far as I understand it: every pattern from every applicable .gitignore goes into one ordered list (shallower files first, deeper files later), and the last matching pattern across that whole list wins. The directory-exclusion rule is applied separately, during traversal. So a fix might be "walk deepest-first, but only treat a negation as decisive if that negation matched the path itself, not a parent directory". Another option is to concatenate the patterns with each file's base rewritten and let pathspec do a single last-match-wins pass.

Might be worth adding this as a third fixture alongside pkg/other and selfneg, since none of the current ones has a second, independent exclusion pattern in the ancestor file.

I used an AI assistant to help explore this; I reproduced the git and Python results above myself.

@github-actions

github-actions Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

diff-shades results comparing this PR (1dec3a6) to main (8d5a2d9):

--preview style: no changes

--stable style: no changes


What is this? | Workflow run | diff-shades documentation

@santhosh220z

Copy link
Copy Markdown
Author

i have reworked on it i have fixed the issue can you check it again and update me if anything is wrong or needs fixing please inform me

and i apologize not responding quickly

_path_is_ignored walked the .gitignore files shallowest-first and returned
True on the first hit, so an ancestor's exclusion short-circuited before
any nested file could say `!`. Black's ignore handling therefore ORed the
files together, and the deepest one -- the only one that can re-include --
was functionally shadowed.

Git resolves this per path: the closest .gitignore decides, and shallower
ones are only asked when no deeper file has a matching pattern. So walk
the dict in reverse and let the first file with a match decide, using
check_file to tell "this file has no matching pattern, ask the one above"
apart from "this file matched a negation". Last-match-wins within a single
file is already pathspec's job.

Because directories go through the same function, pruning needs no change:
a directory is skipped only when nothing deeper re-included it, and
descended into when a nested .gitignore does. That keeps git's rule that a
path whose parent directory is excluded cannot be re-included, so a
.gitignore inside an ignored directory stays inert.

The effect is that black no longer silently skips files git tracks;
`black --check` on such a tree used to exit 0 without a word.
The previous commit stopped at "the closest .gitignore with a matching pattern
decides", which is right about which file gets to decide but wrong about what
counts as a match. pathspec reports a match when a pattern matches the path *or*
a directory above it, because git prunes an excluded directory rather than
testing the files inside it. That is the right answer for the combined list of
every pattern git consults, but not for asking whether one .gitignore has an
opinion about this path.

So `!playground/build_cache` in pkg/.gitignore matched every file under
playground/build_cache, and the walk returned there, never asking the root file
about its `*_pb2.py`:

    .gitignore     ->  build_cache
                      *_pb2.py
    pkg/.gitignore ->  !playground/build_cache
    pkg/playground/build_cache/msg_pb2.py

git ignores msg_pb2.py (the root pattern, which names the file, is the only
thing that speaks about it); the walk collected it. This commit requires a
pattern to name the path itself before it gets a say, which pathspec's compiled
regex already distinguishes: it matches `^pattern(?:(?P<ps_d>/)|$)`, so a match
that captured the ps_d separator only covered a prefix of the path, and one that
did not reached the end of it.

Note this shape already diverged on main, in the other direction: main ignored
msg_other.py here too, because it took the root's transitive `build_cache` match
as an answer about a file that pattern does not name.

Verified against `git add --dry-run` on 18 nested-gitignore trees, including the
three real-world shapes named in psf#5376 and the reviewer-reported case.
One line came to 89 characters. .flake8 sets max-line-length = 80 with B950
selected, and B950 allows 10% over, so the effective limit is 88. Black does
not reflow docstrings, so `black --check` was happy while flake8 was not.
@santhosh220z
santhosh220z force-pushed the fix/nested-gitignore-negation branch from acb7ff8 to 4b2b623 Compare October 5, 2026 05:51
@mathewOracle

Copy link
Copy Markdown

Thanks for the rework, no worries on timing! Checked 2854416 and the original case is fixed: pkg/playground/build_cache/msg_pb2.py stays ignored, and msg_other.py next to it is formatted, which matches git check-ignore.

I also diffed Black against git check-ignore -v on 8 small repos (nested negations re-including a directory, a root *_pb2.py-style pattern under a re-included dir, anchored /x.py in a nested file, **/tmp/** with a nested !tmp/**, a parent-excluded dir that can't re-include a child, and a self-negating .gitignore). On this branch all 8 agree with git. On main 4 of them disagree, all in the direction of ignoring files git would keep. The existing -k gitignore tests pass too.

The _pattern_matches_directly approach (checking whether the match used pathspec's ps_d directory group) reads well. It depends on pathspec's compiled-regex internals though, so a short comment naming the pathspec version it was checked against might help whoever bumps pathspec next.

One thing left before a maintainer can merge: the branch now conflicts with main in CHANGES.md (just the changelog entry, nothing in the code).

LGTM from my side.

AI disclosure: the verification scripts and this write-up were produced with an AI coding assistant (code-puppy) at my request; the numbers above are from actually running them.

@cobaltt7 cobaltt7 added this to the File discovery milestone Nov 25, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants