-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
Copy pathlint-md.src.mjs
53 lines (46 loc) · 1.5 KB
/
lint-md.src.mjs
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
import fs from 'fs';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkStringify from 'remark-stringify';
import presetLintNode from 'remark-preset-lint-node';
import { read } from 'to-vfile';
import { reporter } from 'vfile-reporter';
const paths = process.argv.slice(2);
if (!paths.length) {
console.error('Usage: lint-md.mjs <path> [<path> ...]');
process.exit(1);
}
let format = false;
if (paths[0] === '--format') {
paths.shift();
format = true;
}
const linter = unified()
.use(remarkParse)
.use(presetLintNode)
.use(remarkStringify);
paths.forEach(async (path) => {
const file = await read(path);
// We need to calculate `fileContents` before running `linter.process(files)`
// because `linter.process(files)` mutates `file` and returns it as `result`.
// So we won't be able to use `file` after that to see if its contents have
// changed as they will have been altered to the changed version.
const fileContents = file.toString();
const result = await linter.process(file);
const isDifferent = fileContents !== result.toString();
if (format) {
if (isDifferent) {
fs.writeFileSync(path, result.toString());
}
} else {
if (isDifferent) {
process.exitCode = 1;
const cmd = process.platform === 'win32' ? 'vcbuild' : 'make';
console.error(`${path} is not formatted. Please run '${cmd} format-md'.`);
}
if (result.messages.length) {
process.exitCode = 1;
console.error(reporter(result));
}
}
});