Attributes now have YAML values

This commit is contained in:
Zef Hemel
2023-07-26 17:12:56 +02:00
parent 5481e49393
commit 7b8d8af2c1
12 changed files with 139 additions and 54 deletions
+12 -10
View File
@@ -1,28 +1,28 @@
import {
findNodeOfType,
ParseTree,
replaceNodesMatching,
replaceNodesMatchingAsync,
} from "$sb/lib/tree.ts";
import { YAML } from "$sb/plugos-syscall/mod.ts";
export type Attribute = {
name: string;
value: string;
};
const numberRegex = /^-?\d+(\.\d+)?$/;
/**
* Extracts attributes from a tree, optionally cleaning them out of the tree.
* @param tree tree to extract attributes from
* @param clean whether or not to clean out the attributes from the tree
* @returns mapping from attribute name to attribute value
*/
export function extractAttributes(
export async function extractAttributes(
tree: ParseTree,
clean: boolean,
): Record<string, any> {
): Promise<Record<string, any>> {
const attributes: Record<string, any> = {};
replaceNodesMatching(tree, (n) => {
await replaceNodesMatchingAsync(tree, async (n) => {
if (n.type === "ListItem") {
// Find top-level only, no nested lists
return n;
@@ -31,11 +31,13 @@ export function extractAttributes(
const nameNode = findNodeOfType(n, "AttributeName");
const valueNode = findNodeOfType(n, "AttributeValue");
if (nameNode && valueNode) {
let val: any = valueNode.children![0].text!;
if (numberRegex.test(val)) {
val = +val;
const name = nameNode.children![0].text!;
const val = valueNode.children![0].text!;
try {
attributes[name] = await YAML.parse(val);
} catch (e: any) {
console.error("Error parsing attribute value as YAML", val, e);
}
attributes[nameNode.children![0].text!] = val;
}
// Remove from tree
if (clean) {