1
0
silverbullet/plug-api/lib/cheap_yaml.ts
2023-12-22 13:59:16 +01:00

37 lines
1004 B
TypeScript

const yamlKvRegex = /^\s*(\w+):\s*["']?([^'"]*)["']?$/;
const yamlListItemRegex = /^\s*-\s+["']?([^'"]+)["']?$/;
/**
* Cheap YAML parser to determine tags (ugly, regex based but fast)
* @param yamlText
* @returns
*/
export function determineTags(yamlText: string): string[] {
const lines = yamlText.split("\n");
let inTagsSection = false;
const tags: string[] = [];
for (const line of lines) {
const yamlKv = yamlKvRegex.exec(line);
if (yamlKv) {
const [key, value] = yamlKv.slice(1);
// Looking for a 'tags' key
if (key === "tags") {
inTagsSection = true;
// 'template' there? Yay!
if (value) {
tags.push(
...value.split(/,\s*|\s+/).map((t) => t.replace(/^#/, "")),
);
}
} else {
inTagsSection = false;
}
}
const yamlListem = yamlListItemRegex.exec(line);
if (yamlListem && inTagsSection) {
tags.push(yamlListem[1].replace(/^#/, ""));
}
}
return tags;
}