Skip to content

fix(diff): honor negated gitignore directories - #1794

Open
LuckVd wants to merge 10 commits into
alibaba:mainfrom
LuckVd:fix/1793-gitignore-negated-directories
Open

LuckVd wants to merge 10 commits into
alibaba:mainfrom
LuckVd:fix/1793-gitignore-negated-directories

Conversation

@LuckVd

@LuckVd LuckVd commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Description

Fixes #1793

A negated directory pattern (!dir/) was never honored: isPathExcluded in internal/diff/git.go skipped every negated pattern ending in /, so a repository pairing /*/ with !/src/ kept every file under src/ out of review and reported No files changed. even though git tracks changes there. The skip existed for a good reason — !*/ must not re-admit the files matched by * — but it also discarded the negations that re-include directories.

This change resolves ignore state separately for the path and each of its ancestor directories, mirroring how git resolves rules per directory: a file is excluded if any ancestor directory ends up excluded (file negations cannot bypass an excluded parent), otherwise by the last pattern matching the file itself, where directory-only patterns only ever affect directories.

Change

  • internal/diff/git.go (isPathExcluded): track last-match state per ancestor directory and for the file itself; negated directory-only patterns now participate in the per-directory resolution instead of being skipped, while still being unable to re-include files.
  • internal/diff/git.go (matchGitignoreDirectory → matchGitignoreDirectoryPath): extracted the directory-path matcher so both the old call site and the new per-ancestor loop share one implementation; behavior preserved.
  • internal/diff/gitignore_test.go: added TestIsPathExcluded_NegatedDirectoryPatterns covering /*/ + !/src/, src/ + !src/, * + !*/ (files stay excluded), and src/ + !src/a.go (parent exclusion wins).

Type of Change

  • Bug fix (non-breaking change that fixes an issue)

How Has This Been Tested?

  • make test passes locally (Go 1.x, local module cache; all packages pass, including internal/diff with -count=1)

  • Manual testing: built the CLI and reproduced the exact steps from .gitignore !dir/ never re-includes a directory: /*/ + !/src/ drops every file under src/ #1793 in a scratch repository. Against the fix, ocr review --preview lists Will review (1): src/a.go for /*/ + !/src/, matching git check-ignore --no-index. Cross-checked the full truth table from the issue against local git:

    .gitignore git this PR
    /*/ !/src/ not ignored reviewed
    src/ !src/ not ignored reviewed
    /* !/src/ not ignored reviewed
    * !*/ !*.go not ignored reviewed
    * !*/ ignored dropped

    The new test also fails on origin/main (verified by checking it out onto main without the fix): /*/ + !/src/ and src/ + !src/ returned true, and src/ + !src/a.go returned false.

Checklist

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly (if applicable)
  • I have signed the CLA
  • I did not use AI/LLM to create this PR, or I disclosed the tool/model below and reviewed its output; I did not attribute commits to AI and will answer maintainer questions and review comments myself without AI/LLM.

Tool(s) used: GPT-6 (Codex) for the fix, Claude for verification — drafted under my direction; reviewed every line before submitting.

Related Issues

@github-actions

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: Review complete: 0 finding(s) across 1 selected item(s).

@PJunhyuk

Copy link
Copy Markdown

This fixes the case in #1793, but it also brings back directories that git keeps ignored. When a !dir/ line re-includes a directory, an ignored directory inside it is re-included too:

.gitignore path git this PR
build/ /*/ !/src/ src/build/out.go ignored not excluded
node_modules/ /*/ !/ui/ ui/node_modules/x.js ignored not excluded
vendor/ !src/ src/vendor/lib.go ignored not excluded
build !tools/ tools/build/x.go ignored not excluded

main excludes the first three (it already misses the fourth), so those three would be new regressions.

The cause is the new per-directory loop in isPathExcluded. For each parent directory it calls matchGitignoreDirectoryPath, which (as its comment says) matches the pattern against any component of the path, not only that directory. So when the loop checks src/build, !/src/ matches its src component and clears it. Each parent directory already has its own entry in directoryExcluded, so it should be enough for the loop to match only the directory itself: its name if the pattern has no leading or middle slash, its full path otherwise. matchGitignoreDirectory still needs the any-component behaviour, so this would be a separate helper. With that change, the copy I tested gives git's result on all 23 cases I tried, these four included.

How I checked: I copied isPathExcluded and its helpers from this branch (56fea37) into a scratch program, with doublestar v4.10.0 as in go.mod, and compared each result with git check-ignore --no-index. I used Claude Code (Claude Opus 5.5) to trace the cause, run the comparison and draft this comment.

Comment thread internal/diff/git.go Outdated
directoryPath := strings.Join(parts[:i+1], "/")
var matched bool
if directoryOnly {
matched = matchGitignoreDirectoryPath(directoryPath, body)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked Git’s dir.c: re-including src allows traversal into it, but src/build is still checked separately and remains ignored by build/. Here, the matcher also checks ancestor components, so !/src/ incorrectly clears the exclusion of src/build. Could we match only the current directory in this loop and add a regression test for that case?

@LuckVd

LuckVd commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @PJunhyuk — the per-directory loop was indeed matching negations against any component of the parent path, exactly as you traced. d8b99c2 (pushed shortly after your review) takes the approach you suggested: a separate helper, matchGitignoreDirectoryEntry, that matches a pattern against the directory itself only — basename when the pattern has no leading or middle slash, full path otherwise — while matchGitignoreDirectoryPath keeps the any-component behaviour for the file-level directory match. The per-directory loop in isPathExcluded now uses the new helper.

All four rows from your table are in the test file and pass on this head (src/build/out.go, ui/node_modules/x.js, src/vendor/lib.go, tools/build/x.go — the fourth included, which main misses). @chaojixinren the changes-requested landed five minutes before that push, so it predates the fix — could you take another look at d8b99c2?

@abhisheksharma2411 abhisheksharma2411 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked at this because it touches isPathExcluded, which my #1805 also calls.

Rather than reason about the semantics, I built a differential harness: a real git repo per case, write the .gitignore, then compare git check-ignore --no-index against IsPathExcluded for 32 pattern/path combinations.

origin/main: 8 of 32 disagree with git. This branch: 0 of 32.

patterns path git main this PR
/*/ !/src/ src/a.go not ignored ignored not ignored
build/ /*/ !/src/ src/a.go not ignored ignored not ignored
node_modules/ /*/ !/ui/ ui/app.js not ignored ignored not ignored
src/ !src/ src/a.go not ignored ignored not ignored
src/ !src/a.go src/a.go ignored not ignored ignored
/build build/o.go ignored not ignored ignored
**/logs logs/x ignored not ignored ignored
**/logs a/logs/x ignored not ignored ignored

Two things worth drawing out.

@chaojixinren's point is settled by the build/ + /*/ + !/src/ case with src/build/out.go: git ignores it, and so does this branch after d8b99c2. The concern was real against 56fea37, and the per-directory resolution handles it — both agree with git now.

The more interesting bit is that three of the eight fixes have nothing to do with negations: /build matching build/o.go, and **/logs matching logs/x and a/logs/x. Those are anchored and globstar patterns that main got wrong on their own, and resolving per ancestor directory fixes them as a side effect. It might be worth a line in the description, because as it stands someone reading the title would not know anchored patterns were fixed too — and there is no test pinning them, so a later refactor could regress them with nothing turning red.

go test ./... passes on the branch.

One logistics note: this and my #1805 both touch internal/diff/git.go, in different functions (isPathExcluded here, partitionDiffs there), so whichever lands second may need a trivial rebase. Nothing semantic — mine only calls isPathExcluded and inherits whatever this decides.

Happy to share the harness if it would be useful as a test.

LGTM.

Claude assisted with this review; the numbers above are from runs on my own machine.

@chaojixinren chaojixinren left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@LuckVd

LuckVd commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Hi maintainers — thanks for the reviews. The latest two reviews are approvals, but GitHub still reports REVIEW_REQUIRED / BLOCKED, and I only see the CLA check on this PR. Could you let me know whether a required review or workflow approval is still pending, or if any action is needed from me?

@lizhengfeng101

Copy link
Copy Markdown
Contributor

@LuckVd Thanks for the update. CI is now green on 5b83f6e, but two matcher regressions still need to be fixed before merging. The merge from main did not change the affected matcher functions.

Both cases below should remain included, as they do with Git and the pre-PR matcher, but this PR's matcher excludes them:

Root .gitignore rules, in order Path Expected Current matcher
src/**
!src/*.go
src/a.go Included Excluded
docs/generated src/docs/generated/a.go Included Excluded

Both originate in the new ancestor-matching call at internal/diff/git.go:338:

  1. Trailing /** must not exclude the directory itself. doublestar.Match("src/**", "src") accepts a zero-component suffix, so the ancestor loop marks src excluded. The later file exception cannot clear that ancestor state. Git's trailing /** matches the directory's contents, not src itself; please preserve that distinction when matching ancestors.
  2. Slash-containing patterns must remain root-relative. When checking the ancestor src/docs/generated, matchGitignoreBody falls through to its existing suffix match for docs/generated. Reusing that fallback for ancestors now excludes an unrelated subtree. A pattern containing an internal slash is relative to the .gitignore location, even without a leading slash.

Please fix both cases and add regression tests asserting that these files are not excluded. For the second case, also retain a control asserting that docs/generated/a.go at the repository root is excluded by docs/generated. Please cover at least one affected enumeration/preview path and rerun CI after the changes.

The merged main now bypasses .gitignore filtering for tracked workspace changes, so that workflow is no longer affected. However, range/commit review, untracked-file collection, and scan enumeration still use this matcher. The current green suite does not cover these two cases.

Validation: compared extracted matcher functions with git check-ignore --no-index, then checked that the matcher functions are unchanged in the latest head. This review and comment were AI-assisted using Codex and OpenCodeReview; the OCR run was on d8b99c2, not a new run on the merge commit.

@NanaseInori NanaseInori left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed both changed files, #1793, the full discussion including the November 9 maintainer comment, and the competing #1795 implementation. The original negated-directory defect is real, and the earlier ancestor-versus-current-directory issue has been addressed. Two separate regressions identified in the latest comment remain in this head.

[P2] Do not let a trailing / exclude the ancestor directory itself.** For src/** followed by !src/*.go, the new ancestor call passes src to doublestar.Match. That library accepts the empty /** suffix, so src is marked excluded and the valid file exception never gets a chance to admit src/a.go. Git ignores contents here, not the src directory itself.

[P2] Do not reuse the file suffix fallback for ancestor paths. For the root rule docs/generated, matchGitignoreBody treats src/docs/generated as a suffix match. The new ancestor loop consequently excludes src/docs/generated/a.go, although an internal slash makes this rule relative to the root .gitignore. The root control docs/generated/a.go should remain excluded.

I independently checked all three file outcomes with git check-ignore --no-index: the two reported paths were included; the root control was excluded. I then traced the unchanged matcher branches and doublestar's zero-length suffix handling. This is Git ground-truth execution plus source inspection, not an independent execution of OCR's matcher or full suite.

Please preserve current-directory matching while correcting these two rules, add the exact regressions and retain the root control. The earlier #1795 comparison does not make either implementation merge-ready. References: maintainer's detailed cases, Git pattern semantics.

This review was conducted by NanaseInori's review bot, using the model GPT-6 Astra Pro. If you need a human review, please manually @NanaseInori.

…ectories

Two regressions from the ancestor-resolution loop, both fixed against
git check-ignore --no-index ground truth:

- A trailing /** matched the prefix directory itself because doublestar
  accepts the empty suffix (doublestar.Match("src/**", "src") is true).
  Git ignores the contents of src, not src, which is what lets
  !src/*.go re-admit src/a.go. Trailing /** now matches the prefix
  followed by at least one component; the same rule applies to
  directory-only patterns like src/**/ via matchGitignoreDirectoryEntry.
- Ancestor directories reused matchGitignoreBody's path-suffix fallback,
  so the root rule docs/generated excluded the unrelated
  src/docs/generated subtree. Ancestors now resolve against their full
  path only (matchGitignoreAncestorBody); the suffix fallback stays
  file-only.

Adds regression tests for both cases with their root controls, plus an
end-to-end enumeration test through the scan provider.
@LuckVd

LuckVd commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Both regressions are fixed on 9e1c47a, verified against git check-ignore --no-index ground truth (13-case differential, 0 mismatches, including the three file outcomes from the review and the directory-level controls src / src/docs/generated).

1. Trailing /** no longer excludes the prefix directory. The globstar branch now matches the prefix followed by at least one required component (prefix/**/*), because doublestar accepts the empty suffix (doublestar.Match("src/**", "src") is true). Current-directory matching is preserved: src/** still excludes src/sub, and the negation !src/*.go re-admits src/a.go. While grounding this I found the same defect on the directory-only shape: git says src/**/ leaves src/a.go visible too, so the fix also applies through matchGitignoreDirectoryEntry (src/**/ → src/sub/x.go excluded, src/a.go included).

2. Ancestors no longer reuse the file suffix fallback. New matchGitignoreAncestorBody resolves an ancestor directory against its full path only, so the root rule docs/generated keeps excluding docs/generated/a.go (control retained) but never reaches src/docs/generated/a.go. The file-path suffix fallback itself is untouched.

Tests: a unit table for both rules with root controls and git-verified boundaries (mid-pattern a/**/b/**, directory-only src/**/, anchored /docs/generated), plus an end-to-end enumeration test through the scan provider. Full suite green locally (go build/vet/test ./..., 25 packages); CI is rerunning on the new head.

@lizhengfeng101 lizhengfeng101 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@LuckVd Thanks for the update. The original directory-negation case and the previously reported trailing-/** and root-relative ancestor regressions are fixed in 9e1c47a. A fresh review found two additional false-exclusion cases in matchGitignoreAncestorBody, detailed inline. Please fix both, add regression tests (including an affected enumeration/review entry point), and rerun CI with native Windows coverage before merging.

Validation: make test PACKAGES='./internal/diff ./internal/scan ./internal/tool' passes, but the independent regression fixtures expose the gaps below. The first issue was reproduced natively on macOS; the second was verified against Git and a Windows-semantics simulation of Go's matcher, not a native Windows run.

AI assistance: Codex and OpenCodeReview. The fresh OCR run completed on this exact head; the behavioral checks were performed separately.

Comment thread internal/diff/git.go Outdated
body, anchored = trimmed, true
}

if strings.Contains(body, "**") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Select the basename before matching slashless globstar rules

With these root .gitignore rules:

cache
!**cache

Git and the pre-PR implementation include src/cache/a.go, but this head excludes it. The first rule excludes ancestor src/cache; this branch then matches **cache against that full path rather than its basename. Non-component ** behaves like * and cannot cross /, so the negation cannot clear the ancestor state.

Fresh native tests reproduce the omission through commit review, range review, untracked workspace collection, and scan. Tracked workspace changes remain unaffected. Please select basename versus full path according to anchoring and slash presence before dispatching globstar matching, as matchGitignoreDirectoryEntry already does, and add this exact nested-directory regression.

Comment thread internal/diff/git.go Outdated

// Slash-containing patterns are relative to the .gitignore location and
// match the directory's full path only — no suffix fallback.
matched, _ := filepath.Match(body, directoryPath)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Use slash-based matching for normalized ancestor paths on Windows

With these root .gitignore rules:

src/*
!src/ok/
!src/ok/nested/*.go

Git includes src/ok/nested/a.go. On Windows, however, filepath.Match uses backslash as its separator, so src/* also matches the slash-normalized ancestor src/ok/nested. The directory exception clears src/ok, not that deeper ancestor, and the later file exception cannot bypass the new ancestor veto.

The frozen baseline passes and this head fails when both are evaluated using the Go standard-library matcher with its Windows branches and separator selected; the Git oracle also includes the file. This is a Windows-semantics simulation, not native Windows execution. Please use a matcher with a consistent / separator contract, such as path.Match, for normalized ancestor paths (including the anchored branch), and add native Windows regression coverage for this case.

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.

.gitignore !dir/ never re-includes a directory: /*/ + !/src/ drops every file under src/

6 participants