-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcli.js
executable file
·82 lines (68 loc) · 1.92 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
79
80
81
82
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const minimist = require('minimist');
const { render } = require('.');
const argv = minimist(process.argv.slice(2));
function usage() {
console.log(
'Usage: runmd input_file [--lame] [--watch] [--output=output_file]'
);
process.exit(1);
}
const inputName = argv._[0];
const outputName = argv.output;
// Check usage
if (!argv._.length) usage();
// Full paths (input and output)
const inputPath = path.resolve(process.cwd(), inputName);
let outputPath;
if (outputName) {
if (!/\.md$/.test(outputName)) {
throw new Error(`Output file ${outputName} must have .md extension`);
}
outputPath = outputName && path.resolve(process.cwd(), outputName);
}
/**
* Render input file to output. (args passed by fs.watchFile)
*/
async function run(curr, prev) {
// Do nothing if file not modified
if (curr && prev && curr.mtime === prev.mtime) return;
let markdown;
try {
// Read input file
const inputText = fs.readFileSync(inputPath, 'utf8');
// Render it
markdown = render(inputText, {
inputName,
outputName,
lame: argv.lame
});
// Format using prettier (if available)
try {
const prettier = require('prettier');
const config = await prettier.resolveConfig(outputPath);
markdown = await prettier.format(markdown, {
parser: 'markdown',
...config
});
} catch (err) {
console.log(`Formatting skipped (${err.message})`);
}
// Write to output (file or stdout)
if (outputPath) {
fs.writeFileSync(outputPath, markdown);
console.log('Rendered', argv.output);
} else {
process.stdout.write(markdown);
process.stdout.write('\n');
}
} catch (err) {
if (!argv.watch) throw err;
console.error(err);
}
}
run().catch(console.error);
// If --watch, rerender when file changes
if (argv.watch) fs.watchFile(inputPath, run);