generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmeta-updater.ts
31 lines (27 loc) · 983 Bytes
/
meta-updater.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { App, TFile } from "obsidian";
export const upsert = async (app: App, file: TFile, key: string, value: string) => {
const content = await app.vault.read(file)
if (!content.startsWith("---")) {
return ["---", `${key}: ${value}`, "---", content].join("\n")
}
const secondTripleDashPos = content.indexOf("---", 3)
const frontmatter = content.substring(0, secondTripleDashPos + 3)
const rest = content.substring(secondTripleDashPos + 3)
let keyExists = false
const updatedFrontmatterLines = frontmatter.split("\n").map((line) => {
if (line.startsWith(`${key}:`)) {
keyExists = true
return `${key}: ${value}`
}
return line
})
const lastLine = updatedFrontmatterLines.pop()
if (!keyExists) {
updatedFrontmatterLines.push(`${key}: ${value}`)
}
if (lastLine) {
updatedFrontmatterLines.push(lastLine)
}
const updatedFrontmatter = updatedFrontmatterLines.join("\n")
return [updatedFrontmatter, rest].join("\n")
}