Basic syncing in the plugin

This commit is contained in:
Andras Schmelczer 2024-12-15 15:47:08 +00:00
parent dfdf1d016b
commit d088d42a65
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
17 changed files with 560 additions and 178 deletions

View file

@ -0,0 +1,18 @@
import { RelativePath } from "src/database/document-metadata";
export interface FileOperations {
read(path: RelativePath): Promise<Uint8Array>;
create(path: RelativePath, newContent: Uint8Array): Promise<void>;
// Writes new content to the file at the given path. If the file's content has changed since the expectedContent was read, the write will merge the changes.
write(
path: RelativePath,
expectedContent: Uint8Array,
newContent: Uint8Array
): Promise<Uint8Array>;
remove(path: RelativePath): Promise<void>;
move(oldPath: RelativePath, newPath: RelativePath): Promise<void>;
}

View file

@ -0,0 +1,71 @@
import { normalizePath, Vault } from "obsidian";
import { FileOperations } from "./file-operations";
import * as lib from "../../../backend/sync_lib/pkg/sync_lib.js";
import { isEqualBytes } from "src/utils/is-equal-bytes";
import { RelativePath } from "src/database/document-metadata";
export class ObsidianFileOperations implements FileOperations {
public constructor(private vault: Vault) {}
async read(path: RelativePath): Promise<Uint8Array> {
return new Uint8Array(
await this.vault.adapter.readBinary(normalizePath(path))
);
}
async write(
path: RelativePath,
expectedContent: Uint8Array,
newContent: Uint8Array
): Promise<Uint8Array> {
if (!(await this.vault.adapter.exists(normalizePath(path)))) {
return new Uint8Array(0);
}
const currentContent = await this.read(path);
if (!isEqualBytes(currentContent, expectedContent)) {
const result = lib.merge(
expectedContent,
currentContent,
newContent
);
await this.vault.adapter.writeBinary(normalizePath(path), result);
return result;
} else {
await this.vault.adapter.writeBinary(
normalizePath(path),
newContent
);
return newContent;
}
}
async create(path: RelativePath, newContent: Uint8Array): Promise<void> {
if (await this.vault.adapter.exists(normalizePath(path))) {
await this.write(path, new Uint8Array(0), newContent);
return;
}
await this.vault.adapter.writeBinary(normalizePath(path), newContent);
}
async remove(path: RelativePath): Promise<void> {
if (await this.vault.adapter.exists(normalizePath(path))) {
return this.vault.adapter.remove(normalizePath(path));
}
}
async move(oldPath: RelativePath, newPath: RelativePath): Promise<void> {
if (oldPath === newPath) {
return;
}
this.vault.adapter.rename(
normalizePath(oldPath),
normalizePath(newPath)
);
}
}