(lines, indent)
| 47 | } |
| 48 | |
| 49 | function parseMap(lines, indent) { |
| 50 | const map = {}; |
| 51 | let i = 0; |
| 52 | while (i < lines.length) { |
| 53 | const line = lines[i]; |
| 54 | if (!line.trim() || line.trim().startsWith("#")) { |
| 55 | i += 1; |
| 56 | continue; |
| 57 | } |
| 58 | if (indentOf(line) !== indent) { |
| 59 | throw new Error(`unexpected indentation: "${line.trim()}"`); |
| 60 | } |
| 61 | const match = line.trim().match(/^([A-Za-z0-9_-]+):(.*)$/); |
| 62 | if (!match) { |
| 63 | throw new Error(`cannot parse line: "${line.trim()}"`); |
| 64 | } |
| 65 | const key = match[1]; |
| 66 | if (key in map) { |
| 67 | throw new Error(`duplicate key "${key}"`); |
| 68 | } |
| 69 | const value = match[2].trim(); |
| 70 | i += 1; |
| 71 | |
| 72 | // Collect lines indented deeper than the current key. |
| 73 | const children = []; |
| 74 | while (i < lines.length) { |
| 75 | const child = lines[i]; |
| 76 | if (!child.trim() || indentOf(child) > indent) { |
| 77 | children.push(child); |
| 78 | i += 1; |
| 79 | } else { |
| 80 | break; |
| 81 | } |
| 82 | } |
| 83 | const nonEmpty = children.filter((l) => l.trim()); |
| 84 | |
| 85 | if (value === "|" || value === "|-" || value === ">" || value === ">-") { |
| 86 | if (nonEmpty.length === 0) { |
| 87 | throw new Error(`empty block scalar for key "${key}"`); |
| 88 | } |
| 89 | const childIndent = Math.min(...nonEmpty.map(indentOf)); |
| 90 | map[key] = children |
| 91 | .map((l) => l.slice(childIndent)) |
| 92 | .join("\n") |
| 93 | .trim(); |
| 94 | } else if (value === "") { |
| 95 | if (nonEmpty.length === 0) { |
| 96 | map[key] = ""; |
| 97 | } else { |
| 98 | const childIndent = Math.min(...nonEmpty.map(indentOf)); |
| 99 | map[key] = nonEmpty[0].trim().startsWith("-") |
| 100 | ? parseList(nonEmpty, childIndent) |
| 101 | : parseMap(nonEmpty, childIndent); |
| 102 | } |
| 103 | } else { |
| 104 | if (nonEmpty.length > 0) { |
| 105 | throw new Error(`unexpected indented block under "${key}: ${value}"`); |
| 106 | } |
no test coverage detected