Skip to content

fix(diff): read .gitignore from the reviewed ref in range and commit modes - #1549

Open
ydflow wants to merge 2 commits into
alibaba:mainfrom
ydflow:fix/range-mode-gitignore-from-ref
Open

ydflow wants to merge 2 commits into
alibaba:mainfrom
ydflow:fix/range-mode-gitignore-from-ref

Conversation

@ydflow

@ydflow ydflow commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

Description

Range and commit modes reviewed history, but filtered their changed files with the working tree's .gitignore.

An ignore rule that exists only locally — an uncommitted .gitignore, or one that exists on the checked-out branch but not on the reviewed one — silently dropped files out of the review, while the run still exited 0. A file the user explicitly asked about was never looked at, and nothing said so.

Reproduction from the issue: a feature branch adds gen.go and has no .gitignore; with a local uncommitted .gitignore containing gen.go, ocr review --from base --to feature reviews nothing.

Why this is the right rule

A range review answers "what did this ref change", so the ignore rules that apply are the ones the ref itself carries. Read them from REF:.gitignore instead of the checkout. A ref without a .gitignore yields no patterns, which is exactly what its history says — not a reason to fall back to the working tree, because that is the bug.

Workspace mode keeps reading the working tree, because there the working tree is the thing under review.

LoadGitignorePatterns (exported) and its callers in internal/scan and internal/tool/file_find are untouched: those were always working-tree semantics and still are.

Type of Change

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

How Has This Been Tested?

Three tests in internal/diff/git_test.go, all driving real git repositories:

  • TestRangeModeIgnoresWorkingTreeGitignore — the regression. Base commit with no .gitignore, a feature commit adding gen.go, then an uncommitted local .gitignore ignoring gen.go. Asserts the range review still selects gen.go.
  • TestCommitModeIgnoresWorkingTreeGitignore — same rule for --commit, which diffs against the commit's first parent.
  • TestWorkspaceModeStillHonorsWorkingTreeGitignore — the guard against over-correcting: workspace mode must still honor the working tree's rules (it reviews the working tree), so gen.go stays excluded there.

Confirmed the tests pin real behavior rather than an incidental pass: reverting only the GetDiffSet change makes both history-mode tests fail with selected [] — the exact silent-drop symptom from the issue — and restoring it makes them pass.

Local runs (Windows, go1.27.0):

  • go test ./internal/diff/... ./internal/agent/... ./internal/scan/... ./internal/session/... — all ok
  • gofmt -s -l internal/diff/ — clean
  • go vet ./internal/diff/ — clean
  • bash scripts/verify-license.sh — all source files have valid license headers
  • go build ./cmd/opencodereview — exit 0

Not run: internal/tool, whose GitGrep tests fail on this machine for a pre-existing environment reason (the installed git is 2.33.1 and the code needs --max-count from 2.45+). Verified unrelated by checking out the base commit and re-running: the same 21 failures. No files in that package are touched by this PR.

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) — no documented contract changes; this aligns behavior with what range/commit modes already claim to do
  • 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.

AI/LLM disclosure: used Claude (Anthropic) as a coding assistant for navigating the codebase and drafting. Every line was read and verified by me: the root cause was confirmed by a failing test before any fix, and the fix was re-verified by reverting it to watch those tests go red again. The test results above are from commands I ran locally. Commits carry no AI attribution.

Related Issues

closes #1487

Scope note

The issue asks whether range/commit modes should read ignore rules from the reviewed ref, or whether the working-tree behavior is intended — so a maintainer may prefer the "document it instead" route. This PR implements the ref-based reading because the current behavior is silent data loss rather than a documented choice, and the issue reports it as a bug. Happy to switch to a docs-only change if that is the preferred direction.

One thing this does not address: nested .gitignore files in subdirectories are still not read (only the repository root's, matching the pre-existing behavior). That is a separate gap and out of scope here.

@github-actions

Copy link
Copy Markdown
Contributor

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

@Qiyuanqiii Qiyuanqiii 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.

Reviewed ecad46b.

The history-mode behavior now matches the input being reviewed. Range mode reads .gitignore from the target ref, commit mode reads it from the reviewed commit, and workspace mode continues to use the working tree.

This also removes the previous dependency on unrelated local or uncommitted .gitignore state when reviewing historical refs. The new tests cover range, commit, and workspace behavior with real repositories.

I don't see another blocker. Approving.

@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.

@ydflow Thanks — the fix itself is correct and well-scoped. I verified it independently in both directions: a .gitignore committed in the reviewed ref still filters tracked files, and a working tree missing the .gitignore that the ref carries now drops the file as it should. internal/diff, internal/agent, internal/scan, internal/session and cmd/... all pass; no conflict with current main. Leaving LoadGitignorePatterns and the internal/scan / file_find callers alone is the right call.

A few things to address before merging — the first is the one that matters.

1. The tests don't pin the positive half of the new behavior.

Replacing the pattern load with nil, i.e. doing no .gitignore filtering at all in history modes, still passes all three new tests:

if ref != "" {
    return p.partitionDiffsWithPatterns(diffs, nil), nil
}

TestWorkspaceModeStillHonorsWorkingTreeGitignore guards the workspace side, but nothing guards "the reviewed ref's own rules still apply". Please add a test where the ref carries a committed .gitignore that ignores a tracked file (git add -f), asserting the file is still filtered out. The implementation already passes this — it's purely a missing test.

2. gitOutput duplicates gitOut and its doc comment is wrong.

git_resolve_test.go already has gitOut(t, dir, args...) in this same package with an identical body, except that it trims. The new helper's comment says "returns its trimmed stdout" but returns string(out) untrimmed, so the call site wraps it in strings.TrimSpace. Suggest deleting gitOutput and using gitOut.

3. Unreachable branch. The if ref == "" { return nil } in loadGitignorePatternsAtRef can't be hit — the only caller already checks ref != "". Worth dropping given the 90% coverage threshold.

4. Errors are swallowed wholesale, including cancellation. Fail-open is the right direction here (over-reviewing beats silently dropping), but ctx.Err() goes down the same path, so a cancelled or timed-out run degrades to "no ignore rules" and keeps going. The rest of GetDiffSet propagates, and runGitSplit has an explicit cancellation guard. Suggest propagating ctx.Err() and noting in the comment that fail-open on other errors is deliberate.

5. Minor: if ref != "" re-derives the mode from a value the switch p.mode just above computed. Folding the pattern load into that switch, or testing p.mode != ModeWorkspace, states the intent more directly.

One note for the release notes: this is user-visible. Anyone who relied on a local .gitignore to keep generated-but-tracked files out of range/commit reviews will now see those files reviewed — which is the point, but it will read as a regression otherwise. --preview changes the same way, via internal/agent/preview.go.

@ydflow

ydflow commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — all five addressed in c2f1a35, pushed on top of the merge of upstream main.

1. Positive half now pinned. Two new tests: TestRangeModeStillFiltersGitignoreFromReviewedRef and TestCommitModeStillFiltersGitignoreFromReviewedCommit. Each commits a .gitignore ignoring gen.go and force-adds the generated-but-tracked file, then removes the working-tree .gitignore so any filtering must have come from the ref. Both assert [.gitignore keep.go] — .gitignore is itself part of the change under review, gen.go is the one the ref's rule must keep out.

Confirmed they pin real behavior: substituting nil for the pattern load fails both with selected [.gitignore gen.go keep.go] — the exact over-review symptom your mutation produces. Restoring the load makes them pass. That also closes the gap in the existing three, which a nil load passed unchanged.

2. gitOutput removed. gitOut from git_resolve_test.go is now the only such helper; the one call site uses it directly, with no strings.TrimSpace wrapper. The wrong "returns its trimmed stdout" comment went with it.

3. Unreachable branch dropped. loadGitignorePatternsAtRef no longer takes the empty-ref case — the caller decides by mode, so the branch could not be reached. Coverage of that function is now 100% (was 66.7%), and the package is at 93.5%.

4. ctx.Err() propagated. The reader returns ([]string, error); on failure it first checks ctx.Err() and returns that, falling back to nil only for a genuinely absent or unreadable .gitignore. GetDiffSet propagates the error, so a cancelled or timed-out run stops instead of degrading to "no ignore rules". The comment now states that fail-open is deliberate for the other errors and says why cancellation is not part of that trade.

New test TestRangeModeCancelledWhileReadingGitignoreReportsCancellation drives the reader with an already-cancelled context. It does not use the PATH shim, which skips on Windows — this runs on Linux CI and locally here. Reverting just the ctx.Err() propagation fails it; restoring it passes.

5. Intent stated directly. GetDiffSet now branches on p.mode == ModeWorkspace for the working-tree path, and the history path follows unconditionally, instead of re-deriving the mode from ref after the switch above already computed it.

Verification (Windows, go1.27.0, git 2.33.1): go test ./internal/diff/... ./internal/agent/... ./internal/scan/... ./internal/session/... all ok; gofmt -s -l internal/ cmd/ clean; go vet clean on those packages plus ./cmd/...; scripts/verify-license.sh and scripts/verify-english-only.go both pass; go build ./cmd/opencodereview exit 0. make is not installed here, so I ran the individual targets rather than make check / make test. internal/tool remains unrun — its GitGrep tests need --max-count from git 2.45+, and the same 21 failures occur on the base commit; no files there are touched.

Release note: agreed, and worth stating precisely — a range/commit review no longer honors a .gitignore that exists only in the reviewer's checkout, and --preview moves the same way through internal/agent/preview.go. A repo that relies on a local rule to keep generated-but-tracked files out of a history review will now see them reviewed, which is the point, but it will read as a regression without the note.

@ydflow

ydflow commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

The current head is c2f1a35. The checks shown on the PR are passing, and I previously addressed the review feedback on this head. GitHub still shows review required. Could a maintainer check whether anything else is needed for review or merge?

ydflow and others added 2 commits November 4, 2026 09:12
…modes

Range and commit modes reviewed history, but filtered their changed files with
the working tree's .gitignore. A rule that exists only locally — an uncommitted
.gitignore, or one on the checked-out branch but not on the reviewed one —
silently dropped files out of the review while the run still exited 0. Reported
with a `feature` branch adding gen.go and no .gitignore, plus a local uncommitted
.gitignore ignoring it: `ocr review --from base --to feature` reviewed nothing.

A range review answers "what did this ref change", so the ignore rules that apply
are the ones the ref carries. Read them with `git show REF:.gitignore` instead;
a ref without one yields no patterns, which is what its history says. Workspace
mode keeps reading the working tree, because there the working tree is the thing
under review.

The exported LoadGitignorePatterns and the workspace paths in scan and file_find
are untouched: those callers were always working-tree semantics.
- Pin the positive half: the reviewed ref's own .gitignore still filters
  tracked files in range and commit modes. Without this, replacing the
  pattern load with nil passed all three existing tests.
- Propagate ctx.Err() from the ref read instead of swallowing it into
  "no ignore rules". Fail-open on other errors stays deliberate and is
  now stated in the comment.
- Drop the unreachable ref == "" branch (the only caller already checks
  the mode) and key the history-mode branch on p.mode instead of ref.
- Replace the duplicated gitOutput test helper with gitOut.
@ydflow
ydflow force-pushed the fix/range-mode-gitignore-from-ref branch from c2f1a35 to 17e60e7 Compare November 4, 2026 01:13
@ydflow

ydflow commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (abb7abc) — mergeable again, and the merge commit that was carrying stale upstream state is gone. The branch is two commits now instead of two commits plus a merge.

The rebase needed one real decision: main added a honorGitignore := p.mode != ModeWorkspace gate to partitionDiffs, which is the same function this PR splits so a history mode can pass the ignore patterns of the ref it reviews. Keeping only one side would have broken the other:

  • Keeping this branch's side alone would restore the bug main just fixed — partitionDiffs would apply .gitignore in workspace mode, where ignored untracked files are already filtered and applying the rules again drops tracked changes.
  • Keeping main's side alone would restore the bug this PR fixes — history modes would load patterns from the working tree again.

So partitionDiffs now delegates: it passes nil patterns in workspace mode and the working-tree patterns otherwise, and partitionDiffsWithPatterns keeps main's honorGitignore gate for the include/exclude decision. GetDiffSet is unchanged from this PR: a range or commit review still passes loadGitignorePatternsAtRef(ctx, ref).

Verified at 17e60e7:

  • go build ./... clean
  • go test ./internal/diff/... pass
  • go vet and gofmt -l clean

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.

Range and commit modes filter changed files with the working tree's ignore rules

3 participants