Skip to content

Commit

Permalink
registerFileInVault
Browse files Browse the repository at this point in the history
  • Loading branch information
mnaoumov committed Aug 26, 2024
1 parent 0c966db commit 2551c58
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
"tsdoc",
"tsdocs",
"Unescapes",
"unregisters",
"vararg",
"varargs",
"vectorize",
Expand Down
38 changes: 37 additions & 1 deletion src/obsidian/MetadataCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import type {
LinkCache,
MarkdownView,
ReferenceCache,
TAbstractFile,
Vault,
} from "obsidian";
import {
retryWithTimeout,
Expand Down Expand Up @@ -119,7 +121,12 @@ export async function getBacklinksForFileSafe(app: App, pathOrFile: PathOrFile,
let backlinks: CustomArrayDict<LinkCache> | null = null;
await retryWithTimeout(async () => {
const file = getFile(app, pathOrFile);
backlinks = app.metadataCache.getBacklinksForFile(file);
const unregister = registerFileInVault(app.vault, file);
try {
backlinks = app.metadataCache.getBacklinksForFile(file);
} finally {
unregister();
}
for (const notePath of backlinks.keys()) {
const note = app.vault.getFileByPath(notePath);
if (!note) {
Expand Down Expand Up @@ -178,3 +185,32 @@ export async function getFrontMatterSafe<CustomFrontMatter = unknown>(app: App,
const cache = await getCacheSafe(app, pathOrFile);
return (cache?.frontmatter ?? {}) as CombinedFrontMatter<CustomFrontMatter>;
}

/**
* Registers the specified file in the vault.
*
* @param vault - The vault instance.
* @param file - The file to register.
* @returns A function that unregisters the file.
*/
export function registerFileInVault(vault: Vault, file: TAbstractFile): () => void {
if (!file.deleted) {
return () => { };
}

const deletedPaths: string[] = [];

let deletedFile: TAbstractFile = file;

while (deletedFile.deleted) {
deletedPaths.push(deletedFile.path);
vault.fileMap[deletedFile.path] = deletedFile;
deletedFile = deletedFile.parent!;
}

return () => {
for (const path of deletedPaths) {
delete vault.fileMap[path];
}
};
}

0 comments on commit 2551c58

Please sign in to comment.