-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·57 lines (49 loc) · 1.56 KB
/
index.js
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
#!/usr/bin/env node
const toc = require("markdown-toc");
const walk = require("./walk");
const path = require("path");
const fs = require("fs/promises");
const yargs = require("yargs");
const args = yargs
.usage("Usage: $0 [options]")
.option("ignore", {
alias: "i",
type: "array",
description: "files and directories to ignore",
})
.option("output-file", {
alias: "o",
type: "string",
description: "path to the file to which output the Table of Content",
})
.help()
.alias("help", "h")
.example(
"$0 . -i foo.md dist/ -o README.md",
"builds a Table of Content recursively for all files in current directory excluding foo.md and dist/* and writes the result to README.md"
).argv;
const run = async () => {
const { _, ignore: ignoredPaths, "output-file": outputFile } = args;
const res = await walk(_[0]);
const markdownFiles = res?.filter((name) => name.endsWith(".md"));
const files = markdownFiles?.map((e) => path.relative(process.cwd(), e));
const withoutIgnoredPaths = files?.filter(
(e) => !ignoredPaths?.find((ignoredPath) => e.startsWith(ignoredPath))
);
let result = "";
for (let file of withoutIgnoredPaths) {
const currentFileContent = await fs.readFile(`./${file}`, "utf-8");
const fileResult = toc(currentFileContent).content;
result = `${result}\n${fileResult.replaceAll(
"(#",
`(./${encodeURIComponent(file)}#`
)}`;
}
result = `## Table of Content${result}`;
if (!outputFile) {
console.log(result);
return;
}
fs.writeFile(outputFile, result, "utf8");
};
run();