Fix file writing

This commit is contained in:
Andras Schmelczer 2025-01-09 21:50:24 +00:00
commit 9a321121af
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C

View file

@ -15,7 +15,7 @@ export class ObsidianFileOperations implements FileOperations {
public async read(path: RelativePath): Promise<Uint8Array> { public async read(path: RelativePath): Promise<Uint8Array> {
const result = new Uint8Array( const result = new Uint8Array(
await this.vault.readBinary(this.getAbstractFile(path)) await this.vault.adapter.readBinary(normalizePath(path))
); );
return result; return result;
@ -49,7 +49,7 @@ export class ObsidianFileOperations implements FileOperations {
} }
await this.createParentDirectories(normalizePath(path)); await this.createParentDirectories(normalizePath(path));
await this.vault.createBinary(normalizePath(path), newContent); await this.vault.adapter.writeBinary(normalizePath(path), newContent);
} }
public async write( public async write(
@ -63,21 +63,26 @@ export class ObsidianFileOperations implements FileOperations {
} }
if (isBinary(expectedContent)) { if (isBinary(expectedContent)) {
await this.vault.createBinary(normalizePath(path), newContent); await this.vault.adapter.writeBinary(
normalizePath(path),
newContent
);
return newContent; return newContent;
} }
const expetedText = new TextDecoder().decode(expectedContent); const expetedText = new TextDecoder().decode(expectedContent);
const newText = new TextDecoder().decode(newContent); const newText = new TextDecoder().decode(newContent);
const file = this.getAbstractFile(path); const resultText = await this.vault.adapter.process(
const resultText = await this.vault.process(file, (currentText) => { normalizePath(path),
if (currentText !== expetedText) { (currentText) => {
return mergeText(expetedText, currentText, newText); if (currentText !== expetedText) {
} return mergeText(expetedText, currentText, newText);
}
return newText; return newText;
}); }
);
return new TextEncoder().encode(resultText); return new TextEncoder().encode(resultText);
} }
@ -113,17 +118,4 @@ export class ObsidianFileOperations implements FileOperations {
} }
} }
} }
private getAbstractFile(path: RelativePath): TFile {
const file = this.vault.getAbstractFileByPath(path);
if (!file) {
throw new Error(`File not found: ${path}`);
}
if (file instanceof TFile) {
return file;
}
throw new Error(`Not a file: ${path}`);
}
} }