-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
39 lines (39 loc) · 1.44 KB
/
index.ts
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
import escapeStringRegexp from "escape-string-regexp";
import fs from "fs";
import { resolve } from "path";
const { readFile, writeFile } = fs.promises;
export default async function mdAggregate({
input = [] as string[],
target = "",
write = false,
} = {}) {
let dstContent = await readFile(resolve(target), "utf8");
await Promise.all(input.map(srcProcess));
if (write) {
await writeFile(resolve(target), dstContent);
console.log(resolve(target));
} else {
console.log(dstContent);
}
return;
async function srcProcess(src: string) {
const srcContent = await readFile(resolve(src), "utf8");
if (!srcContent.match(/^# /)) throw new Error("srcContent must start with '# '");
const lines = srcContent
.trim()
.split(/\r?\n/)
.map((e) => e.replace(/^#/gim, "##"));
// TODO: test with \r\n
const matchStartPattern = `\n${escapeStringRegexp(lines[0])}$`;
const eofPattern = "$(?![\\r\\n])";
const sectionStartPattern = `\n##? `;
const startPattern = `${matchStartPattern}|${eofPattern}`;
const anyPattern = `[\\s\\S]*?`;
const endPattern = `${eofPattern}|${sectionStartPattern}`;
const srcContentWithoutSectionStart = lines
.join("\n")
.replace(new RegExp(sectionStartPattern, "img"), "\n### ");
const pattern = new RegExp(`(${startPattern})${anyPattern}(?=${endPattern})`, "m");
dstContent = dstContent.replace(pattern, `\n${srcContentWithoutSectionStart}\n`);
}
}