parse indented documents

This commit is contained in:
Tangent Wantwight 2024-07-10 00:17:33 -04:00
parent e90727a06c
commit 2f9bb73107
2 changed files with 32 additions and 10 deletions

View file

@ -16,7 +16,11 @@ Uid: 0
Shell: tclsh Shell: tclsh
Group: users Group: users
Group: sudo Group: sudo
` Banner:
+------------------+
|Welcome to Debian!|
+------------------+
#`
); );
const pre = h("pre"); const pre = h("pre");

View file

@ -13,14 +13,30 @@ export class Idv {
} }
static parseLines(input: string[]): Idv { static parseLines(input: string[]): Idv {
const idv = new Idv(); const idv = new Idv();
let currentDocument: string[] = []; let currentDocument: string[] | undefined = undefined;
let currentIndent: string | undefined = undefined;
let bufferedBlankLines: string[] = [];
input.forEach((line) => { input.forEach((line) => {
const indent = LEADING_WHITESPACE.exec(line)?.[1]; const indent = LEADING_WHITESPACE.exec(line)?.[1];
if (indent) { if (indent) {
// TODO if (currentDocument == undefined) {
throw new Error("Indented document found before an entry");
}
if (currentIndent == undefined) {
currentIndent = indent;
}
if (line.startsWith(currentIndent)) {
currentDocument.push(...bufferedBlankLines);
bufferedBlankLines = [];
currentDocument.push(line.substring(currentIndent.length));
} else {
throw new Error(
"Inconsistent indentation- line indented less than the first line of its document"
);
}
} else if (line == "") { } else if (line == "") {
// TODO bufferedBlankLines.push("");
} else if (line[0] == "#") { } else if (line[0] == "#") {
// skip // skip
} else { } else {
@ -33,6 +49,7 @@ export class Idv {
} }
currentDocument = []; currentDocument = [];
currentIndent = undefined;
idv.collections[collection].push([distinguisher, currentDocument]); idv.collections[collection].push([distinguisher, currentDocument]);
} else { } else {
throw new Error("Failed to parse a property"); throw new Error("Failed to parse a property");
@ -47,13 +64,14 @@ export class Idv {
name: string, name: string,
parseDistinguisher: DistinguisherParser<T>, parseDistinguisher: DistinguisherParser<T>,
parseDocument: DocumentParser<T> parseDocument: DocumentParser<T>
): T | null { ): T | undefined {
const firstEntry = this.collections[name]?.[0]; const firstEntry = this.collections[name]?.[0];
return firstEntry && firstEntry[1].length > 0 return (
? parseDocument(firstEntry[1]) firstEntry &&
: firstEntry?.[0] (firstEntry[1].length > 0
? parseDistinguisher(firstEntry[0]) ? parseDocument(firstEntry[1])
: null; : parseDistinguisher(firstEntry[0]))
);
} }
public getList<T>( public getList<T>(