From 2f9bb73107078b231316f056b107058ac19180f1 Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Wed, 10 Jul 2024 00:17:33 -0400 Subject: [PATCH] parse indented documents --- debug/idv.ts | 6 +++++- lib/idv.ts | 36 +++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/debug/idv.ts b/debug/idv.ts index 43dbd7e..b54354c 100644 --- a/debug/idv.ts +++ b/debug/idv.ts @@ -16,7 +16,11 @@ Uid: 0 Shell: tclsh Group: users Group: sudo - ` +Banner: + +------------------+ + |Welcome to Debian!| + +------------------+ +#` ); const pre = h("pre"); diff --git a/lib/idv.ts b/lib/idv.ts index 2521e82..a656145 100644 --- a/lib/idv.ts +++ b/lib/idv.ts @@ -13,14 +13,30 @@ export class Idv { } static parseLines(input: string[]): Idv { const idv = new Idv(); - let currentDocument: string[] = []; + let currentDocument: string[] | undefined = undefined; + let currentIndent: string | undefined = undefined; + let bufferedBlankLines: string[] = []; input.forEach((line) => { const indent = LEADING_WHITESPACE.exec(line)?.[1]; 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 == "") { - // TODO + bufferedBlankLines.push(""); } else if (line[0] == "#") { // skip } else { @@ -33,6 +49,7 @@ export class Idv { } currentDocument = []; + currentIndent = undefined; idv.collections[collection].push([distinguisher, currentDocument]); } else { throw new Error("Failed to parse a property"); @@ -47,13 +64,14 @@ export class Idv { name: string, parseDistinguisher: DistinguisherParser, parseDocument: DocumentParser - ): T | null { + ): T | undefined { const firstEntry = this.collections[name]?.[0]; - return firstEntry && firstEntry[1].length > 0 - ? parseDocument(firstEntry[1]) - : firstEntry?.[0] - ? parseDistinguisher(firstEntry[0]) - : null; + return ( + firstEntry && + (firstEntry[1].length > 0 + ? parseDocument(firstEntry[1]) + : parseDistinguisher(firstEntry[0])) + ); } public getList(