Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv

- We fixed an issue where JabRef closed when a client of the integrated language server disconnected. [#17303](https://github.com/JabRef/jabref/pull/17303)
- We fixed an issue where entries containing dollar signs or backslashes caused citation style preview and export to fail. [#12799](https://github.com/JabRef/jabref/issues/12799)
- We fixed an issue where legacy group memberships, markings, and special fields were no longer migrated when opening a library. [#17019](https://github.com/JabRef/jabref/pull/17019)
- We fixed an issue where the Hayagriva YAML export wrote braced author names, such as company names, as invalid YAML. [#17316](https://github.com/JabRef/jabref/issues/17316)
- We fixed the BibTeX source dialog background in the Citation Relations tab for dark themes. [#13599](https://github.com/JabRef/jabref/issues/13599)
- We fixed an issue where "Regenerate (custom)" in the AI summary ignored the chosen summarization algorithm. [#17216](https://github.com/JabRef/jabref/issues/17216)
Expand Down
19 changes: 19 additions & 0 deletions docs/code-howtos/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,25 @@ void convertsToUpperCamelCase(String input, String expected) {
}
```

## Legacy library migration profiling

Generate a deterministic 100,000-entry migration fixture from the repository root:

```sh
python3 scripts/bib-file-generator_legacy.py
```

The script creates `generated-large-legacy-library.bib` and refuses to overwrite an existing file.
Use `--entries`, `--separator`, and `--output` for smaller fixtures or libraries with a semicolon keyword separator.
The fixture contains large and overlapping explicit groups, nested hierarchy modes, duplicate and missing citation keys, markings, and special field values stored in keywords.
It also includes keyword, regular-expression, search, automatic, and legacy smart groups.

Measure parsing separately from `PerformLoadDatabaseMigrations` with a JVM flight recording.
Migration runs before GUI attachment: only conversions with remaining legacy content run, using temporarily detached entries and a single citation-key index.
Entries are reinserted in a batch to restore observation and database indices, and the library is marked modified so the converted representation can be saved.
A localized notification announces migration when legacy content is found.
Save and reopen the fixture to verify that no conversion runs again; the content checks still run to detect legacy data in mixed-format libraries.

## Coverage

IntelliJ has build in test coverage reports. Choose "Run with coverage".
Expand Down
23 changes: 23 additions & 0 deletions docs/requirements/import.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,27 @@ Rationale: Closing the tab prevents leaving an empty, untitled library that the

Needs: impl, utest

## Legacy libraries must be migrated when opened
`req~import.bibtex.legacy-migrations~1`

Opening a library written by JabRef 2.x/3.x converts its legacy content to the current representation: explicit group memberships stored inside the group tree move to the entries' `groups` field, `__markedentry` markings become groups, and special field values stored in `keywords` move to their own fields.
The keyword separator used for splitting is the library's own, falling back to the configured one.

Needs: impl, utest

## Libraries without legacy content must skip legacy migration
`req~import.bibtex.legacy-migrations.only-when-needed~1`

After conversion and saving, reopening the library does not convert entries or rebuild the entries list again.
Legacy content is identified by group membership keys, entry markings, and special field values in keywords, including in mixed-format libraries.

Needs: impl, utest

## Legacy library migration must announce conversion
`req~import.bibtex.legacy-migrations.announcement~1`

When legacy content is detected during opening, a localized notification names the library before conversion starts.

Needs: impl, utest

<!-- markdownlint-disable-file MD022 -->
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.jabref.logic.util.TaskExecutor;
import org.jabref.logic.util.io.FileHistory;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.migrations.PerformLoadDatabaseMigrations;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.util.FileUpdateMonitor;

Expand Down Expand Up @@ -276,6 +277,13 @@ ParserResult loadDatabase(Path file) throws NotASharedDatabaseException, SQLExce
preferences.getImportFormatPreferences(),
fileUpdateMonitor);
}

// [impl->req~import.bibtex.legacy-migrations~1]
PerformLoadDatabaseMigrations.performLoadDatabaseMigrations(
parserResult,
parserResult.getDatabaseContext().getKeywordSeparator(preferences.getImportFormatPreferences().bibEntryPreferences().getKeywordSeparator()),
// [impl->req~import.bibtex.legacy-migrations.announcement~1]
() -> dialogService.notify(Localization.lang("Migrating library '%0' to the current version", fileToLoad.toString())));
} catch (IOException e) {
parserResult = ParserResult.fromError(e);
LOGGER.error("Error opening file '{}'", fileToLoad, e);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package org.jabref.migrations;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jabref.logic.importer.ParserResult;
import org.jabref.model.entry.BibEntry;
Expand All @@ -15,14 +17,31 @@
public class ConvertLegacyExplicitGroups implements PostOpenMigration {

@Override
public void performMigration(@NonNull ParserResult parserResult) {
public boolean isMigrationNecessary(ParserResult parserResult) {
return parserResult.getMetaData().getGroups()
.map(root -> !getExplicitGroupsWithLegacyKeys(root).isEmpty())
.orElse(false);
}

@Override
public void performMigration(@NonNull ParserResult parserResult, List<BibEntry> entries) {
if (parserResult.getMetaData().getGroups().isEmpty()) {
return;
}

for (ExplicitGroup group : getExplicitGroupsWithLegacyKeys(parserResult.getMetaData().getGroups().get())) {
List<ExplicitGroup> groups = getExplicitGroupsWithLegacyKeys(parserResult.getMetaData().getGroups().orElseThrow());
if (groups.isEmpty()) {
return;
}

Map<String, List<BibEntry>> entriesByCitationKey = new HashMap<>();
for (BibEntry entry : entries) {
entry.getCitationKey().ifPresent(key -> entriesByCitationKey.computeIfAbsent(key, _ -> new ArrayList<>()).add(entry));
}

for (ExplicitGroup group : groups) {
for (String entryKey : group.getLegacyEntryKeys()) {
for (BibEntry entry : parserResult.getDatabase().getEntriesByCitationKey(entryKey)) {
for (BibEntry entry : entriesByCitationKey.getOrDefault(entryKey, List.of())) {
group.add(entry);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javafx.collections.ObservableList;

import org.jabref.logic.groups.GroupsFactory;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
Expand All @@ -28,20 +26,31 @@ public class ConvertMarkingToGroups implements PostOpenMigration {

private static final Pattern MARKING_PATTERN = Pattern.compile("\\[(.*):(\\d+)\\]");

private final Character keywordSeparator;

public ConvertMarkingToGroups(Character keywordSeparator) {
this.keywordSeparator = keywordSeparator;
}

@Override
public boolean isMigrationNecessary(ParserResult parserResult) {
return parserResult.getDatabase().getEntries().stream()
.anyMatch(entry -> entry.getField(InternalField.MARKED_INTERNAL).isPresent());
}

@Override
public void performMigration(@NonNull ParserResult parserResult) {
ObservableList<BibEntry> entries = parserResult.getDatabase().getEntries();
public void performMigration(@NonNull ParserResult parserResult, List<BibEntry> entries) {
Multimap<String, BibEntry> markings = getMarkingWithEntries(entries);
if (!markings.isEmpty()) {
GroupTreeNode markingRoot = GroupTreeNode.fromGroup(
new ExplicitGroup(Localization.lang("Markings"), GroupHierarchyType.INCLUDING, ','));
new ExplicitGroup(Localization.lang("Markings"), GroupHierarchyType.INCLUDING, keywordSeparator));

for (Map.Entry<String, Collection<BibEntry>> marking : markings.asMap().entrySet()) {
String markingName = marking.getKey();
Collection<BibEntry> markingMatchedEntries = marking.getValue();

GroupTreeNode markingGroup = markingRoot.addSubgroup(
new ExplicitGroup(markingName, GroupHierarchyType.INCLUDING, ','));
new ExplicitGroup(markingName, GroupHierarchyType.INCLUDING, keywordSeparator));
markingGroup.addEntriesToGroup(markingMatchedEntries);
}

Expand All @@ -67,7 +76,7 @@ private Multimap<String, BibEntry> getMarkingWithEntries(List<BibEntry> entries)
}

Matcher matcher = MARKING_PATTERN.matcher(marking.get());
if (matcher.find()) {
if (matcher.matches()) {
String owner = matcher.group(1);
String number = matcher.group(2);
markings.put(owner + ":" + number, entry);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,50 @@
package org.jabref.migrations;

import java.util.Arrays;
import java.util.List;

import org.jabref.logic.importer.ParserResult;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;

public class PerformLoadDatabaseMigrations {

// FIXME: Should be called somewhere
// Typical call: performLoadDatabaseMigrations(result, importFormatPreferences.bibEntryPreferences().getKeywordSeparator());
public static void performLoadDatabaseMigrations(ParserResult parserResult,
Character keywordDelimited) {
List<PostOpenMigration> postOpenMigrations = Arrays.asList(
Character keywordSeparator) {
performLoadDatabaseMigrations(parserResult, keywordSeparator, () -> {
});
}

/// Run before attaching the parsed library to GUI listeners.
// [impl->req~import.bibtex.legacy-migrations.only-when-needed~1]
public static void performLoadDatabaseMigrations(ParserResult parserResult,
Character keywordSeparator,
Runnable onMigrationStarted) {
List<PostOpenMigration> postOpenMigrations = List.of(
new ConvertLegacyExplicitGroups(),
new ConvertMarkingToGroups(),
new SpecialFieldsToSeparateFields(keywordDelimited)
new ConvertMarkingToGroups(keywordSeparator),
new SpecialFieldsToSeparateFields(keywordSeparator)
);

for (PostOpenMigration migration : postOpenMigrations) {
migration.performMigration(parserResult);
List<PostOpenMigration> necessaryMigrations = postOpenMigrations.stream()
.filter(migration -> migration.isMigrationNecessary(parserResult))
.toList();
if (necessaryMigrations.isEmpty()) {
return;
}
onMigrationStarted.run();

// Before the library is attached to the GUI, detach the extractor-backed entries list so each migrated
// field does not trigger a scan of the whole library. Reinsert the same entries to rebuild its indices.
BibDatabase database = parserResult.getDatabase();
List<BibEntry> entries = database.getEntriesSnapshot();
database.removeEntries(entries);
try {
for (PostOpenMigration migration : necessaryMigrations) {
migration.performMigration(parserResult, entries);
}
} finally {
database.insertEntries(entries);
}
parserResult.setChangedOnMigration(true);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
package org.jabref.migrations;

import java.util.List;

import org.jabref.logic.importer.ParserResult;
import org.jabref.model.entry.BibEntry;

public interface PostOpenMigration {
void performMigration(ParserResult parserResult);
boolean isMigrationNecessary(ParserResult parserResult);

default void performMigration(ParserResult parserResult) {
performMigration(parserResult, parserResult.getDatabase().getEntries());
}

/// Entries may be temporarily detached from the database to avoid per-field observable-list scans.
void performMigration(ParserResult parserResult, List<BibEntry> entries);
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.jabref.model.entry.KeywordList;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.model.entry.field.SpecialFieldValue;
import org.jabref.model.entry.field.StandardField;

public class SpecialFieldsToSeparateFields implements PostOpenMigration {
private final KeywordList possibleKeywordsToMigrate;
Expand All @@ -30,13 +31,21 @@ public SpecialFieldsToSeparateFields(Character keywordDelimiter) {
}

@Override
public void performMigration(ParserResult parserResult) {
parserResult.getDatabase().getEntries().forEach(this::migrateEntry);
public boolean isMigrationNecessary(ParserResult parserResult) {
return parserResult.getDatabase().getEntries().stream()
.filter(entry -> entry.hasField(StandardField.KEYWORDS))
.anyMatch(entry -> possibleKeywordsToMigrate.stream().anyMatch(entry.getKeywords(keywordDelimiter)::contains));
}

@Override
public void performMigration(ParserResult parserResult, List<BibEntry> entries) {
entries.forEach(this::migrateEntry);
}

private void migrateEntry(BibEntry entry) {
KeywordList keywords = entry.getKeywords(keywordDelimiter);
for (Keyword keyword : possibleKeywordsToMigrate) {
if (entry.getKeywords(keywordDelimiter).contains(keyword) && migrationTable.containsKey(keyword.get())) {
if (keywords.contains(keyword) && migrationTable.containsKey(keyword.get())) {
entry.setField(migrationTable.get(keyword.get()), keyword.get());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;

import javafx.collections.FXCollections;

Expand All @@ -22,7 +23,9 @@
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.Directories;
import org.jabref.logic.util.TaskExecutor;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.util.FileUpdateMonitor;

import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -172,4 +175,57 @@ void loadDatabaseReportsNothingForReadableFile(@TempDir Path tempDir) throws Exc
JavaFxExtension.awaitEvents();
verify(dialogService, never()).showErrorDialogAndWait(anyString(), anyString());
}

// [utest->req~import.bibtex.legacy-migrations~1]
// [utest->req~import.bibtex.legacy-migrations.announcement~1]
@Test
void loadDatabaseMigratesLegacyExplicitGroups(@TempDir Path tempDir) throws Exception {
Path library = tempDir.resolve("legacy-groups.bib");
Files.writeString(library, """
@Article{Entry1,
author = {Koppor Test},
title = {Legacy groups migration test},
}

@Comment{jabref-meta: groupsversion:3;}

@Comment{jabref-meta: groupstree:
0 AllEntriesGroup:;
1 ExplicitGroup:TestGroup\\;0\\;Entry1\\;;
}
""");

FilePreferences filePreferences = mock(FilePreferences.class);
when(filePreferences.getBackupDirectory()).thenReturn(tempDir.resolve("backups"));
when(guiPreferences.getFilePreferences()).thenReturn(filePreferences);
when(guiPreferences.getImportFormatPreferences()).thenReturn(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS));

ParserResult parserResult = openDatabaseAction.loadDatabase(library);

BibEntry entry = parserResult.getDatabase().getEntries().getFirst();
assertEquals(Optional.of("TestGroup"), entry.getField(StandardField.GROUPS));
assertTrue(parserResult.getChangedOnMigration());
verify(dialogService).notify(Localization.lang("Migrating library '%0' to the current version", library.toAbsolutePath().toString()));
}

@Test
void loadModernDatabaseDoesNotShowMigrationNotification(@TempDir Path tempDir) throws Exception {
Path library = tempDir.resolve("modern.bib");
Files.writeString(library, """
@Article{Entry1,
title = {Modern library},
keywords = {research},
groups = {Current group},
}
""");
FilePreferences filePreferences = mock(FilePreferences.class);
when(filePreferences.getBackupDirectory()).thenReturn(tempDir.resolve("backups"));
when(guiPreferences.getFilePreferences()).thenReturn(filePreferences);
when(guiPreferences.getImportFormatPreferences()).thenReturn(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS));

ParserResult result = openDatabaseAction.loadDatabase(library);

assertFalse(result.getChangedOnMigration());
verify(dialogService, never()).notify(Localization.lang("Migrating library '%0' to the current version", library.toAbsolutePath().toString()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,23 @@ void performActionClearsLegacyKeys() {
assertEquals(List.of(), group.getLegacyEntryKeys());
}

@Test
void migrationPreservesDuplicateCitationKeysAndIgnoresMissingKeys() {
BibEntry duplicate = new BibEntry().withCitationKey("Entry1").withField(StandardField.TITLE, "Duplicate key");
BibEntry unkeyed = new BibEntry().withField(StandardField.TITLE, "No key");
group.addLegacyEntryKey("Missing");
group.addLegacyEntryKey("Entry1");
ParserResult result = new ParserResult(List.of(entry, duplicate, unkeyed));
result.getMetaData().setGroups(GroupTreeNode.fromGroup(group));

action.performMigration(result);

assertEquals(Optional.of("TestGroup"), entry.getField(StandardField.GROUPS));
assertEquals(Optional.of("TestGroup"), duplicate.getField(StandardField.GROUPS));
assertEquals(Optional.empty(), unkeyed.getField(StandardField.GROUPS));
assertEquals(List.of(), group.getLegacyEntryKeys());
}

@Test
void performActionWritesGroupMembershipInEntryForComplexGroupTree() {
GroupTreeNode root = GroupTreeNode.fromGroup(new AllEntriesGroup(""));
Expand Down
Loading
Loading