Repository navigation
Expand file tree
/
Copy pathchangelog-parser.ts
More file actions
91 lines (83 loc) · 2.23 KB
/
Copy pathchangelog-parser.ts
File metadata and controls
91 lines (83 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
export type ChangelogBlock =
| { kind: "paragraph"; text: string }
| { kind: "list"; items: string[] };
type ChangelogSection = {
title: string;
blocks: ChangelogBlock[];
};
export type ChangelogEntry = {
version: string;
lede: ChangelogBlock[];
sections: ChangelogSection[];
};
export function parseChangelog(markdown: string): ChangelogEntry[] {
const entries: ChangelogEntry[] = [];
let entry: ChangelogEntry | null = null;
let section: ChangelogSection | null = null;
let paragraph: string[] = [];
const blocksInScope = (): ChangelogBlock[] | null => {
if (!entry) {
return null;
}
return section ? section.blocks : entry.lede;
};
const flushParagraph = () => {
if (paragraph.length === 0) {
return;
}
const text = paragraph.join(" ").trim();
paragraph = [];
const blocks = blocksInScope();
if (text && blocks) {
blocks.push({ kind: "paragraph", text });
}
};
for (const rawLine of markdown.split("\n")) {
const line = rawLine.trimEnd();
if (line.startsWith("## ") && !line.startsWith("### ")) {
flushParagraph();
section = null;
entry = { version: line.slice(3).trim(), lede: [], sections: [] };
entries.push(entry);
continue;
}
if (!entry) {
continue;
}
if (line.startsWith("### ")) {
flushParagraph();
section = { title: line.slice(4).trim(), blocks: [] };
entry.sections.push(section);
continue;
}
if (line.startsWith("- ")) {
flushParagraph();
const blocks = blocksInScope();
if (!blocks) {
continue;
}
const last = blocks.at(-1);
let list = last?.kind === "list" ? last : null;
if (!list) {
list = { kind: "list", items: [] };
blocks.push(list);
}
list.items.push(line.slice(2).trim());
continue;
}
if (line.startsWith(" ") && line.trim()) {
const last = blocksInScope()?.at(-1);
if (last?.kind === "list" && last.items.length > 0) {
last.items[last.items.length - 1] += ` ${line.trim()}`;
continue;
}
}
if (!line.trim()) {
flushParagraph();
continue;
}
paragraph.push(line.trim());
}
flushParagraph();
return entries;
}