Skip to content

Add auto-renaming of linked files on entry data change #13295

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

paudelritij
Copy link
Contributor

Closes #11316

This PR introduces an option to automatically rename linked files when the associated entry data is modified. The feature is configurable in Preferences under Linked files -> Linked file name conventions, with a default setting of false. It also includes handling for entries with multiple attached files and adds relevant test cases.

Steps to test

  1. Open JabRef and go to Preferences > Linked files.
  2. Enable [ ] Auto rename files if entry changes.
  3. Create a new entry and attach a file.
  4. Modify any field in the entry.
  5. Check that the linked file's name updates to match the new citation key.
  6. Test with multiple files to ensure all are renamed.
image

Mandatory checks

  • I own the copyright of the code submitted and I license it under the MIT license
  • Change in CHANGELOG.md described in a way that is understandable for the average user (if change is visible to the user)
  • Tests created for changes (if applicable)
  • Manually tested changed features in running JabRef (always required)
  • Screenshots added in PR description (if change is visible to the user)
  • Checked developer's documentation: Is the information available and up to date? If not, I outlined it in this pull request.
  • Checked documentation: Is the information available and up to date? If not, I created an issue at https://github.com/JabRef/user-documentation/issues or, even better, I submitted a pull request to the documentation repository.

- Implemented a preference option under Linked files -> Linked file name conventions to enable auto-renaming of files when entry data changes (default: false).
- Added functionality to listen for entry change events and rename files if the preference is enabled and the file name matches the defined pattern.
- Ensured that no action is taken if the pattern is empty, as the file name would not match.
- Considered scenarios where an entry has multiple files attached and handled them appropriately.
- Added test cases to verify the new functionality.
@@ -106,6 +109,18 @@ public void setStoreFilesRelativeToBibFile(boolean shouldStoreFilesRelativeToBib
this.storeFilesRelativeToBibFile.set(shouldStoreFilesRelativeToBibFile);
}

public boolean shouldAutoRenameFilesOnChange() {
Copy link

Choose a reason for hiding this comment

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

The method should return an Optional instead of a primitive boolean to avoid returning null and to align with modern Java practices.

@paudelritij paudelritij marked this pull request as ready for review June 10, 2025 00:56
}

private boolean relatesToFilePattern(String fileNamePattern, FieldChangedEvent event) {
Set<String> extractedFields = new HashSet<>();
Copy link

Choose a reason for hiding this comment

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

Using 'new HashSet<>()' is not optimal. Consider using 'Set.of()' for better readability and performance as per modern Java practices.

@koppor
Copy link
Member

koppor commented Jul 7, 2025

Ensure if the target file exists, do not use that name, use FileNameUniqueness.getNonOverWritingFileName(targetDirectory, targetFileName) to ensure that there is a unique other file name.

(Note to us: File should be kept even there are binary equal files. Otherwise, it gets complicated. E.g., if the same file is attached to another entry).

@paudelritij
Copy link
Contributor Author

Ensure if the target file exists, do not use that name, use FileNameUniqueness.getNonOverWritingFileName(targetDirectory, targetFileName) to ensure that there is a unique other file name.

(Note to us: File should be kept even there are binary equal files. Otherwise, it gets complicated. E.g., if the same file is attached to another entry).

I am trying implementing it in org.jabref.logic.externalfiles.LinkedFileHandler#renameToSuggestedName to put uniqueFileName. However, I'm encountering an issue with org.jabref.logic.search.indexing.DocumentReader#addMetaData, which is causing errors when reading timestamps. There may be creation of a loop where file changes name from e.g. abc.pdf to abc(1).pdf to abc.pdf again repeatedly. Any insights on how to resolve this would be greatly appreciated.

" ERROR: Could not read timestamp for /Users//Documents/JabRef/Gen28_ - Hands on Machine Learning with Scikit Learn, Keras, and TensorFlow.pdf: java.nio.file.NoSuchFileException: /Users//Documents/JabRef/Gen28_ - Hands on Machine Learning with Scikit Learn, Keras, and TensorFlow.pdf "

@koppor
Copy link
Member

koppor commented Jul 15, 2025

@LoayGhreeb Do you have some hints maybe?

@LoayGhreeb
Copy link
Member

I am trying implementing it in org.jabref.logic.externalfiles.LinkedFileHandler#renameToSuggestedName to put uniqueFileName. However, I'm encountering an issue with org.jabref.logic.search.indexing.DocumentReader#addMetaData, which is causing errors when reading timestamps. There may be creation of a loop where file changes name from e.g. abc.pdf to abc(1).pdf to abc.pdf again repeatedly. Any insights on how to resolve this would be greatly appreciated.

I don't think the problem is with the indexing itself. The NoSuchFileException means it's trying to access a file that doesn't exist, maybe it's still trying to use the old name, or the new one, but since there's a loop renaming the file back and forth, the file might not be available at the expected time during indexing.

I guess this loop could be happening if the same file is linked to two different entries. Could that be the case?

Please try to investigate further by adding some breakpoints to understand why, and where this loop is happening. Also, if possible, please push the commits that reproduce this issue, either here or in a new branch so we can take a proper look and help without guessing what's going on.

* of duplicate markers. For example, if "paper (1).pdf" is already linked to the entry and is the correct format,
* the method will return "paper (1).pdf" instead of generating "paper (2).pdf".
*/
public static String generateUniqueFileName(Path targetDirectory, String proposedName, String fileAlreadyInUse) {
Copy link

Choose a reason for hiding this comment

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

Method accepts null parameter 'fileAlreadyInUse' which violates modern Java practices of avoiding null parameters. Should use Optional instead.

@paudelritij
Copy link
Contributor Author

when using FileNameUniqueness.getNonOverWritingFileName(), a loop was occurring why?

  • Example: The original file name is paper_2082.pdf.
  • After renaming, the new name becomes paper1_2082.pdf. This triggers a file field change event.
  • On the next iteration, getSuggestedFileName() generates paper1_2082.pdf as the suggested name.
  • Since the file paper1_2082.pdf already exists (only we know that it is already linked to same entry), FileNameUniqueness.getNonOverWritingFileName() renames it to paper1_2082 (1).pdf.
  • This triggers another file field change event by generating file name again as paper1_2082.pdf (as it was in 1st place), and the process repeats, causing an infinite loop.

Solution Implemented

Case 1: File Exists but is Not Linked to the Entry: A new unique file name is suggested.
Case 2: File Exists and is Linked to the Entry: The file name change is discarded to prevent unnecessary renaming and event triggering.

Copy link
Member

@koppor koppor left a comment

Choose a reason for hiding this comment

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

I think, the loop comes from org.jabref.logic.cleanup.RenamePdfCleanup#cleanup

you can add some LOGGER.trace calls and adjust the log level (locally) to trace as desribed at https://devdocs.jabref.org/code-howtos/logging.html

Comment on lines +129 to +130
// create multiple entries
List<String> fileNames = List.of(
Copy link

Choose a reason for hiding this comment

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

Comment is trivial and doesn't add any new information beyond what's clearly visible in the code. The list creation is self-explanatory from the variable name and content.

Comment on lines +152 to +153
// Change author only
entry.setField(StandardField.AUTHOR, "newKey");
Copy link

Choose a reason for hiding this comment

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

The comment merely restates what the code does without providing additional context or reasoning. The code action is self-evident from the method call.

void noFileRenameByDefault() throws IOException {
Files.createFile(tempDir.resolve("oldKey2081.pdf"));
entry.setFiles(List.of(new LinkedFile("", "oldKey2081.pdf", "PDF")));
entry.setField(StandardField.AUTHOR, "newKey");
Copy link

Choose a reason for hiding this comment

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

Using setField instead of withField method for BibEntry modification. The code should use the wither pattern as per JabRef conventions.

Copy link

trag-bot bot commented Aug 2, 2025

@trag-bot didn't find any issues in the code! ✅✨

@paudelritij paudelritij requested a review from koppor August 4, 2025 00:15
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.

If entry data is changed, file name should also be changed
3 participants