-
Notifications
You must be signed in to change notification settings - Fork 79
/
cli.ts
292 lines (260 loc) · 8.29 KB
/
cli.ts
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/env node
import * as meow from 'meow';
import * as updateNotifier from 'update-notifier';
import chalk = require('chalk');
import {LinkChecker, LinkState, LinkResult, CheckOptions} from './index';
import {promisify} from 'util';
import {Flags, getConfig} from './config';
import {Format, Logger, LogLevel} from './logger';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const toCSV = promisify(require('jsonexport'));
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pkg = require('../../package.json');
updateNotifier({pkg}).notify();
/* eslint-disable no-process-exit */
const cli = meow(
`
Usage
$ linkinator LOCATION [ --arguments ]
Positional arguments
LOCATION
Required. Either the URLs or the paths on disk to check for broken links.
Flags
--concurrency
The number of connections to make simultaneously. Defaults to 100.
--config
Path to the config file to use. Looks for \`linkinator.config.json\` by default.
--directory-listing
Include an automatic directory index file when linking to a directory.
Defaults to 'false'.
--format, -f
Return the data in CSV or JSON format.
--help
Show this command.
--markdown
Automatically parse and scan markdown if scanning from a location on disk.
--recurse, -r
Recursively follow links on the same root domain.
--server-root
When scanning a locally directory, customize the location on disk
where the server is started. Defaults to the path passed in [LOCATION].
--skip, -s
List of urls in regexy form to not include in the check.
--timeout
Request timeout in ms. Defaults to 0 (no timeout).
--verbosity
Override the default verbosity for this command. Available options are
'debug', 'info', 'warning', 'error', and 'none'. Defaults to 'warning'.
Examples
$ linkinator docs/
$ linkinator https://www.google.com
$ linkinator . --recurse
$ linkinator . --skip www.googleapis.com
$ linkinator . --format CSV
`,
{
flags: {
config: {type: 'string'},
concurrency: {type: 'number'},
recurse: {type: 'boolean', alias: 'r'},
skip: {type: 'string', alias: 's'},
format: {type: 'string', alias: 'f'},
silent: {type: 'boolean'},
timeout: {type: 'number'},
markdown: {type: 'boolean'},
serverRoot: {type: 'string'},
verbosity: {type: 'string'},
directoryListing: {type: 'boolean'},
},
booleanDefault: undefined,
}
);
let flags: Flags;
async function main() {
if (cli.input.length < 1) {
cli.showHelp();
return;
}
flags = await getConfig(cli.flags);
const start = Date.now();
const verbosity = parseVerbosity(cli.flags);
const format = parseFormat(cli.flags);
const logger = new Logger(verbosity, format);
logger.error(`🏊♂️ crawling ${cli.input}`);
const checker = new LinkChecker();
checker.on('link', (link: LinkResult) => {
let state = '';
switch (link.state) {
case LinkState.BROKEN:
state = `[${chalk.red(link.status!.toString())}]`;
logger.error(`${state} ${chalk.gray(link.url)}`);
break;
case LinkState.OK:
state = `[${chalk.green(link.status!.toString())}]`;
logger.warn(`${state} ${chalk.gray(link.url)}`);
break;
case LinkState.SKIPPED:
state = `[${chalk.grey('SKP')}]`;
logger.info(`${state} ${chalk.gray(link.url)}`);
break;
}
});
const opts: CheckOptions = {
path: cli.input,
recurse: flags.recurse,
timeout: Number(flags.timeout),
markdown: flags.markdown,
concurrency: Number(flags.concurrency),
serverRoot: flags.serverRoot,
directoryListing: flags.directoryListing,
};
if (flags.skip) {
if (typeof flags.skip === 'string') {
opts.linksToSkip = flags.skip.split(' ').filter(x => !!x);
} else if (Array.isArray(flags.skip)) {
opts.linksToSkip = flags.skip;
}
}
const result = await checker.check(opts);
const filteredResults = result.links.filter(link => {
switch (link.state) {
case LinkState.OK:
return verbosity <= LogLevel.WARNING;
case LinkState.BROKEN:
if (verbosity > LogLevel.DEBUG) {
link.failureDetails = undefined;
}
return verbosity <= LogLevel.ERROR;
case LinkState.SKIPPED:
return verbosity <= LogLevel.INFO;
}
});
if (format === Format.JSON) {
result.links = filteredResults;
console.log(JSON.stringify(result, null, 2));
return;
} else if (format === Format.CSV) {
result.links = filteredResults;
const csv = await toCSV(result.links);
console.log(csv);
return;
} else {
// Build a collection scanned links, collated by the parent link used in
// the scan. For example:
// {
// "./README.md": [
// {
// url: "https://img.shields.io/npm/v/linkinator.svg",
// status: 200
// ....
// }
// ],
// }
const parents = result.links.reduce((acc, curr) => {
const parent = curr.parent || '';
if (!acc[parent]) {
acc[parent] = [];
}
acc[parent].push(curr);
return acc;
}, {} as {[index: string]: LinkResult[]});
Object.keys(parents).forEach(parent => {
// prune links based on verbosity
const links = parents[parent].filter(link => {
if (verbosity === LogLevel.NONE) {
return false;
}
if (link.state === LinkState.BROKEN) {
return true;
}
if (link.state === LinkState.OK) {
if (verbosity <= LogLevel.WARNING) {
return true;
}
}
if (link.state === LinkState.SKIPPED) {
if (verbosity <= LogLevel.INFO) {
return true;
}
}
return false;
});
if (links.length === 0) {
return;
}
logger.error(chalk.blue(parent));
links.forEach(link => {
let state = '';
switch (link.state) {
case LinkState.BROKEN:
state = `[${chalk.red(link.status!.toString())}]`;
logger.error(` ${state} ${chalk.gray(link.url)}`);
logger.debug(JSON.stringify(link.failureDetails, null, 2));
break;
case LinkState.OK:
state = `[${chalk.green(link.status!.toString())}]`;
logger.warn(` ${state} ${chalk.gray(link.url)}`);
break;
case LinkState.SKIPPED:
state = `[${chalk.grey('SKP')}]`;
logger.info(` ${state} ${chalk.gray(link.url)}`);
break;
}
});
});
}
const total = (Date.now() - start) / 1000;
if (!result.passed) {
const borked = result.links.filter(x => x.state === LinkState.BROKEN);
logger.error(
chalk.bold(
`${chalk.red('ERROR')}: Detected ${
borked.length
} broken links. Scanned ${chalk.yellow(
result.links.length.toString()
)} links in ${chalk.cyan(total.toString())} seconds.`
)
);
process.exit(1);
}
logger.error(
chalk.bold(
`🤖 Successfully scanned ${chalk.green(
result.links.length.toString()
)} links in ${chalk.cyan(total.toString())} seconds.`
)
);
}
function parseVerbosity(flags: typeof cli.flags): LogLevel {
if (flags.silent && flags.verbosity) {
throw new Error(
'The SILENT and VERBOSITY flags cannot both be defined. Please consider using VERBOSITY only.'
);
}
if (flags.silent) {
return LogLevel.ERROR;
}
if (!flags.verbosity) {
return LogLevel.WARNING;
}
const verbosity = flags.verbosity.toUpperCase();
const options = Object.values(LogLevel);
if (!options.includes(verbosity)) {
throw new Error(
`Invalid flag: VERBOSITY must be one of [${options.join(',')}]`
);
}
return LogLevel[verbosity as keyof typeof LogLevel];
}
function parseFormat(flags: typeof cli.flags): Format {
if (!flags.format) {
return Format.TEXT;
}
flags.format = flags.format.toUpperCase();
const options = Object.values(Format);
if (!options.includes(flags.format)) {
throw new Error("Invalid flag: FORMAT must be 'TEXT', 'JSON', or 'CSV'.");
}
return Format[flags.format as keyof typeof Format];
}
main();