Skip to content

Use JGit to match .gitignore rules in unlinked files search - #17656

Merged
Siedlerchr merged 49 commits into
JabRef:mainfrom
Sandeep332005:fix-17546-gitignore-literal-brace
Nov 14, 2026
Merged

Siedlerchr merged 49 commits into
JabRef:mainfrom
Sandeep332005:fix-17546-gitignore-literal-brace

Conversation

@Sandeep332005

@Sandeep332005 Sandeep332005 commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixed an issue where a .gitignore pattern containing an unmatched literal opening brace caused JabRef to throw a PatternSyntaxException while searching for unlinked local files.

The pattern notes{draft.pdf was interpreted as Java glob syntax rather than a literal filename pattern. This caused the file scanning process to fail.

.gitignore rules are no longer converted to Java glob patterns. They are now matched with JGit's IgnoreNode, which follows git's own ignore semantics, so literal braces and other characters that are special in globs no longer cause errors. Regression tests were added to verify that the matching file is ignored and other files can still be processed.

The built-in ignores (.gitignore, .git, .DS_Store, desktop.ini, Thumbs.db) now always apply, also when a .gitignore file exists. Previously, they were used only when no .gitignore was found. A negation in the user's .gitignore (for example !desktop.ini) can override them.

Steps to test

  1. Start JabRef and open a library.

  2. Create a test directory containing notes{draft.pdf and paper.pdf.

  3. Create a .gitignore file inside the test directory.

  4. Add the following pattern:

    notes{draft.pdf
  5. Open Search for unlinked local files.

  6. Check the Event Log and verify that no PatternSyntaxException is thrown.

  7. Verify that notes{draft.pdf is ignored and paper.pdf remains available in the results.

Screenshot 1 – Unlinked Local Files dialog

Unlinked Local Files dialog before fix

The Search for unlinked local files dialog where the issue occurs during local file scanning.

Screenshot 2 – PatternSyntaxException in the Event Log

PatternSyntaxException before fix

The Event Log shows the PatternSyntaxException caused by the unmatched opening brace in notes{draft.pdf.

Screenshot 3 – Successful search after the fix

Successful unlinked file search after fix

After the fix, JabRef completes the unlinked local files search without the previous exception.

Related issues and pull requests

Closes #17546

AI usage

Claude Code (model: Claude Opus 5) — Used for understanding the issue, tracing the relevant code path, and reviewing the proposed solution.

I reviewed the implementation and regression tests and take responsibility for the submitted code.

The follow-up commit that lets .gitignore negations override the built-in ignores was made by a maintainer with Claude Code (model claude-opus-5-5) and reviewed by that maintainer.

1. Code self-review

Nullability and control flow

  • No unnecessary null checks introduced.
  • Existing nullability conventions preserved.
  • No unnecessary Objects.requireNonNull(...) calls introduced.

Exceptions

  • Only specific exceptions are caught.
  • PatternSyntaxException is handled where applicable.
  • No broad catch (Exception e) introduced.
  • Exception logging follows the project's logging conventions.

Style and idioms

  • Existing project coding conventions followed.
  • No commented-out code added.
  • No unnecessary comments added.
  • Changes are limited to the relevant file-filtering behavior.

Tests

  • Regression test added for a pattern containing a literal opening brace.
  • Test verifies that the matching file is ignored.
  • Test verifies that unrelated files remain accepted.
  • Existing relevant tests reviewed.

2. Verification commands

  • ./gradlew :jabgui:test --tests "*GitIgnoreFileFilterTest*" — targeted tests passed.
  • ./gradlew checkstyleMain checkstyleTest checkstyleJmh
  • ./gradlew modernizer
  • ./gradlew --no-configuration-cache :rewriteDryRun
  • ./gradlew javadoc
  • npx markdownlint-cli2 "CHANGELOG.md" — run on the changed changelog.

3. Documentation

  • Added a changelog entry describing the fix from the user's point of view.
  • Linked the related issue.
  • No additional requirements documentation needed for this bug fix.
  • No developer documentation changes needed.

4. Pull request

  • PR description follows the repository template.
  • HTML comments removed from the PR body.
  • Steps to test documented.
  • Screenshots included to demonstrate the issue and the application behavior.
  • All required checks completed successfully.
  • CHANGELOG.md merge conflict resolved.

Checklist

  • I own the copyright of the code submitted and I license it under the [MIT license]
  • If AI tools were used, I disclosed them in the AI usage section and reviewed, understood, and take full ownership of all AI-generated code.
  • I manually tested my changes in running JabRef.
  • I added JUnit tests for the change.
  • I added screenshots in the PR description.
  • I added one sentence to CHANGELOG.md describing the change from the user's point of view.
  • I checked the user documentation; a separate documentation PR is not needed for this bug fix.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Hey @Sandeep332005! 👋

Thank you for contributing to JabRef!

We have automated checks in place, based on which you will soon get feedback if any of them are failing. We also use Qodo for review assistance. It will update your pull request description with a review help and offer suggestions to improve the pull request.

After all automated checks pass, a maintainer will also review your contribution. Once that happens, you can go through their comments in the "Files changed" tab and act on them, or reply to the conversation if you have further inputs. You can read about the whole pull request process in our contribution guide.

Please ensure that your pull request is in line with our AI Usage Policy and make necessary disclosures.

@github-actions github-actions Bot added first contrib status: changes-required Pull requests that are not yet complete labels Nov 1, 2026
@qodo-code-review

qodo-code-review Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Use JGit ignore rules when searching for unlinked files

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Match .gitignore rules with JGit so literal braces cannot break unlinked-file searches.
• Apply built-in and ancestor ignore rules in order, allowing later negations to override earlier
 matches.
• Preserve Windows case-insensitive matching and directory-only rule behavior for symbolic links.
Diagram

graph TD
  Crawler["Unlinked files crawler"] --> Attributes["Entry attributes"] --> PdfFilter["Unlinked file filter"] --> IgnoreFilter{"JGit ignores?"} --> Results["Search results"]
  Defaults["Built-in rules"] --> IgnoreFilter
  Gitignore["Ancestor gitignores"] --> IgnoreFilter
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Escape special characters in Java globs
  • ➕ Smaller change to the existing matcher.
  • ➖ Addresses the brace exception without reliably reproducing Git rule precedence, negation, or path semantics.

Recommendation: Use the PR’s JGit approach: matching rules with a Git-aware parser addresses the underlying semantic mismatch, while an escape-only fix would leave other differences unresolved.

Files changed (6) +195 / -63

Bug fix (3) +94 / -63
GitIgnoreFileFilter.javaReplace Java glob matching with ordered JGit ignore rules +76/-53

Replace Java glob matching with ordered JGit ignore rules

• Parses built-in rules and ancestor '.gitignore' files with JGit, then applies their matches in precedence order so later negations can override earlier rules. Converts path components to Git-style separators, handles Windows case-insensitive matching, and accepts entry directory status without following symbolic links.

jabgui/src/main/java/org/jabref/gui/externalfiles/GitIgnoreFileFilter.java

UnlinkedFilesCrawler.javaPass entry attributes to both crawler filters +13/-9

Pass entry attributes to both crawler filters

• Enumerates directory entries and reads their attributes once. Uses followed-directory status for traversal and unlinked-file filtering, but the entry’s own directory status for ignore-rule matching.

jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java

UnlinkedPDFFileFilter.javaAllow callers to provide directory status +5/-1

Allow callers to provide directory status

• Adds an overload that accepts a precomputed directory flag, while retaining the existing filter interface method.

jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedPDFFileFilter.java

Tests (1) +79 / -0
GitIgnoreFileFilterTest.javaCover literal braces and ignore-rule edge cases +79/-0

Cover literal braces and ignore-rule edge cases

• Adds tests for ignoring a literal-brace filename without excluding unrelated files, built-in rule overrides, and nested rule precedence. Also covers Windows case matching, symbolic links under directory-only rules, and backslashes in filenames.

jabgui/src/test/java/org/jabref/gui/externalfiles/GitIgnoreFileFilterTest.java

Documentation (2) +22 / -0
CHANGELOG.mdDocument the unlinked-file search fix +1/-0

Document the unlinked-file search fix

• Adds a user-facing entry for searches failing when '.gitignore' contains a literal opening brace, with a link to the issue.

CHANGELOG.md

files.mdSpecify ignore precedence and path-matching requirements +21/-0

Specify ignore precedence and path-matching requirements

• Defines requirements for ordered built-in and ancestor rules, Windows case-insensitive matching, and directory-only rules applied to symbolic links.

docs/requirements/files.md

@qodo-code-review

qodo-code-review Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (2)

Grey Divider


Remediation recommended

1. Nested repositories lose unlinked PDFs 🐞 Bug
Description
GitIgnoreFileFilter loads every ancestor .gitignore without stopping at a nested repository’s
.git boundary. When an outer repository ignores nested/*.pdf and the nested repository has its
own .gitignore with no matching override, the crawler excludes PDFs that the nested repository’s
rules would leave visible.
Code

jabgui/src/main/java/org/jabref/gui/externalfiles/GitIgnoreFileFilter.java[R56-57]

+        for (Path current = path.toAbsolutePath(); current != null; current = current.getParent()) {
+            ancestors.add(current);
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An outer repository's `.gitignore` is applied to files inside a nested Git repository, hiding eligible PDFs.
## Fix Focus Areas
- jabgui/src/main/java/org/jabref/gui/externalfiles/GitIgnoreFileFilter.java[55-74]
- jabgui/src/test/java/org/jabref/gui/externalfiles/GitIgnoreFileFilterTest.java[114-125]
## Recommended Fix
When collecting ancestor ignore files, stop at the nearest enclosing Git repository boundary, including a `.git` directory or worktree `.git` file. Add a nested-repository test in which an outer rule matches a PDF but the nested repository's rules do not.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



View low (1)
Informational
2. Directory validation is copied into both search overloads 🐞 Bug
Description
The new package-private searchDirectory(Path, UnlinkedPDFFileFilter) copies the
null/Files.isDirectory guard that the private recursive overload still runs, and the private
overload still carries the stale "Return null" comment. The private overload also repeats the guard
for every recursed subdirectory, although the crawler has just classified each of those entries as a
directory, so the two copies can drift if one is edited later.
Code

jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java[R131-134]

+        if ((directory == null) || !Files.isDirectory(directory)) {
+            throw new IOException("Invalid directory for searching: %s".formatted(directory));
+        }
+        return searchDirectory(directory, unlinkedPDFFileFilter, new GitIgnoreFileFilter(directory));
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The directory validation now exists in both `searchDirectory` overloads, and the private one still has a stale "Return null" comment.
## Fix Focus Areas
- jabgui/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java[130-141]
## Recommended Fix
Keep the null/isDirectory guard in the package-private entry overload only. Remove the duplicate guard and its stale comment from the private recursive overload, since its callers already pass validated directories.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Resolved findings
1. Windows searches miss some ignored files ✓ Resolved

Resolving commit: 2a0ca2e

Resolution reason
N/A
Description
GitIgnoreFileFilter lowercases entire .gitignore rules before parsing them, changing a
character-class range such as [A-z] into [a-z]. On Windows, [A-z].pdf should match [.pdf,
but the transformed range excludes [ and lets that file through.

2. Other folders' rules hide matching PDFs ✓ Resolved
Description
GitIgnoreFileFilter walks parents of path.toAbsolutePath() without normalizing .. segments, so
it can load a .gitignore from a directory that is not an ancestor of the search directory. If a
user searches /root/other/../target and /root/other/.gitignore contains *.pdf, that unrelated
rule is applied to PDFs under /root/target, even when target has its own .gitignore.

3. Deep folders slow unlinked-file searches ✓ Resolved
Description
GitIgnoreFileFilter reads and parses every ancestor .gitignore each time searchDirectory
constructs a filter. In a chain of nested folders with an ignore file at each level, searching D
folders performs roughly D(D+1)/2 ignore-file reads and parses rather than one per ancestor file.

4. Manual-pull tests fail before updates ✓ Resolved
Description
remoteUpdateExecutor now queues updates submitted from the synchronizer’s worker thread, but the
manual-pull tests assert database state immediately after calling pullChanges(). Those pulls
submit their model changes through this executor, and the tests never drain the queue before
checking the client’s entries.

5. Nested ignores hide included PDFs ✓ Resolved
Description
GitIgnoreFileFilter adds the built-in rules to every new filter but reads only the nearest
.gitignore, losing negations from parent files. If the root file contains !.git/ and a
subdirectory has an empty .gitignore, the crawler rejects that subdirectory’s .git folder and
never reaches PDFs inside it; before this change, the nested filter did not apply the built-in
.git rule.

6. Explicitly included folders stay hidden ✓ Resolved
Description
GitIgnoreFileFilter parses DEFAULT_IGNORES after the user's .gitignore, so a default rule
takes precedence over an earlier negation such as !.git/. When that directory contains eligible
PDFs, accept() rejects the directory before the crawler can search its contents.

7. Two crawler tests pass without crawling ✓ Resolved
Description
searchDirectory now calls UnlinkedPDFFileFilter.accept(Path, boolean), but two existing crawler
tests stub only accept(Path). Mockito returns false for the unstubbed overload, so those tests
produce the expected empty tree without exercising the ignore rules they are meant to verify.

8. Chained directory filter left as dead code ⊘ Outdated
Description
searchDirectory used to be the only caller of ChainedFilters. It now calls
UnlinkedPDFFileFilter.accept(Path, boolean) and GitIgnoreFileFilter.accept(Path, boolean)
directly, so ChainedFilters has no callers in main or test code. A later reader may assume the
crawler still filters through it and change it, and that change will have no effect on the search.

9. File searches repeat metadata lookups ✓ Resolved
Description
GitIgnoreFileFilter.accept() now calls Files.isDirectory(path) even though the crawler
classifies the same entry in its preceding filter and, if accepted, again when partitioning results.
Large unlinked-file searches therefore perform an additional filesystem metadata lookup for every
entry that reaches the ignore filter, including entries on slower network storage.

10. Ignored PDFs can appear in search results ✓ Resolved
Description
GitIgnoreFileFilter catches a PatternSyntaxException and drops the ignore rule when a pattern
such as draft[.pdf reaches Java's glob parser. Git treats that unmatched bracket as literal, but
if the file is otherwise an eligible unlinked PDF, accept() allows it through to the search
results.

11. One vanished file hides sibling results ✓ Resolved
Description
searchDirectory reads each entry’s attributes inside a directory-wide try, so an IOException
returns the current node before the collected files are processed. If an entry disappears during
enumeration or its attributes cannot be read, valid PDFs elsewhere in that directory are omitted
from the search results.

12. The nullable ignore result lacks its marker ✓ Resolved
Description
ignored stores the nullable result of IgnoreNode.checkIgnored without a JSpecify @Nullable
type-use annotation. Because checkIgnored returns null when no rule matches and line 65 tests
that value, the local is explicitly nullable but remains unannotated.

13. Symlinked folders disappear from searches ✓ Resolved
Description
accept() uses Files.isDirectory(path), which follows symbolic links, and passes that result to
checkIgnored(). When a .gitignore contains a directory-only rule such as link/, a symlink
named link to a directory is treated as a matching directory and excluded before the crawler can
search its files.

14. Files with backslashes can be hidden ✓ Resolved
Description
accept() replaces every backslash in the relative path with /, including a literal backslash in
a Unix filename. If .gitignore contains dir/file.pdf, a distinct file named dir\file.pdf is
passed to checkIgnored() as dir/file.pdf and excluded from the unlinked-file search.

Grey Divider

Tip of the day
💡 Did you know, you can ask Qodo to dismiss a finding you disagree with, with your reason on record

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@jabref-machine jabref-machine added the dev: send-to-black-forest Port to the black-forest branch of JabRef/jabref-black-forest after merging (ADR-0073) label Nov 1, 2026
@github-actions github-actions Bot added status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers and removed status: changes-required Pull requests that are not yet complete labels Nov 1, 2026
@github-actions github-actions Bot added status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers and removed status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Nov 2, 2026
koppor
koppor previously requested changes Nov 2, 2026
@github-actions github-actions Bot added status: changes-required Pull requests that are not yet complete and removed status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Nov 2, 2026
Co-Authored-By: Claude Code <noreply@anthropic.com>
@github-actions github-actions Bot added status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers and removed status: changes-required Pull requests that are not yet complete labels Nov 2, 2026
@Sandeep332005
Sandeep332005 requested a review from koppor November 2, 2026 13:25
@github-actions github-actions Bot added status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers and removed status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Nov 2, 2026
@github-actions github-actions Bot added status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers and removed status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Nov 2, 2026
github-actions Bot and others added 7 commits November 9, 2026 05:42
…-literal-brace

* upstream/main:
  Chore(deps): Bump org.bouncycastle:bcprov-jdk18on from 1.86 to 1.87 in /versions (#17807)
  Chore(deps): Bump com.dlsc.gemsfx:gemsfx from 4.7.0 to 4.9.0 in /versions (#17806)
  Chore(deps): Bump gradle-wrapper from 9.9.0 to 9.9.1 (#17805)
  New Crowdin updates (#17804)
  chore(deps): update dependency org.apache.commons:commons-lang3 to v3.22.0 (#17799)
  Add review and edit workflow for citation imports (#17690)
  Chore(deps): Bump jablib/src/main/resources/csl-styles from `3220666` to `af0aea3` (#17788)
  Chore(deps): Bump us.hebi.graalvm:jfx-static-libs from 27-2 to 27.0.1 in /versions (#17796)
  chore(deps): update dependency org.bouncycastle:bcprov-jdk18on to v1.87 (#17794)
  Chore(deps): Bump actions/setup-java from 6.1.0 to 6.2.0 in /.github/actions/setup-gradle (#17795)
  Chore(deps): Bump actions/setup-java from 6.1.0 to 6.2.0 (#17792)
  Chore(deps): Bump docker/login-action from 4.7.0 to 4.8.0 (#17791)
  Chore(deps): Bump peter-evans/create-pull-request from 8.1.1 to 8.1.3 (#17793)
  Chore(deps): Bump anthropics/claude-code-action from 1.0.264 to 1.0.271 (#17790)
  Chore(deps): Bump ruby/setup-ruby from 1.336.0 to 1.338.0 (#17789)
  New Crowdin updates (#17785)
  Add "No value" subgroup to automatic keyword groups (#17716)
  Fix invalid XML for emoji and math symbols in DocBook export (#17765)
@Siedlerchr

Copy link
Copy Markdown
Member

@doraem-on I implemented your remainign feedback now

@github-actions

Copy link
Copy Markdown
Contributor

Do not mark a PR as ready-for-review if changes are required.
Address the changes first.

Siedlerchr and others added 4 commits November 12, 2026 19:50
…p332005/jabref into fix-17546-gitignore-literal-brace

* 'fix-17546-gitignore-literal-brace' of github.com:Sandeep332005/jabref:
  Added the word AS to the list of function words and JUnit Tests (#17751)
Siedlerchr
Siedlerchr previously approved these changes Nov 13, 2026
Siedlerchr
Siedlerchr previously approved these changes Nov 13, 2026
Siedlerchr
Siedlerchr previously approved these changes Nov 13, 2026
Siedlerchr
Siedlerchr previously approved these changes Nov 14, 2026
Siedlerchr
Siedlerchr previously approved these changes Nov 14, 2026
…m/Sandeep332005/jabref into fix-17546-gitignore-literal-brace

* 'fix-17546-gitignore-literal-brace' of https://github.com/Sandeep332005/jabref:
  Fix Markdown export fixture comparison on Windows
  Speed up sorting the main table by caching collation keys (#17762)
  Preserve literal characters in HTML paragraphs (#17779)
  Count braced organizations as one editor (#17781)
  Add Markdown publication exporter (#17598)
  Change OK button to Remove in three confirmation dialogs (#17565)
  test: serialize simulator model updates
  Add Test Cases For File-link Scenarios (#17645)
  Preserve uppercase named entities in HTML export (#17777)
  Improve icon colors and Shorten read-status and priority labels (#17691)
  Show effective file directory as prompt text in library properties (#17581)
  Chore(deps): Bump com.konghq:unirest-java-bom from 4.11.4 to 4.11.5 in /versions (#17813)
  Chore(deps): Bump org.apache.commons:commons-lang3 from 3.21.0 to 3.22.0 in /versions (#17814)
  New Crowdin updates (#17812)
  chore(deps): update dependency com.konghq:unirest-modules-gson to v4.11.5 (#17811)
@jabref-machine

Copy link
Copy Markdown
Collaborator

Created backport PR for black-forest:

Please cherry-pick the changes locally and resolve any conflicts.

git fetch origin port-17656-to-black-forest
git worktree add --checkout .worktree/port-17656-to-black-forest port-17656-to-black-forest
cd .worktree/port-17656-to-black-forest
git reset --hard HEAD^
git cherry-pick -x 47fa9f4686db045ca7559ff8e79e67f92c5d301a

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

Labels

component: export-or-save component: external-files component: shared-database dev: send-to-black-forest Port to the black-forest branch of JabRef/jabref-black-forest after merging (ADR-0073) first contrib size: medium status: to-be-merged PRs which are accepted and should go into the merge-queue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unlinked file search fails when .gitignore contains a literal opening brace

5 participants