mirror of
https://github.com/vrtmrz/obsidian-livesync.git
synced 2026-09-21 18:17:05 +00:00
Refactor conflict resolution into service features
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
LOG_LEVEL_NOTICE,
|
||||
type FilePath,
|
||||
type FilePathWithPrefix,
|
||||
type ObsidianLiveSyncSettings,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import type { IConflictService, IVaultService } from "@vrtmrz/livesync-commonlib/compat/services/base/IService";
|
||||
import type { LogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils";
|
||||
import type { ReactiveSource } from "octagonal-wheels/dataobject/reactive";
|
||||
import { QueueProcessor } from "octagonal-wheels/concurrency/processor";
|
||||
|
||||
export type ConflictCheckingSettings = Pick<ObsidianLiveSyncSettings, "checkConflictOnlyOnOpen">;
|
||||
|
||||
export interface ConflictCheckingDependencies {
|
||||
readonly conflict: Pick<
|
||||
IConflictService,
|
||||
"getOptionalConflictCheckMethod" | "queueCheckFor" | "resolve" | "resolveByNewest"
|
||||
>;
|
||||
readonly conflictProcessQueueCount: ReactiveSource<number>;
|
||||
readonly currentSettings: () => ConflictCheckingSettings;
|
||||
readonly vault: Pick<IVaultService, "getActiveFilePath">;
|
||||
readonly log: LogFunction;
|
||||
}
|
||||
|
||||
export interface ConflictCheckingHandlers {
|
||||
readonly queueCheckForIfOpen: (file: FilePathWithPrefix) => Promise<void>;
|
||||
readonly queueCheckFor: (file: FilePathWithPrefix) => Promise<void>;
|
||||
readonly ensureAllProcessed: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create conflict-checking handlers and retain both queue processors privately.
|
||||
* The returned operations do not expose queue state to a host or consumer.
|
||||
*/
|
||||
export function createConflictCheckingHandlers(dependencies: ConflictCheckingDependencies): ConflictCheckingHandlers {
|
||||
const conflictResolveQueue = new QueueProcessor<FilePathWithPrefix, void>(
|
||||
async (filenames: FilePathWithPrefix[]) => {
|
||||
const filename = filenames[0];
|
||||
return await dependencies.conflict.resolve(filename);
|
||||
},
|
||||
{
|
||||
suspended: false,
|
||||
batchSize: 1,
|
||||
// No need to limit concurrency to `1` here, subsequent process will handle it,
|
||||
// and some cases do not need to be synchronised (for example, auto-merge).
|
||||
// Global concurrency is limited by the resolver with the UI.
|
||||
concurrentLimit: 10,
|
||||
delay: 0,
|
||||
keepResultUntilDownstreamConnected: false,
|
||||
}
|
||||
).replaceEnqueueProcessor((queue, newEntity) => {
|
||||
const newQueue = [...queue].filter((entry) => entry != newEntity);
|
||||
return [...newQueue, newEntity];
|
||||
});
|
||||
|
||||
const conflictCheckQueue = new QueueProcessor<FilePathWithPrefix, FilePathWithPrefix>(
|
||||
(files: FilePathWithPrefix[]) => {
|
||||
const filename = files[0];
|
||||
return Promise.resolve([filename]);
|
||||
},
|
||||
{
|
||||
suspended: false,
|
||||
batchSize: 1,
|
||||
concurrentLimit: 10,
|
||||
delay: 0,
|
||||
keepResultUntilDownstreamConnected: true,
|
||||
pipeTo: conflictResolveQueue,
|
||||
totalRemainingReactiveSource: dependencies.conflictProcessQueueCount,
|
||||
}
|
||||
);
|
||||
|
||||
const queueCheckForIfOpen = async (file: FilePathWithPrefix): Promise<void> => {
|
||||
const path = file;
|
||||
if (dependencies.currentSettings().checkConflictOnlyOnOpen) {
|
||||
const activeFile: FilePath | undefined = dependencies.vault.getActiveFilePath();
|
||||
if (activeFile && activeFile != path) {
|
||||
dependencies.log(`${file} is conflicted, merging process has been postponed.`, LOG_LEVEL_NOTICE);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await dependencies.conflict.queueCheckFor(path);
|
||||
};
|
||||
|
||||
const queueCheckFor = async (file: FilePathWithPrefix): Promise<void> => {
|
||||
const optionalConflictResult = await dependencies.conflict.getOptionalConflictCheckMethod(file);
|
||||
if (optionalConflictResult == true) {
|
||||
// The conflict has been resolved by another process.
|
||||
return;
|
||||
} else if (optionalConflictResult === "newer") {
|
||||
// The conflict should be resolved by the newer entry.
|
||||
await dependencies.conflict.resolveByNewest(file);
|
||||
} else {
|
||||
conflictCheckQueue.enqueue(file);
|
||||
}
|
||||
};
|
||||
|
||||
const ensureAllProcessed = (): Promise<boolean> => conflictResolveQueue.waitForAllProcessed();
|
||||
|
||||
return {
|
||||
queueCheckForIfOpen,
|
||||
queueCheckFor,
|
||||
ensureAllProcessed,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,587 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createServiceContext } from "@vrtmrz/livesync-commonlib/context";
|
||||
import { InjectableConflictService } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableConflictService";
|
||||
import {
|
||||
AUTO_MERGED,
|
||||
DEFAULT_SETTINGS,
|
||||
LOG_LEVEL_INFO,
|
||||
LOG_LEVEL_NOTICE,
|
||||
MISSING_OR_ERROR,
|
||||
NOT_CONFLICTED,
|
||||
type FilePath,
|
||||
type FilePathWithPrefix,
|
||||
type MetaEntry,
|
||||
type ObsidianLiveSyncSettings,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import { EVENT_CONFLICT_CANCELLED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents";
|
||||
import { NO_INTERACTION } from "@vrtmrz/livesync-commonlib/replication";
|
||||
import type { ConflictResolutionHost } from "./index";
|
||||
import { createConflictResolutionOperations, useConflictResolutionFeature } from "./index";
|
||||
import type { ConflictResolutionOperationsDependencies } from "./operations";
|
||||
|
||||
type ConflictLeaf = {
|
||||
rev: string;
|
||||
data: string;
|
||||
ctime: number;
|
||||
mtime: number;
|
||||
deleted?: boolean;
|
||||
};
|
||||
|
||||
type HarnessOptions = {
|
||||
files?: FilePathWithPrefix[];
|
||||
settings?: Partial<ObsidianLiveSyncSettings>;
|
||||
activeFile?: FilePathWithPrefix;
|
||||
compose?: boolean;
|
||||
};
|
||||
|
||||
function createHarness(options: HarnessOptions = {}) {
|
||||
const context = createServiceContext();
|
||||
const conflict = new InjectableConflictService(context);
|
||||
const settings = { ...DEFAULT_SETTINGS, ...options.settings };
|
||||
const tryAutoMerge = vi.fn();
|
||||
const databaseFileAccess = {
|
||||
fetchEntryMeta: vi.fn(),
|
||||
getConflictedRevs: vi.fn(async () => [] as string[]),
|
||||
storeContent: vi.fn(async () => true),
|
||||
};
|
||||
const fileHandler = {
|
||||
dbToStorage: vi.fn(async () => true),
|
||||
deleteRevisionFromDB: vi.fn(async () => true),
|
||||
};
|
||||
const addLog = vi.fn();
|
||||
const storageAccess = {
|
||||
getFileNames: vi.fn(async () => options.files ?? []),
|
||||
};
|
||||
const activeFile = vi.fn(() => options.activeFile);
|
||||
const services = {
|
||||
API: { addLog },
|
||||
appLifecycle: { isSuspended: vi.fn(() => false) },
|
||||
conflict,
|
||||
context,
|
||||
database: { localDatabase: { tryAutoMerge } },
|
||||
replication: { replicateUnattendedByEvent: vi.fn(async () => ({ status: "completed" as const })) },
|
||||
setting: { currentSettings: vi.fn(() => settings) },
|
||||
vault: { getActiveFilePath: activeFile },
|
||||
};
|
||||
const serviceModules = { databaseFileAccess, fileHandler, storageAccess };
|
||||
|
||||
if (options.compose !== false) {
|
||||
useConflictResolutionFeature({ services, serviceModules } as unknown as ConflictResolutionHost);
|
||||
}
|
||||
|
||||
return {
|
||||
addLog,
|
||||
conflict,
|
||||
context,
|
||||
databaseFileAccess,
|
||||
fileHandler,
|
||||
services,
|
||||
serviceModules,
|
||||
storageAccess,
|
||||
tryAutoMerge,
|
||||
};
|
||||
}
|
||||
|
||||
function leaf(rev: string, data: string, mtime: number): ConflictLeaf {
|
||||
return { rev, data, mtime, ctime: mtime, deleted: false };
|
||||
}
|
||||
|
||||
function metadata(path: FilePathWithPrefix, rev: string, mtime: number): MetaEntry {
|
||||
return {
|
||||
_id: "doc-id",
|
||||
_rev: rev,
|
||||
path,
|
||||
ctime: mtime,
|
||||
mtime,
|
||||
size: 0,
|
||||
children: [],
|
||||
type: "plain",
|
||||
eden: {},
|
||||
} as unknown as MetaEntry;
|
||||
}
|
||||
|
||||
function createOperationsHarness() {
|
||||
const events = { emitEvent: vi.fn() };
|
||||
const tryAutoMerge = vi.fn();
|
||||
const databaseFileAccess = {
|
||||
fetchEntryMeta: vi.fn(),
|
||||
getConflictedRevs: vi.fn(async () => [] as string[]),
|
||||
storeContent: vi.fn(async () => true),
|
||||
};
|
||||
const fileHandler = {
|
||||
dbToStorage: vi.fn(async () => true),
|
||||
deleteRevisionFromDB: vi.fn(async () => true),
|
||||
};
|
||||
const resolveByDeletingRevision = vi.fn(async () => AUTO_MERGED);
|
||||
const queueCheckFor = vi.fn(async () => undefined);
|
||||
const resolveByUserInteraction = vi.fn(async () => false);
|
||||
const replicateUnattendedByEvent = vi.fn(async () => ({ status: "completed" as const }));
|
||||
const dependencies = {
|
||||
events,
|
||||
databaseFileAccess,
|
||||
fileHandler,
|
||||
localDatabase: () => ({ tryAutoMerge }),
|
||||
conflict: { queueCheckFor, resolveByDeletingRevision, resolveByUserInteraction },
|
||||
replication: { replicateUnattendedByEvent },
|
||||
appLifecycle: { isSuspended: vi.fn(() => false) },
|
||||
vault: { getActiveFilePath: vi.fn(() => undefined) },
|
||||
storageAccess: { getFileNames: vi.fn(async () => [] as FilePathWithPrefix[]) },
|
||||
currentSettings: vi.fn(() => ({
|
||||
disableMarkdownAutoMerge: false,
|
||||
resolveConflictsByNewerFile: false,
|
||||
syncAfterMerge: true,
|
||||
showMergeDialogOnlyOnActive: false,
|
||||
})),
|
||||
log: vi.fn(),
|
||||
} as unknown as ConflictResolutionOperationsDependencies;
|
||||
|
||||
return {
|
||||
...dependencies,
|
||||
dependencies,
|
||||
operations: createConflictResolutionOperations(dependencies),
|
||||
events,
|
||||
tryAutoMerge,
|
||||
databaseFileAccess,
|
||||
fileHandler,
|
||||
resolveByDeletingRevision,
|
||||
resolveByUserInteraction,
|
||||
queueCheckFor,
|
||||
replicateUnattendedByEvent,
|
||||
};
|
||||
}
|
||||
|
||||
describe("conflict resolution serviceFeature", () => {
|
||||
it("keeps resolver operations on narrow collaborators and extension seams", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "same.md" as FilePathWithPrefix;
|
||||
const leftLeaf = leaf("1-left", "Same content\n", 1000);
|
||||
const rightLeaf = leaf("1-right", "Same content\n", 2000);
|
||||
harness.tryAutoMerge.mockResolvedValue({
|
||||
leftRev: leftLeaf.rev,
|
||||
rightRev: rightLeaf.rev,
|
||||
leftLeaf,
|
||||
rightLeaf,
|
||||
});
|
||||
|
||||
const result = await harness.operations.checkConflictAndPerformAutoMerge(path);
|
||||
|
||||
expect(result).toBe(AUTO_MERGED);
|
||||
expect(harness.resolveByDeletingRevision).toHaveBeenCalledWith(path, "1-left", "same");
|
||||
expect(harness.fileHandler.deleteRevisionFromDB).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("acquires the active local database for each resolution attempt", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "database-reset.md" as FilePathWithPrefix;
|
||||
const firstTryAutoMerge = vi.fn(async () => ({ ok: NOT_CONFLICTED as typeof NOT_CONFLICTED }));
|
||||
const replacementTryAutoMerge = vi.fn(async () => ({ ok: NOT_CONFLICTED as typeof NOT_CONFLICTED }));
|
||||
let activeDatabase = { tryAutoMerge: firstTryAutoMerge };
|
||||
const dependencies = {
|
||||
...harness.dependencies,
|
||||
localDatabase: () => activeDatabase,
|
||||
};
|
||||
const operations = createConflictResolutionOperations(dependencies);
|
||||
|
||||
await operations.checkConflictAndPerformAutoMerge(path);
|
||||
activeDatabase = { tryAutoMerge: replacementTryAutoMerge };
|
||||
await operations.checkConflictAndPerformAutoMerge(path);
|
||||
|
||||
expect(firstTryAutoMerge).toHaveBeenCalledOnce();
|
||||
expect(replacementTryAutoMerge).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("returns a manual diff for independently created files with different content", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "independently-created.md" as FilePathWithPrefix;
|
||||
const leftLeaf = leaf("1-left", "Left content\n", 1000);
|
||||
const rightLeaf = leaf("1-right", "Right content\n", 2000);
|
||||
harness.tryAutoMerge.mockResolvedValue({
|
||||
leftRev: leftLeaf.rev,
|
||||
rightRev: rightLeaf.rev,
|
||||
leftLeaf,
|
||||
rightLeaf,
|
||||
});
|
||||
|
||||
const result = await harness.operations.checkConflictAndPerformAutoMerge(path);
|
||||
|
||||
expect(result).toMatchObject({ left: leftLeaf, right: rightLeaf });
|
||||
expect(result).toHaveProperty("diff");
|
||||
expect(harness.resolveByDeletingRevision).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stores a sensible merge before resolving its conflict leaf", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "sensible.md" as FilePathWithPrefix;
|
||||
harness.tryAutoMerge.mockResolvedValue({
|
||||
result: "Title\nLeft changed\nRight changed\n",
|
||||
conflictedRev: "2-right",
|
||||
});
|
||||
|
||||
const result = await harness.operations.checkConflictAndPerformAutoMerge(path);
|
||||
|
||||
expect(result).toBe(AUTO_MERGED);
|
||||
expect(harness.databaseFileAccess.storeContent).toHaveBeenCalledWith(
|
||||
path,
|
||||
"Title\nLeft changed\nRight changed\n"
|
||||
);
|
||||
expect(harness.resolveByDeletingRevision).toHaveBeenCalledWith(path, "2-right", "Sensible");
|
||||
});
|
||||
|
||||
it("keeps the conflict leaf when sensible merged content cannot be stored", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "failed-sensible.md" as FilePathWithPrefix;
|
||||
harness.tryAutoMerge.mockResolvedValue({
|
||||
result: "Merged content\n",
|
||||
conflictedRev: "2-right",
|
||||
});
|
||||
harness.databaseFileAccess.storeContent.mockResolvedValue(false);
|
||||
|
||||
const result = await harness.operations.checkConflictAndPerformAutoMerge(path);
|
||||
|
||||
expect(result).toBe(MISSING_OR_ERROR);
|
||||
expect(harness.resolveByDeletingRevision).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stops before emitting or reflecting when conflict revision deletion fails", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "failed-delete.md" as FilePathWithPrefix;
|
||||
harness.fileHandler.deleteRevisionFromDB.mockResolvedValue(false);
|
||||
|
||||
const result = await harness.operations.resolveByDeletingRevision(path, "2-right", "UI Selected");
|
||||
|
||||
expect(result).toBe(MISSING_OR_ERROR);
|
||||
expect(harness.events.emitEvent).not.toHaveBeenCalled();
|
||||
expect(harness.fileHandler.dbToStorage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rechecks a remaining manual pair after committing a sensible merge", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "three-versions.md" as FilePathWithPrefix;
|
||||
const remainingManualPair = {
|
||||
leftRev: "3-merged",
|
||||
rightRev: "2-third",
|
||||
leftLeaf: leaf("3-merged", "Merged\n", 3),
|
||||
rightLeaf: leaf("2-third", "Overlapping\n", 2),
|
||||
};
|
||||
harness.tryAutoMerge
|
||||
.mockResolvedValueOnce({
|
||||
result: "Merged\n",
|
||||
conflictedRev: "2-second",
|
||||
})
|
||||
.mockResolvedValueOnce(remainingManualPair);
|
||||
|
||||
await harness.operations.resolve(path);
|
||||
|
||||
expect(harness.databaseFileAccess.storeContent).toHaveBeenCalledWith(path, "Merged\n");
|
||||
expect(harness.resolveByDeletingRevision).toHaveBeenCalledWith(path, "2-second", "Sensible");
|
||||
expect(harness.queueCheckFor).toHaveBeenCalledWith(path);
|
||||
expect(harness.resolveByUserInteraction).not.toHaveBeenCalled();
|
||||
|
||||
await harness.operations.resolve(path);
|
||||
|
||||
expect(harness.tryAutoMerge).toHaveBeenCalledTimes(2);
|
||||
expect(harness.resolveByUserInteraction).toHaveBeenCalledWith(
|
||||
path,
|
||||
expect.objectContaining({
|
||||
left: remainingManualPair.leftLeaf,
|
||||
right: remainingManualPair.rightLeaf,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("requeues and replicates through collaborators after an automatic merge", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "merged.md" as FilePathWithPrefix;
|
||||
harness.tryAutoMerge.mockResolvedValue({ ok: AUTO_MERGED });
|
||||
|
||||
await harness.operations.resolve(path);
|
||||
|
||||
expect(harness.replicateUnattendedByEvent).toHaveBeenCalledWith({
|
||||
trigger: "merge",
|
||||
interaction: NO_INTERACTION,
|
||||
});
|
||||
expect(harness.queueCheckFor).toHaveBeenCalledWith(path);
|
||||
});
|
||||
|
||||
it("postpones a manual merge until its file is active when configured", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "inactive.md" as FilePathWithPrefix;
|
||||
harness.tryAutoMerge.mockResolvedValue({
|
||||
leftRev: "2-left",
|
||||
rightRev: "2-right",
|
||||
leftLeaf: leaf("2-left", "Left\n", 1),
|
||||
rightLeaf: leaf("2-right", "Right\n", 2),
|
||||
});
|
||||
const dependencies = {
|
||||
...harness.dependencies,
|
||||
currentSettings: () => ({
|
||||
disableMarkdownAutoMerge: false,
|
||||
resolveConflictsByNewerFile: false,
|
||||
syncAfterMerge: false,
|
||||
showMergeDialogOnlyOnActive: true,
|
||||
}),
|
||||
vault: { getActiveFilePath: () => "other.md" as FilePath },
|
||||
};
|
||||
const operations = createConflictResolutionOperations(dependencies);
|
||||
|
||||
await operations.resolve(path);
|
||||
|
||||
expect(harness.resolveByUserInteraction).not.toHaveBeenCalled();
|
||||
expect(dependencies.log).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Merging process has been postponed"),
|
||||
LOG_LEVEL_NOTICE
|
||||
);
|
||||
});
|
||||
|
||||
it("cancels an active same-file dialogue before serialising a repeated resolution", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "repeated.md" as FilePathWithPrefix;
|
||||
harness.tryAutoMerge.mockResolvedValue({
|
||||
leftRev: "2-left",
|
||||
rightRev: "2-right",
|
||||
leftLeaf: leaf("2-left", "Left\n", 1),
|
||||
rightLeaf: leaf("2-right", "Right\n", 2),
|
||||
});
|
||||
let finishDialogue: ((result: boolean) => void) | undefined;
|
||||
harness.resolveByUserInteraction.mockImplementation(
|
||||
async () => await new Promise<boolean>((resolve) => (finishDialogue = resolve))
|
||||
);
|
||||
harness.events.emitEvent.mockImplementation((event, filename) => {
|
||||
if (event === EVENT_CONFLICT_CANCELLED && filename === path && finishDialogue) {
|
||||
const finish = finishDialogue;
|
||||
finishDialogue = undefined;
|
||||
finish(false);
|
||||
}
|
||||
});
|
||||
|
||||
const first = harness.operations.resolve(path);
|
||||
await vi.waitFor(() => expect(harness.resolveByUserInteraction).toHaveBeenCalledOnce());
|
||||
const replacement = harness.operations.resolve(path);
|
||||
|
||||
await vi.waitFor(() => expect(harness.resolveByUserInteraction).toHaveBeenCalledTimes(2));
|
||||
expect(harness.events.emitEvent).toHaveBeenCalledWith(EVENT_CONFLICT_CANCELLED, path);
|
||||
|
||||
finishDialogue?.(false);
|
||||
await Promise.all([first, replacement]);
|
||||
});
|
||||
|
||||
it("passes only the newest waiting same-file resolution to the interactive resolver", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "repeated-three-times.md" as FilePathWithPrefix;
|
||||
harness.tryAutoMerge.mockResolvedValue({
|
||||
leftRev: "2-left",
|
||||
rightRev: "2-right",
|
||||
leftLeaf: leaf("2-left", "Left\n", 1),
|
||||
rightLeaf: leaf("2-right", "Right\n", 2),
|
||||
});
|
||||
let finishFirstDialogue: ((result: boolean) => void) | undefined;
|
||||
harness.resolveByUserInteraction
|
||||
.mockImplementationOnce(
|
||||
async () => await new Promise<boolean>((resolve) => (finishFirstDialogue = resolve))
|
||||
)
|
||||
.mockResolvedValue(false);
|
||||
harness.events.emitEvent.mockImplementation((event, filename) => {
|
||||
if (event === EVENT_CONFLICT_CANCELLED && filename === path && finishFirstDialogue) {
|
||||
const finish = finishFirstDialogue;
|
||||
finishFirstDialogue = undefined;
|
||||
finish(false);
|
||||
}
|
||||
});
|
||||
|
||||
const first = harness.operations.resolve(path);
|
||||
await vi.waitFor(() => expect(harness.resolveByUserInteraction).toHaveBeenCalledOnce());
|
||||
const superseded = harness.operations.resolve(path);
|
||||
const replacement = harness.operations.resolve(path);
|
||||
|
||||
await Promise.all([first, superseded, replacement]);
|
||||
|
||||
expect(harness.resolveByUserInteraction).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not open a superseded dialogue after conflict inspection completes", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "superseded-during-inspection.md" as FilePathWithPrefix;
|
||||
const manualConflict = {
|
||||
leftRev: "2-left",
|
||||
rightRev: "2-right",
|
||||
leftLeaf: leaf("2-left", "Left\n", 1),
|
||||
rightLeaf: leaf("2-right", "Right\n", 2),
|
||||
};
|
||||
let finishFirstInspection!: (result: typeof manualConflict) => void;
|
||||
harness.tryAutoMerge
|
||||
.mockImplementationOnce(
|
||||
async () => await new Promise<typeof manualConflict>((resolve) => (finishFirstInspection = resolve))
|
||||
)
|
||||
.mockResolvedValue(manualConflict);
|
||||
harness.resolveByUserInteraction.mockResolvedValue(false);
|
||||
|
||||
const superseded = harness.operations.resolve(path);
|
||||
await vi.waitFor(() => expect(harness.tryAutoMerge).toHaveBeenCalledOnce());
|
||||
const replacement = harness.operations.resolve(path);
|
||||
finishFirstInspection(manualConflict);
|
||||
|
||||
await Promise.all([superseded, replacement]);
|
||||
|
||||
expect(harness.resolveByUserInteraction).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("registers all conflict service operations during composition", () => {
|
||||
const harness = createHarness({ compose: false });
|
||||
const registrations = [
|
||||
vi.spyOn(harness.conflict.queueCheckForIfOpen, "setHandler"),
|
||||
vi.spyOn(harness.conflict.queueCheckFor, "setHandler"),
|
||||
vi.spyOn(harness.conflict.ensureAllProcessed, "setHandler"),
|
||||
vi.spyOn(harness.conflict.resolveByDeletingRevision, "setHandler"),
|
||||
vi.spyOn(harness.conflict.resolve, "setHandler"),
|
||||
vi.spyOn(harness.conflict.resolveByNewest, "setHandler"),
|
||||
vi.spyOn(harness.conflict.resolveAllConflictedFilesByNewerOnes, "setHandler"),
|
||||
];
|
||||
|
||||
useConflictResolutionFeature({
|
||||
services: harness.services,
|
||||
serviceModules: harness.serviceModules,
|
||||
} as unknown as ConflictResolutionHost);
|
||||
|
||||
for (const registration of registrations) {
|
||||
expect(registration).toHaveBeenCalledOnce();
|
||||
expect(registration).toHaveBeenCalledWith(expect.any(Function));
|
||||
}
|
||||
});
|
||||
|
||||
it("applies the active-file gate and deduplicates pending checks for one path", async () => {
|
||||
const path = "postponed.md" as FilePathWithPrefix;
|
||||
const harness = createHarness({
|
||||
activeFile: "other.md" as FilePathWithPrefix,
|
||||
settings: { checkConflictOnlyOnOpen: true },
|
||||
});
|
||||
harness.tryAutoMerge.mockResolvedValue({ ok: NOT_CONFLICTED });
|
||||
|
||||
await harness.conflict.queueCheckForIfOpen(path);
|
||||
expect(harness.tryAutoMerge).not.toHaveBeenCalled();
|
||||
|
||||
harness.services.vault.getActiveFilePath = vi.fn(() => path);
|
||||
await Promise.all([harness.conflict.queueCheckFor(path), harness.conflict.queueCheckFor(path)]);
|
||||
await harness.conflict.ensureAllProcessed();
|
||||
|
||||
expect(harness.tryAutoMerge).toHaveBeenCalledOnce();
|
||||
expect(harness.tryAutoMerge).toHaveBeenCalledWith(path, true);
|
||||
expect(harness.addLog).toHaveBeenCalledWith(
|
||||
`${path} is conflicted, merging process has been postponed.`,
|
||||
LOG_LEVEL_NOTICE,
|
||||
""
|
||||
);
|
||||
});
|
||||
|
||||
it("honours optional conflict handlers before entering the check queue", async () => {
|
||||
const path = "optional.md" as FilePathWithPrefix;
|
||||
const harness = createHarness();
|
||||
harness.tryAutoMerge.mockResolvedValue({ ok: NOT_CONFLICTED });
|
||||
|
||||
const unregisterResolved = harness.conflict.getOptionalConflictCheckMethod.addHandler(async () => true);
|
||||
await harness.conflict.queueCheckFor(path);
|
||||
await harness.conflict.ensureAllProcessed();
|
||||
expect(harness.tryAutoMerge).not.toHaveBeenCalled();
|
||||
unregisterResolved();
|
||||
|
||||
const unregisterNewer = harness.conflict.getOptionalConflictCheckMethod.addHandler(async () => "newer");
|
||||
harness.databaseFileAccess.fetchEntryMeta.mockResolvedValue(false);
|
||||
await harness.conflict.queueCheckFor(path);
|
||||
expect(harness.databaseFileAccess.fetchEntryMeta).toHaveBeenCalledWith(path, undefined, true);
|
||||
unregisterNewer();
|
||||
});
|
||||
|
||||
it("keeps unreadable conflict revisions available for explicit repair", async () => {
|
||||
const path = "missing-conflict-body.md" as FilePathWithPrefix;
|
||||
const harness = createHarness();
|
||||
harness.tryAutoMerge.mockResolvedValue({
|
||||
leftRev: "3-current",
|
||||
rightRev: "2-unreadable",
|
||||
leftLeaf: leaf("3-current", "Readable current body\n", 3),
|
||||
rightLeaf: false,
|
||||
});
|
||||
|
||||
await harness.conflict.resolve(path);
|
||||
|
||||
expect(harness.fileHandler.deleteRevisionFromDB).not.toHaveBeenCalled();
|
||||
expect(harness.fileHandler.dbToStorage).not.toHaveBeenCalled();
|
||||
expect(harness.addLog).toHaveBeenCalledWith(
|
||||
`could not read conflicted revision 2-unreadable:${path}`,
|
||||
LOG_LEVEL_NOTICE,
|
||||
""
|
||||
);
|
||||
expect(MISSING_OR_ERROR).toBeDefined();
|
||||
});
|
||||
|
||||
it("resolves an identical pair, emits cancellation, and rechecks after merging", async () => {
|
||||
const path = "independently-created.md" as FilePathWithPrefix;
|
||||
const harness = createHarness({ settings: { syncAfterMerge: false } });
|
||||
const cancelled: FilePathWithPrefix[] = [];
|
||||
harness.context.events.onEvent(EVENT_CONFLICT_CANCELLED, (filename) => cancelled.push(filename));
|
||||
const leftLeaf = leaf("1-left", "Same content\n", 1000);
|
||||
const rightLeaf = leaf("1-right", "Same content\n", 2000);
|
||||
harness.tryAutoMerge
|
||||
.mockResolvedValueOnce({
|
||||
leftRev: leftLeaf.rev,
|
||||
rightRev: rightLeaf.rev,
|
||||
leftLeaf,
|
||||
rightLeaf,
|
||||
})
|
||||
.mockResolvedValueOnce({ ok: NOT_CONFLICTED });
|
||||
|
||||
await harness.conflict.resolve(path);
|
||||
await harness.conflict.ensureAllProcessed();
|
||||
|
||||
expect(harness.fileHandler.deleteRevisionFromDB).toHaveBeenCalledWith(path, "1-left");
|
||||
expect(harness.fileHandler.dbToStorage).toHaveBeenCalledWith(path, path, true);
|
||||
expect(cancelled).toEqual([path, path]);
|
||||
expect(harness.tryAutoMerge).toHaveBeenCalledTimes(2);
|
||||
expect(AUTO_MERGED).toBeDefined();
|
||||
});
|
||||
|
||||
it("uses deterministic revision ordering and suppresses notices during bulk resolution", async () => {
|
||||
const files = Array.from({ length: 11 }, (_, index) => `note-${index}.md` as FilePathWithPrefix);
|
||||
const harness = createHarness({ files });
|
||||
harness.databaseFileAccess.fetchEntryMeta.mockImplementation(async (path: FilePathWithPrefix, rev?: string) =>
|
||||
metadata(path, rev ?? "2-current", rev ? 1 : 2)
|
||||
);
|
||||
let conflictInspection = 0;
|
||||
harness.databaseFileAccess.getConflictedRevs.mockImplementation(async () =>
|
||||
conflictInspection++ % 2 === 0 ? ["1-old"] : []
|
||||
);
|
||||
|
||||
await harness.conflict.resolveAllConflictedFilesByNewerOnes();
|
||||
|
||||
expect(harness.fileHandler.deleteRevisionFromDB).toHaveBeenCalledTimes(11);
|
||||
expect(harness.addLog).toHaveBeenCalledWith(
|
||||
"Check and Processing 10 / 11",
|
||||
LOG_LEVEL_NOTICE,
|
||||
"resolveAllConflictedFilesByNewerOnes"
|
||||
);
|
||||
expect(harness.addLog).toHaveBeenCalledWith(
|
||||
expect.stringContaining("has been merged automatically"),
|
||||
LOG_LEVEL_INFO,
|
||||
""
|
||||
);
|
||||
});
|
||||
|
||||
it("uses revision identifiers to break newest-resolution timestamp ties", async () => {
|
||||
const harness = createOperationsHarness();
|
||||
const path = "same-time.md" as FilePathWithPrefix;
|
||||
harness.databaseFileAccess.fetchEntryMeta.mockImplementation(
|
||||
async (filename: FilePathWithPrefix, revision?: string) => metadata(filename, revision ?? "2-3", 1000)
|
||||
);
|
||||
harness.databaseFileAccess.getConflictedRevs
|
||||
.mockResolvedValueOnce(["2-10", "2-2"])
|
||||
.mockResolvedValueOnce(["2-10"])
|
||||
.mockResolvedValueOnce([]);
|
||||
|
||||
await harness.operations.resolveByNewest(path);
|
||||
|
||||
expect(harness.fileHandler.deleteRevisionFromDB).toHaveBeenNthCalledWith(1, path, "2-3");
|
||||
expect(harness.fileHandler.deleteRevisionFromDB).toHaveBeenNthCalledWith(2, path, "2-10");
|
||||
expect(harness.dependencies.log).toHaveBeenLastCalledWith(
|
||||
`${path} has been merged automatically`,
|
||||
LOG_LEVEL_NOTICE
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { NecessaryServices } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule";
|
||||
import { createInstanceLogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils";
|
||||
import type { InjectableConflictService } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableConflictService";
|
||||
import type { ServiceContext } from "@vrtmrz/livesync-commonlib/context";
|
||||
import { createConflictCheckingHandlers } from "./checker";
|
||||
import { createConflictResolutionOperations } from "./operations";
|
||||
|
||||
type ConflictResolutionServices = NecessaryServices<
|
||||
"API" | "appLifecycle" | "conflict" | "database" | "replication" | "setting" | "vault",
|
||||
"databaseFileAccess" | "fileHandler" | "storageAccess"
|
||||
>;
|
||||
|
||||
export type ConflictResolutionHost = ConflictResolutionServices & {
|
||||
readonly services: ConflictResolutionServices["services"] & {
|
||||
readonly conflict: InjectableConflictService<ServiceContext>;
|
||||
};
|
||||
};
|
||||
|
||||
/** Compose the host-neutral conflict checker and resolver handlers. */
|
||||
export function useConflictResolutionFeature(host: ConflictResolutionHost): void {
|
||||
const { services, serviceModules } = host;
|
||||
const log = createInstanceLogFunction("SF:ConflictResolution", services.API);
|
||||
const operations = createConflictResolutionOperations({
|
||||
events: services.context.events,
|
||||
databaseFileAccess: serviceModules.databaseFileAccess,
|
||||
fileHandler: serviceModules.fileHandler,
|
||||
localDatabase: () => services.database.localDatabase,
|
||||
conflict: services.conflict,
|
||||
replication: services.replication,
|
||||
appLifecycle: services.appLifecycle,
|
||||
vault: services.vault,
|
||||
storageAccess: serviceModules.storageAccess,
|
||||
currentSettings: () => services.setting.currentSettings(),
|
||||
log,
|
||||
});
|
||||
const checking = createConflictCheckingHandlers({
|
||||
conflict: services.conflict,
|
||||
conflictProcessQueueCount: services.conflict.conflictProcessQueueCount,
|
||||
currentSettings: () => services.setting.currentSettings(),
|
||||
vault: services.vault,
|
||||
log,
|
||||
});
|
||||
|
||||
services.conflict.queueCheckForIfOpen.setHandler(checking.queueCheckForIfOpen);
|
||||
services.conflict.queueCheckFor.setHandler(checking.queueCheckFor);
|
||||
services.conflict.ensureAllProcessed.setHandler(checking.ensureAllProcessed);
|
||||
services.conflict.resolveByDeletingRevision.setHandler(operations.resolveByDeletingRevision);
|
||||
services.conflict.resolve.setHandler(operations.resolve);
|
||||
services.conflict.resolveByNewest.setHandler(operations.resolveByNewest);
|
||||
services.conflict.resolveAllConflictedFilesByNewerOnes.setHandler(operations.resolveAllConflictedFilesByNewerOnes);
|
||||
}
|
||||
|
||||
export { createConflictCheckingHandlers } from "./checker";
|
||||
export type { ConflictCheckingDependencies, ConflictCheckingHandlers } from "./checker";
|
||||
export type {
|
||||
ConflictResolutionOperations,
|
||||
ConflictResolutionOperationsDependencies,
|
||||
ConflictResolutionSettings,
|
||||
} from "./operations";
|
||||
export { createConflictResolutionOperations } from "./operations";
|
||||
@@ -0,0 +1,308 @@
|
||||
import {
|
||||
AUTO_MERGED,
|
||||
CANCELLED,
|
||||
LOG_LEVEL_INFO,
|
||||
LOG_LEVEL_NOTICE,
|
||||
LOG_LEVEL_VERBOSE,
|
||||
MISSING_OR_ERROR,
|
||||
NOT_CONFLICTED,
|
||||
type diff_check_result,
|
||||
type FilePathWithPrefix,
|
||||
type ObsidianLiveSyncSettings,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import { isCustomisationSyncMetadata, isPluginMetadata } from "@vrtmrz/livesync-commonlib/compat/common/typeUtils";
|
||||
import { TARGET_IS_NEW } from "@vrtmrz/livesync-commonlib/compat/common/models/shared.const.symbols";
|
||||
import { compareMTime, displayRev } from "@vrtmrz/livesync-commonlib/compat/common/utils";
|
||||
import type { DatabaseFileAccess } from "@vrtmrz/livesync-commonlib/compat/interfaces/DatabaseFileAccess";
|
||||
import type { IFileHandler } from "@vrtmrz/livesync-commonlib/compat/interfaces/FileHandler";
|
||||
import type {
|
||||
IAppLifecycleService,
|
||||
IConflictService,
|
||||
IReplicationService,
|
||||
IVaultService,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/services/base/IService";
|
||||
import type { LiveSyncLocalDB } from "@vrtmrz/livesync-commonlib/compat/pouchdb/LiveSyncLocalDB";
|
||||
import type { LogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils";
|
||||
import type { LiveSyncEventHub } from "@vrtmrz/livesync-commonlib/context";
|
||||
import type { StorageAccess } from "@vrtmrz/livesync-commonlib/compat/interfaces/StorageAccess";
|
||||
import { EVENT_CONFLICT_CANCELLED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents";
|
||||
import { NO_INTERACTION } from "@vrtmrz/livesync-commonlib/replication";
|
||||
import { isLockAcquired, serialized } from "octagonal-wheels/concurrency/lock";
|
||||
import diff_match_patch from "diff-match-patch";
|
||||
import { stripAllPrefixes, isPlainText } from "@vrtmrz/livesync-commonlib/compat/string_and_binary/path";
|
||||
|
||||
export type ConflictResolutionSettings = Pick<
|
||||
ObsidianLiveSyncSettings,
|
||||
"disableMarkdownAutoMerge" | "resolveConflictsByNewerFile" | "syncAfterMerge" | "showMergeDialogOnlyOnActive"
|
||||
>;
|
||||
|
||||
export interface ConflictResolutionOperationsDependencies {
|
||||
readonly events: Pick<LiveSyncEventHub, "emitEvent">;
|
||||
readonly databaseFileAccess: Pick<DatabaseFileAccess, "fetchEntryMeta" | "getConflictedRevs" | "storeContent">;
|
||||
readonly fileHandler: Pick<IFileHandler, "deleteRevisionFromDB" | "dbToStorage">;
|
||||
readonly localDatabase: () => Pick<LiveSyncLocalDB, "tryAutoMerge">;
|
||||
readonly conflict: Pick<
|
||||
IConflictService,
|
||||
"queueCheckFor" | "resolveByDeletingRevision" | "resolveByUserInteraction"
|
||||
>;
|
||||
readonly replication: Pick<IReplicationService, "replicateUnattendedByEvent">;
|
||||
readonly appLifecycle: Pick<IAppLifecycleService, "isSuspended">;
|
||||
readonly vault: Pick<IVaultService, "getActiveFilePath">;
|
||||
readonly storageAccess: Pick<StorageAccess, "getFileNames">;
|
||||
readonly currentSettings: () => ConflictResolutionSettings;
|
||||
readonly log: LogFunction;
|
||||
}
|
||||
|
||||
export interface ConflictResolutionOperations {
|
||||
readonly resolveByDeletingRevision: (
|
||||
path: FilePathWithPrefix,
|
||||
deleteRevision: string,
|
||||
subTitle?: string,
|
||||
showNotice?: boolean
|
||||
) => Promise<typeof MISSING_OR_ERROR | typeof AUTO_MERGED>;
|
||||
readonly checkConflictAndPerformAutoMerge: (path: FilePathWithPrefix) => Promise<diff_check_result>;
|
||||
readonly resolve: (filename: FilePathWithPrefix) => Promise<void>;
|
||||
readonly resolveByNewest: (filename: FilePathWithPrefix, showNotice?: boolean) => Promise<boolean>;
|
||||
readonly resolveAllConflictedFilesByNewerOnes: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function createConflictResolutionOperations(
|
||||
dependencies: ConflictResolutionOperationsDependencies
|
||||
): ConflictResolutionOperations {
|
||||
const latestResolveRequestByFilename = new Map<FilePathWithPrefix, number>();
|
||||
let nextResolveRequestId = 0;
|
||||
|
||||
const resolveByDeletingRevision = async (
|
||||
path: FilePathWithPrefix,
|
||||
deleteRevision: string,
|
||||
subTitle = "",
|
||||
showNotice = true
|
||||
): Promise<typeof MISSING_OR_ERROR | typeof AUTO_MERGED> => {
|
||||
const title = `Resolving ${subTitle ? `[${subTitle}]` : ""}:`;
|
||||
if (!(await dependencies.fileHandler.deleteRevisionFromDB(path, deleteRevision))) {
|
||||
dependencies.log(
|
||||
`${title} Could not delete conflicted revision ${displayRev(deleteRevision)} of ${path}`,
|
||||
LOG_LEVEL_NOTICE
|
||||
);
|
||||
return MISSING_OR_ERROR;
|
||||
}
|
||||
dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
|
||||
dependencies.log(
|
||||
`${title} Conflicted revision has been deleted ${displayRev(deleteRevision)} ${path}`,
|
||||
LOG_LEVEL_INFO
|
||||
);
|
||||
if ((await dependencies.databaseFileAccess.getConflictedRevs(path)).length != 0) {
|
||||
dependencies.log(`${title} some conflicts are left in ${path}`, LOG_LEVEL_INFO);
|
||||
return AUTO_MERGED;
|
||||
}
|
||||
if (isPluginMetadata(path) || isCustomisationSyncMetadata(path)) {
|
||||
dependencies.log(`${title} ${path} is a plugin metadata file, no need to write to storage`, LOG_LEVEL_INFO);
|
||||
return AUTO_MERGED;
|
||||
}
|
||||
// If no conflicts were found, write the resolved content to the storage.
|
||||
if (!(await dependencies.fileHandler.dbToStorage(path, stripAllPrefixes(path), true))) {
|
||||
dependencies.log(`Could not write the resolved content to the storage: ${path}`, LOG_LEVEL_NOTICE);
|
||||
return MISSING_OR_ERROR;
|
||||
}
|
||||
const level = subTitle.indexOf("same") !== -1 || !showNotice ? LOG_LEVEL_INFO : LOG_LEVEL_NOTICE;
|
||||
dependencies.log(`${path} has been merged automatically`, level);
|
||||
return AUTO_MERGED;
|
||||
};
|
||||
|
||||
const checkConflictAndPerformAutoMerge = async (path: FilePathWithPrefix): Promise<diff_check_result> => {
|
||||
const ret = await dependencies
|
||||
.localDatabase()
|
||||
.tryAutoMerge(path, !dependencies.currentSettings().disableMarkdownAutoMerge);
|
||||
if ("ok" in ret) {
|
||||
return ret.ok;
|
||||
}
|
||||
|
||||
if ("result" in ret) {
|
||||
const p = ret.result;
|
||||
// 1. Store the merged content to the storage.
|
||||
if (!(await dependencies.databaseFileAccess.storeContent(path, p))) {
|
||||
dependencies.log(`Merged content cannot be stored:${path}`, LOG_LEVEL_NOTICE);
|
||||
return MISSING_OR_ERROR;
|
||||
}
|
||||
// 2. Delete the conflicted revision and reflect the result if all conflicts are gone.
|
||||
return await dependencies.conflict.resolveByDeletingRevision(path, ret.conflictedRev, "Sensible");
|
||||
}
|
||||
|
||||
const { rightRev, leftLeaf, rightLeaf } = ret;
|
||||
|
||||
// Should be one or more conflicts.
|
||||
if (leftLeaf == false) {
|
||||
dependencies.log(`could not get current revisions:${path}`, LOG_LEVEL_NOTICE);
|
||||
return MISSING_OR_ERROR;
|
||||
}
|
||||
if (rightLeaf == false) {
|
||||
// A locally unreadable conflict leaf may still be recoverable from another
|
||||
// replica or backup. Keep it visible for explicit repair instead of treating
|
||||
// missing chunks as evidence that the branch is obsolete.
|
||||
dependencies.log(`could not read conflicted revision ${rightRev}:${path}`, LOG_LEVEL_NOTICE);
|
||||
return MISSING_OR_ERROR;
|
||||
}
|
||||
|
||||
const isSame = leftLeaf.data == rightLeaf.data && leftLeaf.deleted == rightLeaf.deleted;
|
||||
const isBinary = !isPlainText(path);
|
||||
const alwaysNewer = dependencies.currentSettings().resolveConflictsByNewerFile;
|
||||
if (isSame || isBinary || alwaysNewer) {
|
||||
const result = compareMTime(leftLeaf.mtime, rightLeaf.mtime);
|
||||
let loser = leftLeaf;
|
||||
// If lMtime > rMtime.
|
||||
if (result != TARGET_IS_NEW) {
|
||||
loser = rightLeaf;
|
||||
}
|
||||
const subTitle = [
|
||||
`${isSame ? "same" : ""}`,
|
||||
`${isBinary ? "binary" : ""}`,
|
||||
`${alwaysNewer ? "alwaysNewer" : ""}`,
|
||||
]
|
||||
.filter((e) => e.trim())
|
||||
.join(",");
|
||||
return await dependencies.conflict.resolveByDeletingRevision(path, loser.rev, subTitle);
|
||||
}
|
||||
// Make diff.
|
||||
const dmp = new diff_match_patch();
|
||||
const diff = dmp.diff_main(leftLeaf.data, rightLeaf.data);
|
||||
dmp.diff_cleanupSemantic(diff);
|
||||
dependencies.log(`conflict(s) found:${path}`);
|
||||
return {
|
||||
left: leftLeaf,
|
||||
right: rightLeaf,
|
||||
diff: diff,
|
||||
};
|
||||
};
|
||||
|
||||
const resolve = async (filename: FilePathWithPrefix): Promise<void> => {
|
||||
const requestId = ++nextResolveRequestId;
|
||||
latestResolveRequestByFilename.set(filename, requestId);
|
||||
const serialisationKey = `conflict-resolve:${filename}`;
|
||||
if (isLockAcquired(serialisationKey)) {
|
||||
// A later check for the same file makes any open comparison stale.
|
||||
// Close it before waiting for the current resolver to release the
|
||||
// per-file lock. Dialogues for other paths remain untouched.
|
||||
dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
|
||||
}
|
||||
return await serialized(serialisationKey, async () => {
|
||||
if (latestResolveRequestByFilename.get(filename) !== requestId) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const conflictCheckResult = await checkConflictAndPerformAutoMerge(filename);
|
||||
if (latestResolveRequestByFilename.get(filename) !== requestId) {
|
||||
return;
|
||||
}
|
||||
if (conflictCheckResult === NOT_CONFLICTED) {
|
||||
dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
|
||||
dependencies.log(`[conflict] Not conflicted or cancelled: ${filename}`, LOG_LEVEL_VERBOSE);
|
||||
return;
|
||||
}
|
||||
if (conflictCheckResult === MISSING_OR_ERROR || conflictCheckResult === CANCELLED) {
|
||||
// Nothing to do.
|
||||
dependencies.log(`[conflict] Not conflicted or cancelled: ${filename}`, LOG_LEVEL_VERBOSE);
|
||||
return;
|
||||
}
|
||||
if (conflictCheckResult === AUTO_MERGED) {
|
||||
// Auto resolved, but need to check again.
|
||||
if (dependencies.currentSettings().syncAfterMerge && !dependencies.appLifecycle.isSuspended()) {
|
||||
// Wait for the running replication, if not running replication, run it once.
|
||||
await dependencies.replication.replicateUnattendedByEvent({
|
||||
trigger: "merge",
|
||||
interaction: NO_INTERACTION,
|
||||
});
|
||||
}
|
||||
dependencies.log("[conflict] Automatically merged, but we have to check it again");
|
||||
await dependencies.conflict.queueCheckFor(filename);
|
||||
return;
|
||||
}
|
||||
if (dependencies.currentSettings().showMergeDialogOnlyOnActive) {
|
||||
const activeFile = dependencies.vault.getActiveFilePath();
|
||||
if (activeFile && activeFile != filename) {
|
||||
dependencies.log(
|
||||
`[conflict] ${filename} is conflicted. Merging process has been postponed to the file have got opened.`,
|
||||
LOG_LEVEL_NOTICE
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
dependencies.log("[conflict] Manual merge required!");
|
||||
dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
|
||||
await dependencies.conflict.resolveByUserInteraction(filename, conflictCheckResult);
|
||||
} finally {
|
||||
if (latestResolveRequestByFilename.get(filename) === requestId) {
|
||||
latestResolveRequestByFilename.delete(filename);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const resolveByNewest = async (filename: FilePathWithPrefix, showNotice = true): Promise<boolean> => {
|
||||
const currentRev = await dependencies.databaseFileAccess.fetchEntryMeta(filename, undefined, true);
|
||||
if (currentRev == false) {
|
||||
dependencies.log(`Could not get current revision of ${filename}`);
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
const revs = await dependencies.databaseFileAccess.getConflictedRevs(filename);
|
||||
if (revs.length == 0) {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
const mTimeAndRev = (
|
||||
[
|
||||
[currentRev.mtime, currentRev._rev],
|
||||
...(await Promise.all(
|
||||
revs.map(async (rev) => {
|
||||
const leaf = await dependencies.databaseFileAccess.fetchEntryMeta(filename, rev);
|
||||
if (leaf == false) {
|
||||
return [0, rev];
|
||||
}
|
||||
return [leaf.mtime, rev];
|
||||
})
|
||||
)),
|
||||
] as [number, string][]
|
||||
).sort((a, b) => {
|
||||
const diff = b[0] - a[0];
|
||||
if (diff == 0) {
|
||||
return a[1].localeCompare(b[1], "en", { numeric: true });
|
||||
}
|
||||
return diff;
|
||||
});
|
||||
dependencies.log(
|
||||
`Resolving conflict by newest: ${filename} (Newest: ${new Date(mTimeAndRev[0][0]).toLocaleString()}) (${mTimeAndRev.length} revisions exists)`
|
||||
);
|
||||
for (let i = 1; i < mTimeAndRev.length; i++) {
|
||||
dependencies.log(
|
||||
`conflict: Deleting the older revision ${mTimeAndRev[i][1]} (${new Date(mTimeAndRev[i][0]).toLocaleString()}) of ${filename}`
|
||||
);
|
||||
await resolveByDeletingRevision(filename, mTimeAndRev[i][1], "NEWEST", showNotice);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const resolveAllConflictedFilesByNewerOnes = async (): Promise<void> => {
|
||||
dependencies.log(`Resolving conflicts by newer ones`, LOG_LEVEL_NOTICE);
|
||||
|
||||
const files = await dependencies.storageAccess.getFileNames();
|
||||
|
||||
let i = 0;
|
||||
for (const file of files) {
|
||||
i++;
|
||||
if (i % 10 === 0)
|
||||
dependencies.log(
|
||||
`Check and Processing ${i} / ${files.length}`,
|
||||
LOG_LEVEL_NOTICE,
|
||||
"resolveAllConflictedFilesByNewerOnes"
|
||||
);
|
||||
await resolveByNewest(file, false);
|
||||
}
|
||||
dependencies.log(`Done!`, LOG_LEVEL_NOTICE, "resolveAllConflictedFilesByNewerOnes");
|
||||
};
|
||||
|
||||
return {
|
||||
resolveByDeletingRevision,
|
||||
checkConflictAndPerformAutoMerge,
|
||||
resolve,
|
||||
resolveByNewest,
|
||||
resolveAllConflictedFilesByNewerOnes,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user