-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
58 lines (47 loc) · 1.81 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
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const util = require('util');
const proc = require('process');
const mri = require('mri');
const mkdirp = require('mkdirp');
const fastGlob = require('fast-glob');
const docks = require('./index');
const argv = mri(proc.argv.slice(2));
const app = docks();
/* eslint-disable promise/prefer-await-to-callbacks */
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const inputFiles = argv._.length > 0 ? argv._ : 'src/**/*.{js,jsx,ts,tsx}';
fastGlob(inputFiles, { ...argv, absolute: true })
.then((files) => app.render(files))
.then(async (apiContent) => {
const outfile = argv.outfile
? path.resolve(argv.outfile)
: path.resolve('README.md');
const promo = '_Generated using [docks](http://npm.im/docks)._';
const docksStart = '<!-- docks-start -->';
const docksEnd = '<!-- docks-end -->';
const content = `${docksStart}\n${promo}\n\n${apiContent}\n\n${docksEnd}`;
if (fs.existsSync(outfile)) {
const fileContent = await readFile(outfile, 'utf-8');
if (fileContent.includes(docksStart) && fileContent.includes(docksEnd)) {
const idxStart = fileContent.indexOf(docksStart);
const idxEnd = fileContent.indexOf(docksEnd) + docksEnd.length;
const apiPart = fileContent.substring(idxStart, idxEnd);
const newContent = fileContent.replace(apiPart, content);
return writeFile(outfile, newContent);
}
const msg = `Outfile should contain placeholders or not exist.`;
throw new Error(msg);
} else {
const dir = path.dirname(outfile);
await util.promisify(mkdirp)(dir);
return writeFile(outfile, content);
}
})
.catch((err) => {
console.error(err.stack);
proc.exit(1);
});