jabref icon indicating copy to clipboard operation
jabref copied to clipboard

"Automatically set file links" doesn't work properly

Open ZiadAbdElFatah opened this issue 9 months ago • 39 comments

Steps to reproduce the behaviour

  1. Open a library example: test-support\src\manual-tests\issue-9798\example1\issue-9798_1.bib in JabRef.
  2. Select the entry in it and go to general. Image
  3. Add the correct file. Image
  4. Execute Automatically set file links. Image
  5. After executing Automatically set file links. Image

Configuration of library properties and the main file directory:

Image Image
  • The expected result is to relink the file links to the correct one and remove the broken one.

ZiadAbdElFatah avatar Feb 11 '26 13:02 ZiadAbdElFatah

Please also add some info on the configured file directories: https://docs.jabref.org/finding-sorting-and-cleaning-entries/filelinks#directories-for-files

The library is also saved?

Siedlerchr avatar Feb 11 '26 13:02 Siedlerchr

/assign-me

shubh1978 avatar Feb 11 '26 16:02 shubh1978

👋 Hey @shubh1978, thank you for your interest in this issue! 🎉

We're excited to have you on board. Start by exploring our Contributing guidelines, and set up your local development workspace by following the steps in our workspace setup guidelines to get started smoothly.

For questions on JabRef functionality, you can consult the JabRef Guru. For questions related to the codebase, please start using DeepWiki.

In case you encounter failing tests during development, please check our developer FAQs!

Still facing issues or having more questions? Feel free to ask here on GitHub or on JabRef's Gitter chat. Please don't hesitate to open a (draft) pull request early on to show the direction you are heading towards if unsure.

Happy coding! 🚀

jabref-machine avatar Feb 11 '26 17:02 jabref-machine

@ZiadAbdElFatah You are very welcome to link the PR you discovered. Your guess that it did not happen before, right?

koppor avatar Feb 11 '26 17:02 koppor

Hi @ZiadAbdElFatah i was able to reproduce the issue successfully but can you please explain how does this actually work and what was expected because the example pdf you shared just prints hello world so how is it supposed to link with other files and what files exactly and please also share your gitter.im username

shubh1978 avatar Feb 12 '26 09:02 shubh1978

Hi @koppor i am new to this repo can you please explain me what to do next and how to approach this issue and please also share your gitter.im username

shubh1978 avatar Feb 12 '26 09:02 shubh1978

Hi @koppor i am new to this repo can you please explain me what to do next and how to approach this issue and please also share your gitter.im username

Go to the Gitter JabRef community. There are 600+ users online. Someone should be able to help. Please also check https://docs.jabref.org/contributing or https://github.com/sponsors/koppor.

koppor avatar Feb 12 '26 15:02 koppor

Please also add some info on the configured file directories: https://docs.jabref.org/finding-sorting-and-cleaning-entries/filelinks#directories-for-files

I read the docs you provided here, but sorry I don't quite understand what you want me to do @Siedlerchr.

ZiadAbdElFatah avatar Feb 13 '26 06:02 ZiadAbdElFatah

@ZiadAbdElFatah You are very welcome to link the PR you discovered. Your guess that it did not happen before, right?

I investigated this PR https://github.com/JabRef/jabref/pull/14710 again, which I mentioned before, to make sure the feature is working properly. I accidentally found that External file types preference on my local machine was cleared. I restored it, and this was the real problem. Apologies for the disturbance. I think the issue should be closed now @koppor.

ZiadAbdElFatah avatar Feb 13 '26 06:02 ZiadAbdElFatah

@ZiadAbdElFatah You are very welcome to link the PR you discovered. Your guess that it did not happen before, right?

I investigated this PR https://github.com/JabRef/jabref/pull/14710 again, which I mentioned before, to make sure the feature is working properly. I accidentally found that External file types preference on my local machine was cleared. I restored it, and this was the real problem. Apologies for the disturbance. I think the issue should be closed now @koppor.

Nevertheless its an issue somehow.

I think automatically set file links should also work if no external file types are configured.

koppor avatar Feb 13 '26 06:02 koppor

Hi @ZiadAbdElFatah i was able to reproduce the issue successfully but can you please explain how does this actually work and what was expected because the example pdf you shared just prints hello world so how is it supposed to link with other files and what files exactly and please also share your gitter.im username

It is supposed to relink the file with its right file path. You can check this https://github.com/JabRef/jabref/issues/9798 and this https://github.com/JabRef/jabref/pull/14710 they will clarify a lot @shubh1978.

ZiadAbdElFatah avatar Feb 13 '26 07:02 ZiadAbdElFatah

Ok @ZiadAbdElFatah thanks a lot

shubh1978 avatar Feb 13 '26 07:02 shubh1978

@ZiadAbdElFatah To better reproduce the issue we need the values of the configured file directories. e.g. just add screenshots of the configuration (library properties and the main file directory

Siedlerchr avatar Feb 13 '26 09:02 Siedlerchr

@ZiadAbdElFatah Even though you might have the default configuration, it is interesting to know. The full configuration possibilites are posted at https://docs.jabref.org/finding-sorting-and-cleaning-entries/filelinks#directories-for-files.

koppor avatar Feb 13 '26 11:02 koppor

Hi @koppor and @ZaidAbdElFatah i have been stuck on this issue since few days but i am not able to ressolve it can you please review the code and tell me what's wrong

AutoSetFileUtil

package org.jabref.gui.externalfiles;

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Collectors; import java.util.stream.Stream;

import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.frame.ExternalApplicationsPreferences; import org.jabref.logic.FilePreferences; import org.jabref.logic.bibtex.FileFieldWriter; import org.jabref.logic.util.io.AutoLinkPreferences; import org.jabref.logic.util.io.FileFinder; import org.jabref.logic.util.io.FileFinders; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile;

import org.slf4j.Logger; import org.slf4j.LoggerFactory;

public class AutoSetFileLinksUtil {

public static class LinkFilesResult {
    private final List<BibEntry> changedEntries = new ArrayList<>();
    private final List<IOException> fileExceptions = new ArrayList<>();

    protected void addBibEntry(BibEntry bibEntry) {
        changedEntries.add(bibEntry);
    }

    protected void addFileException(IOException exception) {
        fileExceptions.add(exception);
    }

    public List<BibEntry> getChangedEntries() {
        return changedEntries;
    }

    public List<IOException> getFileExceptions() {
        return fileExceptions;
    }
}

private static final Logger LOGGER = LoggerFactory.getLogger(AutoSetFileLinksUtil.class);

private final List<Path> directories;
private final AutoLinkPreferences autoLinkPreferences;
private final ExternalApplicationsPreferences externalApplicationsPreferences;
private final FileFinder preConfiguredFileFinder;
private final FileFinder brokenLinkedFileNameBasedFileFinder;

public AutoSetFileLinksUtil(BibDatabaseContext databaseContext,
                            ExternalApplicationsPreferences externalApplicationsPreferences,
                            FilePreferences filePreferences,
                            AutoLinkPreferences autoLinkPreferences) {

    List<Path> dirs = new ArrayList<>(databaseContext.getFileDirectories(filePreferences));

    databaseContext.getDatabasePath().ifPresent(dbPath -> {
        Path parent = dbPath.getParent();
        if (parent != null) {
            try (Stream<Path> walk = Files.walk(parent)) {
                walk.filter(Files::isDirectory)
                    .forEach(dir -> {
                        if (!dirs.contains(dir)) {
                            dirs.add(dir);
                        }
                    });
            } catch (IOException e) {
                LOGGER.error("Error walking directories", e);
            }
        }
    });

    this.directories = dirs;

    // FIX 1: ensure non-null preferences
    this.autoLinkPreferences =
            autoLinkPreferences != null
            ? autoLinkPreferences
            : new AutoLinkPreferences(
                    AutoLinkPreferences.CitationKeyDependency.EXACT,
                    ".*",
                    true,
                    '.'
            );

    this.externalApplicationsPreferences = externalApplicationsPreferences;

    // FIX 2: USE this.autoLinkPreferences, NOT autoLinkPreferences
    this.preConfiguredFileFinder =
            FileFinders.constructFromConfiguration(this.autoLinkPreferences);

    this.brokenLinkedFileNameBasedFileFinder =
            FileFinders.constructBrokenLinkedFileNameBasedFileFinder();

    System.out.println("DEBUG finder = " + this.preConfiguredFileFinder);
}

private AutoSetFileLinksUtil(List<Path> directories, ExternalApplicationsPreferences externalApplicationsPreferences, AutoLinkPreferences autoLinkPreferences) {
    this.directories = directories;
    this.autoLinkPreferences = autoLinkPreferences;
    this.externalApplicationsPreferences = externalApplicationsPreferences;
    this.preConfiguredFileFinder = FileFinders.constructFromConfiguration(autoLinkPreferences);
    this.brokenLinkedFileNameBasedFileFinder = FileFinders.constructBrokenLinkedFileNameBasedFileFinder();
}

/// [impl->req~logic.externalfiles.file-transfer.auto-link~1]
public LinkFilesResult linkAssociatedFiles(List<BibEntry> entries, BiConsumer<List<LinkedFile>, BibEntry> onAddLinkedFile) {
    LinkFilesResult result = new LinkFilesResult();

    for (BibEntry entry : entries) {
        doLinkAssociatedFiles(entry, onAddLinkedFile, result);
    }
    return result;
}

/// Source of associated not linked files:
///   - Part A. match file name with CitationKey, (START, EXACT, REGEX) configured by user
///   - Part B. match file name with broken linked file names, currently silently happen
///
/// The auto-link process:
///   - Prolog: we only consider the file with a unique name
///       - if a file's name is found multiple times in Part A, we do not consider it in Step 1
///       - if a file's name is found multiple times in Part B, we do not consider it in Step 2
///   - Step 1. try to auto link each broken linked file with Part A at first. For unlinked files left in Part A, if no
///         linked file with same name exists, add them
///       - why `add`: Part A are found mainly by CitationKey, which has strong connection to the entry, so we are
///                    confident that we should add them automatically
///   - Step 2. try to auto link each broken linked file with Part B.
///       - how about `unlinked files left in Part B`: those files have the same name with one broken linked file
///                    but different extension. We skip those files.
///       - one trick: we accumulate Part B after Step 1, so Part A does not affect those broken linked files we use
///                    to query Part B
private void doLinkAssociatedFiles(
        BibEntry entry,
        BiConsumer<List<LinkedFile>, BibEntry> onAddLinkedFile,
        LinkFilesResult result) {

    Map<String, LinkedFile> foundFiles =
            getAssociatedFiles(entry, result, preConfiguredFileFinder);

    if (foundFiles.isEmpty()) {
        return;
    }

    List<LinkedFile> updatedFiles = new ArrayList<>(entry.getFiles());

    boolean entryUpdated = false;

    for (LinkedFile newFile : foundFiles.values()) {

        boolean alreadyLinkedAndValid =
                updatedFiles.stream()
                            .anyMatch(existing ->
                                    existing.findIn(directories).isPresent()
                                            &&
                                            newFile.findIn(directories).isPresent()
                                            &&
                                            existing.findIn(directories).get()
                                                    .equals(newFile.findIn(directories).get())
                            );

        if (!alreadyLinkedAndValid) {

            System.out.println("DEBUG: ADDING OR FIXING → " + newFile.getLink());

            updatedFiles.removeIf(existing ->
                    existing.findIn(directories).isEmpty()
            );

            updatedFiles.add(newFile);

            entryUpdated = true;
        }
    }

    if (entryUpdated) {

        System.out.println("DEBUG: ENTRY UPDATED");

        onAddLinkedFile.accept(updatedFiles, entry);

        result.addBibEntry(entry);
    }
}

private boolean filesChanged(List<LinkedFile> newLinkedFiles, List<LinkedFile> files) {
    String newValue = FileFieldWriter.getStringRepresentation(newLinkedFiles);
    String oldValue = FileFieldWriter.getStringRepresentation(files);

    return !Objects.equals(newValue, oldValue);
}

private List<LinkedFile> autoLinkBrokenLinkedFiles(List<LinkedFile> linkedFiles, Map<String, LinkedFile> files) {
    List<LinkedFile> updated = new ArrayList<>();

    for (LinkedFile linkedFile : linkedFiles) {
        String fileName = FileUtil.getBaseName(linkedFile.getLink());
        Optional<String> extension = FileUtil.getFileExtension(linkedFile.getLink());

        if (isBrokenLinkedFile(linkedFile)
                && files.containsKey(fileName)
                && extension.isPresent()
                && extension.get().equalsIgnoreCase(files.get(fileName).getFileType())) {

            // FIX: update existing object, DO NOT replace
            linkedFile.setLink(files.get(fileName).getLink());

            updated.add(linkedFile);
            files.remove(fileName);

        } else {
            updated.add(linkedFile);
        }
    }

    return updated;
}


private Map<String, LinkedFile> getAssociatedFiles(BibEntry entry, LinkFilesResult result, FileFinder finder) {
    Map<String, LinkedFile> files;
    try {
        files = findAssociatedNotLinkedFilesWithUniqueName(entry, finder);
    } catch (IOException e) {
        result.addFileException(e);
        LOGGER.error("Problem finding files", e);
        files = Map.of();
    }
    return files;
}

private Map<String, LinkedFile> findAssociatedNotLinkedFilesWithUniqueName(
        BibEntry entry,
        FileFinder finder) throws IOException {

    Collection<LinkedFile> files =
            findAssociatedNotLinkedFilesWithFinder(entry, finder, getConfiguredExtensions());

    Map<String, LinkedFile> result = new HashMap<>();

    for (LinkedFile file : files) {

        String fileName = FileUtil.getBaseName(file.getLink());

        result.putIfAbsent(fileName, file);
    }

    return result;
}

/// Scans for missing files which should be linked to the given entry.
///
/// Related: {@link org.jabref.gui.externalfiles.UnlinkedFilesCrawler} for scanning files missing at all entries
///
/// NOTE:
/// 1. This method does not check if the file is already linked to another entry.
/// 2. This method does not guarantee how the returned files are ordered. Order by how they appear in BibEntry does
///    not work since findAssociatedFilesByBrokenLinkedFile may return multiple files (with the same name) for one
///    broken linked file in the entry.
public Collection<LinkedFile> findAssociatedNotLinkedFiles(BibEntry entry) throws IOException {
    // Find the associated files
    List<String> extensions = getConfiguredExtensions();
    LOGGER.debug("Searching for associated not linked files with extensions {} in directories {}", extensions, directories);
    return Stream.concat(
                         findAssociatedNotLinkedFilesWithFinder(entry, preConfiguredFileFinder, extensions).stream(),
                         findAssociatedNotLinkedFilesWithFinder(entry, brokenLinkedFileNameBasedFileFinder, extensions).stream())
                 .distinct()
                 .toList();
}

public Collection<LinkedFile> findAssociatedNotLinkedFilesWithFinder(
        BibEntry entry, FileFinder finder, List<String> extensions) throws IOException {

    List<LinkedFile> result = new ArrayList<>();

    Optional<String> citationKeyOpt = entry.getCitationKey();

    if (citationKeyOpt.isEmpty()) {
        return result;
    }

    String citationKey = citationKeyOpt.get();

    for (Path dir : directories) {

        try (Stream<Path> walk = Files.walk(dir)) {

            walk.filter(Files::isRegularFile)
                .forEach(path -> {

                    System.out.println("DEBUG citationKey = " + citationKey);
                    System.out.println("DEBUG found file = " + path);
                    System.out.println("DEBUG basename = " + FileUtil.getBaseName(path));

                    Optional<String> ext = FileUtil.getFileExtension(path);

                    if (ext.isEmpty()) return;

                    if (!extensions.contains(ext.get())) return;

                    String fileName = FileUtil.getBaseName(path);

                    if (citationKey.equals(fileName)) {

                        System.out.println("MATCH FOUND");

                        result.add(buildLinkedFileFromPath(path));
                    }
                });

        }
    }

    return result;
}

private boolean isBrokenLinkedFile(LinkedFile file) {
    return file.findIn(directories).isEmpty();
}

private LinkedFile buildLinkedFileFromPath(Path associatedFile) {
    String strType = checkAndGetFileType(associatedFile);
    Path relativeFilePath = FileUtil.relativize(associatedFile, directories);
    return new LinkedFile("", relativeFilePath, strType);
}

private List<String> getConfiguredExtensions() {
    return externalApplicationsPreferences
            .getExternalFileTypes()
            .stream().map(ExternalFileType::getExtension).toList();
}

private String checkAndGetFileType(Path associatedFile) {
    return FileUtil.getFileExtension(associatedFile)
                   .flatMap(extension ->
                           ExternalFileTypes.getExternalFileTypeByExt(
                                   extension,
                                   externalApplicationsPreferences
                           ))
                   .map(ExternalFileType::getName).orElse("");
}

private static boolean isFileAlreadyLinked(Path foundFile, List<Path> linkedFiles) {
    return linkedFiles.stream()
                      .anyMatch(linked -> {
                          try {
                              return Files.isSameFile(linked, foundFile);
                          } catch (IOException e) {
                              LOGGER.debug("Unable to check file identity, assuming no identity", e);
                              return false;
                          }
                      });
}

}

AutoLinkFilesAction

package org.jabref.gui.externalfiles;

import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; import java.util.stream.Collectors;

import javax.swing.undo.UndoManager;

import javafx.concurrent.Task;

import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.preferences.GuiPreferences; import org.jabref.gui.undo.NamedCompoundEdit; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.BindingsHelper; import org.jabref.gui.util.UiTaskExecutor; import org.jabref.logic.bibtex.FileFieldWriter; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.AutoLinkPreferences; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.field.StandardField;

import static org.jabref.gui.actions.ActionHelper.needsDatabase; import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected;

/// This Action may only be used in a menu or button. /// Never in the entry editor. FileListEditor and EntryEditor have other ways to update the file links public class AutoLinkFilesAction extends SimpleCommand {

private final DialogService dialogService;
private final GuiPreferences preferences;
private final StateManager stateManager;
private final UndoManager undoManager;
private final UiTaskExecutor taskExecutor;

public AutoLinkFilesAction(DialogService dialogService, GuiPreferences preferences, StateManager stateManager, UndoManager undoManager, UiTaskExecutor taskExecutor) {
    this.dialogService = dialogService;
    this.preferences = preferences;
    this.stateManager = stateManager;
    this.undoManager = undoManager;
    this.taskExecutor = taskExecutor;

    this.executable.bind(needsDatabase(this.stateManager).and(needsEntriesSelected(stateManager)));
    this.statusMessage.bind(BindingsHelper.ifThenElse(executable, "", Localization.lang("This operation requires one or more entries to be selected.")));
}

@Override
public void execute() {
    final BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null"));
    final List<BibEntry> entries = stateManager.getSelectedEntries();

    AutoLinkPreferences autoLinkPrefs = preferences.getAutoLinkPreferences();

    if (autoLinkPrefs == null) {
        autoLinkPrefs = new AutoLinkPreferences(
                AutoLinkPreferences.CitationKeyDependency.EXACT,
                "",
                true,
                '_'
        );

        System.out.println("DEBUG: Created fallback AutoLinkPreferences");
    }

    AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(
            database,
            preferences.getExternalApplicationsPreferences(),
            preferences.getFilePreferences(),
            autoLinkPrefs);

    final NamedCompoundEdit nc = new NamedCompoundEdit(Localization.lang("Automatically set file links"));

    Task<AutoSetFileLinksUtil.LinkFilesResult> linkFilesTask = new Task<>() {
        final BiConsumer<List<LinkedFile>, BibEntry> onLinkedFilesUpdated =
                (newLinkedFiles, entry) -> {

                    String newVal =
                            FileFieldWriter.getStringRepresentation(newLinkedFiles);

                    String oldVal =
                            entry.getField(StandardField.FILE).orElse(null);

                    UndoableFieldChange change =
                            new UndoableFieldChange(
                                    entry,
                                    StandardField.FILE,
                                    oldVal,
                                    newVal);

                    nc.addEdit(change);

                    UiTaskExecutor.runAndWaitInJavaFXThread(() -> {

                        entry.setFiles(newLinkedFiles);

                    });
                };

        @Override
        protected AutoSetFileLinksUtil.LinkFilesResult call() {
            return util.linkAssociatedFiles(entries, onLinkedFilesUpdated);
        }

        @Override
        protected void succeeded() {
            AutoSetFileLinksUtil.LinkFilesResult result = getValue();

            if (!result.getFileExceptions().isEmpty()) {
                dialogService.showWarningDialogAndWait(
                        Localization.lang("Automatically set file links"),
                        Localization.lang("Problem finding files. See error log for details."));
                return;
            }

            if (result.getChangedEntries().isEmpty()) {
                dialogService.showWarningDialogAndWait(
                        Localization.lang("Automatically set file links"),
                        Localization.lang("Finished automatically setting external links.") + "\n"
                                + Localization.lang("No files found."));
                return;
            }

            if (nc.hasEdits()) {
                nc.end();
                undoManager.addEdit(nc);
            }

            dialogService.notify("%s %s\n%s".formatted(
                    Localization.lang("Finished automatically setting external links."),
                    Localization.lang("Changed %0 entry(s).", result.getChangedEntries().size()),
                    Localization.lang("Affected entry(s): %0", result.getChangedEntries().stream()
                                                                     .map(BibEntry::getCitationKey)
                                                                     .flatMap(Optional::stream)
                                                                     .collect(Collectors.joining(", ")))));
        }
    };

    dialogService.showProgressDialog(
            Localization.lang("Automatically setting file links"),
            Localization.lang("Searching for files"),
            linkFilesTask);
    taskExecutor.execute(linkFilesTask);
}

}

Image Image

shubh1978 avatar Feb 16 '26 04:02 shubh1978

Hi @koppor i fixed the issue now can you please review the pr

https://github.com/JabRef/jabref/pull/15124

shubh1978 avatar Feb 16 '26 05:02 shubh1978

Hi @koppor i fixed the issue now can you please review the pr

Fix boz comments first before pinging a maintainer. Thank you

koppor avatar Feb 16 '26 06:02 koppor

HI @koppor now i have resolved all the required test cases so can you please review my pr

shubh1978 avatar Feb 19 '26 16:02 shubh1978

/assign-me

PedroVanini avatar Apr 06 '26 16:04 PedroVanini

👋 Hey @PedroVanini, thank you for your interest in this issue! 🎉

We're excited to have you on board. Start by exploring our Contributing guidelines, and set up your local development workspace by following the steps in our workspace setup guidelines to get started smoothly.

For questions on JabRef functionality, you can consult the JabRef Guru. For questions related to the codebase, please start using DeepWiki.

In case you encounter failing tests during development, please check our developer FAQs!

Still facing issues or having more questions? Feel free to ask here on GitHub or on JabRef's Gitter chat. Please don't hesitate to open a (draft) pull request early on to show the direction you are heading towards if unsure.

Happy coding! 🚀

jabref-machine avatar Apr 06 '26 16:04 jabref-machine