-
-
Notifications
You must be signed in to change notification settings - Fork 708
/
cli.js
executable file
·78 lines (70 loc) · 2.38 KB
/
cli.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env node
var fs = require('fs');
var toc = require('./index.js');
var utils = require('./lib/utils');
var args = utils.minimist(process.argv.slice(2), {
boolean: ['i', 'json', 'firsth1', 'stripHeadingTags'],
string: ['append', 'bullets', 'indent'],
default: {
firsth1: true,
stripHeadingTags: true
}
});
if (args._.length !== 1) {
console.error([
'Usage: markdown-toc [options] <input> ',
'',
' input: The Markdown file to parse for table of contents,',
' or "-" to read from stdin.',
'',
' -i: Edit the <input> file directly, injecting the TOC at <!-- toc -->',
' (Without this flag, the default is to print the TOC to stdout.)',
'',
' --json: Print the TOC in JSON format',
'',
' --append: Append a string to the end of the TOC',
'',
' --bullets: Bullets to use for items in the generated TOC',
' (Supports multiple bullets: --bullets "*" --bullets "-" --bullets "+")',
' (Default is "*".)',
'',
' --maxdepth: Use headings whose depth is at most maxdepth',
' (Default is 6.)',
'',
' --no-firsth1: Include the first h1-level heading in a file',
'',
' --no-stripHeadingTags: Do not strip extraneous HTML tags from heading',
' text before slugifying',
'',
' --indent: Provide the indentation to use - defaults to \' \'',
' (to specify a tab, use the bash-escaped $\'\\t\')'
].join('\n'));
process.exit(1);
}
if (args.i && args.json) {
console.error('markdown-toc: you cannot use both --json and -i');
process.exit(1);
}
if (args.i && args._[0] === '-') {
console.error('markdown-toc: you cannot use -i with "-" (stdin) for input');
process.exit(1);
}
var input = process.stdin;
if (args._[0] !== '-') input = fs.createReadStream(args._[0]);
input.pipe(utils.concat(function(input) {
if (args.i) {
var newMarkdown = toc.insert(input.toString(), args);
fs.writeFileSync(args._[0], newMarkdown);
} else {
var parsed = toc(input.toString(), args);
output(parsed);
}
}));
input.on('error', function onErr(err) {
console.error(err);
process.exit(1);
});
function output(parsed) {
if (args.json) return console.log(JSON.stringify(parsed.json, null, ' '));
process.stdout.write(parsed.content);
}