1
Fork 0
mirror of https://github.com/Steffo99/obsidian-file-index.git synced 2024-10-16 13:17:26 +00:00
obsidian-file-index/main.ts

64 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-10-28 17:37:02 +00:00
import {Plugin, TFile, TFolder} from "obsidian"
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
export interface SteffoFileIndex {
basenames: {[basename: string]: string},
paths: string[],
2023-10-28 16:05:49 +00:00
}
2023-10-28 17:37:02 +00:00
export default class SteffoFileIndexPlugin extends Plugin {
static FILE_INDEX_PATH = "steffo-file-index.json"
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
async recreateFileIndex() {
const files = this.app.vault.getFiles()
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
const basenames: {[basename: string]: string} = {}
const paths = []
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
for(const file of files) {
paths.push(file.path)
basenames[file.basename] = file.path
}
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
paths.sort()
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
const index: SteffoFileIndex = {basenames, paths}
const indexContents = JSON.stringify(index, null, "\t")
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
const indexFile = this.app.vault.getAbstractFileByPath(SteffoFileIndexPlugin.FILE_INDEX_PATH)
if(indexFile instanceof TFolder) {
console.error("Cannot create file index, as there's a folder at:", SteffoFileIndexPlugin.FILE_INDEX_PATH)
return
}
else if(indexFile instanceof TFile) {
console.info("File index already exists, overwriting contents of:", SteffoFileIndexPlugin.FILE_INDEX_PATH)
await this.app.vault.modify(indexFile, indexContents)
}
else {
console.info("File index does not exist, creating it right now at:", SteffoFileIndexPlugin.FILE_INDEX_PATH)
await this.app.vault.create(SteffoFileIndexPlugin.FILE_INDEX_PATH, indexContents)
}
2023-10-28 16:05:49 +00:00
}
2023-10-28 17:37:02 +00:00
recreateFileIndexBinding = this.recreateFileIndex.bind(this)
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
async onload() {
this.addCommand({
id: 'steffo-file-index-recreate',
name: 'Force file index recreation',
callback: this.recreateFileIndex.bind(this)
})
2023-10-28 16:05:49 +00:00
2023-10-28 17:37:02 +00:00
this.app.vault.on("create", this.recreateFileIndexBinding)
this.app.vault.on("delete", this.recreateFileIndexBinding)
this.app.vault.on("rename", this.recreateFileIndexBinding)
2023-10-28 16:05:49 +00:00
}
2023-10-28 17:37:02 +00:00
onunload() {
this.app.vault.off("create", this.recreateFileIndexBinding)
this.app.vault.off("delete", this.recreateFileIndexBinding)
this.app.vault.off("rename", this.recreateFileIndexBinding)
2023-10-28 16:05:49 +00:00
}
}