Skip to content

plumbing: gitignore, dirOnly re-include patterns must not cascade to descendants. Fixes #2112 - #2311

Open
thesahibnanda-max wants to merge 2 commits into
go-git:mainfrom
thesahibnanda-max:fix/gitignore-dironly-reinclude-cascade
Open

thesahibnanda-max wants to merge 2 commits into
go-git:mainfrom
thesahibnanda-max:fix/gitignore-dironly-reinclude-cascade

Conversation

@thesahibnanda-max

Copy link
Copy Markdown

Fixes #2112

(Supersedes #2310, closed — that PR's commit didn't follow the repo's commit-message/DCO conventions; this one carries the same change with a corrected, signed-off commit.)

Problem

Given a .gitignore containing:

*
!my-dir/

real git keeps everything under my-dir/ ignored except the directory entry itself is un-excluded for traversal purposes — but files nested inside it (e.g. my-dir/sub/file.txt) remain subject to the * exclusion and stay ignored. go-git instead reported those nested files as untracked, so Worktree.Status() surfaced files that real git status would never show.

Root cause

plumbing/format/gitignore/pattern.go, simpleNameMatch:

func (p *pattern) simpleNameMatch(path []string, isDir bool) bool {
	for i, name := range path {
		if !wildmatch(p.pattern[0], name) {
			continue
		}
		if p.dirOnly && !isDir && i == len(path)-1 {
			return false
		}
		return true
	}
	return false
}

This loop lets a bare (non-glob) pattern match a name at any depth in the path component list — which is correct and necessary for patterns like node_modules matching a/node_modules/file.txt at any nesting level. The bug: that "ancestor match stands in for the whole descendant path" behavior was applied uniformly, but it's only valid for exclusion patterns (excluding an ancestor directory correctly excludes everything below it too). For a dirOnly inclusion pattern (!dir/), a match against an ancestor component (not the final path element) was also being treated as a match for the whole descendant path — incorrectly resurrecting files nested arbitrarily deep under a re-included directory name, even when nothing else in the pattern list re-includes them specifically.

Fix

simpleNameMatch now treats a dirOnly inclusion pattern's match against a non-final (ancestor) path component as no match for that call, instead of a match for the whole path:

last := i == len(path)-1
if p.dirOnly && p.inclusion && !last {
	// A dirOnly re-include pattern restores only the directory entry
	// itself; it must not cascade to the directory's descendants.
	continue
}

Exclusion patterns (p.inclusion == false) are completely unaffected — an excluded ancestor still correctly excludes its descendants, matching existing behavior and existing tests (e.g. TestSimpleMatch_inTheMiddle_dirWanted).

Scope note

I verified this fix against the real git binary (this package already has a conformance_test.go harness that cross-checks against git check-ignore/git status when available). While investigating, I found real git has a separate, narrower quirk: a bare * pattern specifically resists being overridden by any later negation for the exact directory entry it matched (i.e. even !my-dir/ alone, with no nested descendants involved, doesn't un-ignore my-dir itself when preceded by * — confirmed with git status --porcelain --ignored). Other exclude patterns (a literal name, or a non-* wildcard like m*) don't have this quirk; negation works normally against them. That's unrelated to the cascading-into-descendants bug this issue reports, so I deliberately left it alone and didn't assert on it in the new tests, to keep this PR minimal and precisely scoped to #2112.

Tests added

  • plumbing/format/gitignore/pattern_test.go: unit-level coverage of the pattern in isolation (ancestor match no longer cascades; the directory itself, matched directly, still returns Include).
  • plumbing/format/gitignore/conformance_test.go: a new case cross-checked against the real git binary via the existing oracle harness.
  • worktree_status_test.go: an end-to-end regression test reproducing the original report through Worktree.Status().

Testing performed

  • go test ./plumbing/format/gitignore/... — passes (one pre-existing, unrelated TestIgnoreDoubleStarPrefix oracle mismatch confirmed present on unmodified main too, via git stash).
  • go test . — no new failures versus a baseline run on unmodified main (same pre-existing, environment-specific failures on both, verified by diffing the failing-test lists).
  • go vet ./... — clean (one pre-existing, unrelated warning in Windows SSH agent code, not part of this change).

…descendants. Fixes go-git#2112

A pattern like !dir/ only restores the directory entry itself; it does
not implicitly re-include everything nested inside it. simpleNameMatch
let a dirOnly inclusion pattern matching an ancestor path component stand
in for a match on the full descendant path, so a .gitignore like:

    *
    !my-dir/

wrongly reported files under my-dir/ as untracked instead of ignored.

Signed-off-by: Sahib Nanda <[email protected]>
TestStatusIgnored regressed after the previous commit: a root-anchored
glob like "vendor/g*/" excludes two sibling directories, and a nested
vendor/.gitignore's "!github.com/" re-includes one of them specifically.
Once that override is resolved, globMatch's "leftover suffix still
counts as matched" behavior (needed so an excluded directory excludes
its descendants) let "vendor/g*/" keep reasserting its old verdict on
files inside the re-included directory, even though its own anchor
("vendor", "g*") was already fully consumed at that depth and had
nothing left to say about anything deeper.

A single Pattern has no way to know this: only Scope carries the
cross-pattern, cross-directory context needed. Scope.Descend now drops
glob patterns whose domain-plus-pattern length is fully consumed by the
directory just resolved, unless they contain "**" (unbounded reach) or
are non-glob (any-depth matching is their entire purpose, per
simpleNameMatch). This is the mirror image of the existing excluded
sticky flag: that one pins an exclude verdict forward past a resolved
boundary; this pins the boundary itself, so a pattern that already had
its say can't reach past it again.

Verified against TestStatusIgnored (now passing again) and a new
Scope-level test, TestScopeOverriddenGlobDoesNotReclaimDescendants,
confirmed against "git status --porcelain --ignored". Hand-traced
against every existing scope_test.go case; none change behavior, since
they either never reach the surviving branch with a droppable pattern
or use non-glob patterns that dropExhausted never touches.

Signed-off-by: Sahib Nanda <[email protected]>
@thesahibnanda-max

Copy link
Copy Markdown
Author

The test CI jobs on the first commit were failing for a real reason, not flakiness: TestWorktreeSuite/TestStatusIgnored regressed.

That test covers a case real git genuinely supports — a root-anchored glob (vendor/g*/) excludes two sibling directories, and a nested vendor/.gitignore's !github.com/ re-includes one of them specifically. My first commit's fix for #2112 (stop a dirOnly inclusion pattern's ancestor match from cascading to descendants) was correct for the * + !my-dir/ case in the issue, but too broad: it also blocked this legitimate, different kind of override.

The second commit adds the missing piece. globMatch's "a leftover, unconsumed path suffix still counts as matched" behavior is what makes an excluded directory correctly exclude everything below it — but nothing stopped a directory-anchored glob pattern from reasserting that same old verdict on a directory's contents even after a more specific, nested pattern had already overridden that exact directory. A single Pattern can't know this on its own; only Scope has the cross-pattern, cross-directory context needed, so Scope.Descend now drops glob patterns whose anchor is fully consumed by the directory just resolved (patterns using **, or non-glob patterns that are meant to match at any depth, are left untouched). It's the mirror image of the existing excluded sticky flag: that one pins an exclude verdict forward past a resolved boundary; this pins the boundary itself.

Verified TestStatusIgnored passes again, added a new Scope-level test (TestScopeOverriddenGlobDoesNotReclaimDescendants) cross-checked against git status --porcelain --ignored, and hand-traced the change against every existing case in scope_test.go to confirm no behavior changes there. Also ran the full suite and diffed failures against a clean baseline — no new regressions beyond what's already broken on main today (e.g. TestStatusMatchesReferenceGitForIgnoreLayouts, which I confirmed also fails identically on a fresh, unmodified clone of main — unrelated to this PR).

@KaizenShogun

Copy link
Copy Markdown

The bug you're fixing is real, your diagnosis matches what I measure, and the patch fixes more than the issue asks for. It also takes away one case that main currently gets right, and I'd rather say so before it lands than after. Numbers instead of an opinion, and a two-line repro at the end.

Setup. One Go helper (ReadPatterns + Matcher.Match, plus Worktree.Status() as a second entry point), built three times from the same source, changing only the tree it points at: refs/heads/main fetched today, refs/pull/2311/merge (main + both your commits, 4fc02ab and 502b0e5, as GitHub computes the merge), and refs/pull/2318/merge for contrast. I checked the drift rather than assuming it: the +2311 tree differs from main in exactly the five files your PR touches.

The corpus is 33 real repositories' whole .gitignore trees materialised on disk — root plus nested rule files, files and directories variants — 4,463 matcher queries and 2,224 through Status(). Oracle is git check-ignore -v --non-matching --no-index (git 2.55.0), asked again in every tree.

column matcher Status()
main 2 / 4,463 1 / 2,224
+2311 4 / 4,463 — 0 fixed, 2 broken 1 / 2,224

Compared as sets, not counts: the two main already had are untouched, and two new ones appear.

First, what it fixes. #2112, verbatim, and a variant the issue doesn't mention:

.gitignore query git main +2311
* + !my-dir/ my-dir/sub/file.txt ignored not ignored ignored ✔
* + !my-dir/ my-dir/file.txt ignored not ignored ignored ✔
*.tmp + !my-dir/ my-dir/sub/a.tmp ignored not ignored ignored ✔
*.tmp + !my-dir/ my-dir/sub/file.txt not ignored not ignored not ignored

That last row is the interesting one, and your patch gets it right.

What it breaks. Same shape, one thing changed — the pattern that excluded the directory now matches only the directory:

mkdir -p t/sub/.idea && cd t && git init -q
printf '.idea/\n!.idea/\n' > .gitignore
touch sub/.idea/f.txt
git check-ignore -v --no-index -- sub/.idea/f.txt   # no match: git does NOT ignore it

Matcher.Match([]string{"sub", ".idea", "f.txt"}, false) → main: false (agrees with git). +2311: true. Same answer through Status(). It doesn't depend on the name or on the depth (sub/.idea/, sub/a/b/.idea/ behave alike), and it goes away if the negation loses its trailing slash (!.idea is correct in both columns) — which points at the dirOnly path your change touches.

The real-world case the bench found is the same thing across two rule files, which is what python/cpython ships today:

.gitignore                             ->  .idea/
Platforms/Android/testbed/.gitignore   ->  !.idea/
query: Platforms/Android/testbed/_gic_deep/.idea/inspectionProfiles/
git: not ignored   main: not ignored   +2311: ignored

Where I think the line is. Your write-up frames the fix as "a dirOnly re-include matching an ancestor component must not stand in as a match for the whole descendant path". The measurements above fit a slightly different rule: git re-includes the directory, and then re-evaluates what's inside against every pattern again. In #2112 the descendants stay ignored because * matches sub and file.txt on their own — not because !my-dir/ stops counting. Swap * for *.tmp and git's answer splits down that line, which is the row your patch already gets right. The case that breaks is the one where nothing but the directory pattern ever matched the contents: after !.idea/ re-includes the directory, no rule is left to ignore f.txt.

How much is at stake. Only 2 of 4,463 queries move, so this could read as a corner. But the construct isn't rare: 10 of the 33 repositories in the corpus write at least one !something/ — airflow, elasticsearch, grafana, node, vscode, next.js, supabase, cpython, gradio, pathspec — 24 lines across 12 rule files. The bench only materialises the exact combination (excluded by a directory-only pattern, re-included by !dir/, queried below it) in cpython; that's a property of my corpus, not of the wild.

I'm an interested party, not a maintainer: I opened nothing here, I ran the bench because I keep one. The tests, the corpus and the go-git adapter are public if you want to reproduce any row: https://github.com/KaizenShogun/gitignore-conformance

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.

go-git ignores files inside un-ignored directory with wildcard pattern

2 participants