-
Notifications
You must be signed in to change notification settings - Fork 16
/
cli.js
257 lines (245 loc) · 7.74 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
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
#!/usr/bin/env node
import chalk from 'chalk'
import yargs from 'yargs/yargs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { pad } from 'lodash-es'
import { readFile } from 'node:fs/promises'
import { DateTime } from 'luxon'
import { gte } from 'semver'
import ora from 'ora'
import { checkNits } from './lib/index.mjs'
import { getModeByName } from './lib/config/modes.mjs'
// Check Node.js version
if (!gte(process.version, '18.0.0')) {
console.error('idnits3 requires Node.js v18 or later.')
process.exit(1)
}
// Define CLI arguments config
const argv = yargs(process.argv.slice(2))
.scriptName('idnits')
.usage('$0 [args] <file-path>')
.example([
['$0 draft-ietf-abcd-01.xml', ''],
[`$0 -m submission -y ${DateTime.now().year} draft-ietf-abcd-01.xml`, '']
])
.option('filter', {
alias: 'f',
describe: 'Filter output to only certain severity types. Can be declared multiple times to filter multiple severity types.',
choices: ['errors', 'warnings', 'comments'],
default: [],
nargs: 1,
type: 'array'
})
.option('mode', {
alias: 'm',
describe: 'Validation mode to use',
coerce: val => {
try {
const mode = getModeByName(val)
return mode.name
} catch (err) {
return val
}
},
choices: ['normal', 'forgive-checklist', 'submission'],
default: 'normal',
type: 'string'
})
.option('progress', {
default: true,
type: 'boolean',
hidden: true
})
.option('no-progress', {
describe: 'Disable progress messages / animations in pretty output',
type: 'boolean'
})
.option('offline', {
default: false,
describe: 'Disable validations that require an internet connection',
type: 'boolean'
})
.option('output', {
alias: 'o',
describe: 'Output format',
choices: ['pretty', 'json', 'count'],
default: 'pretty',
type: 'string'
})
.option('solarized', {
default: false,
describe: 'Use alternate colors for a solarized light themed terminal',
type: 'boolean'
})
.option('year', {
alias: 'y',
describe: 'Expect the given year in the boilerplate',
type: 'number'
})
.command('* <file>', 'parse and validate document', (y) => {
y.positional('file', {
type: 'string',
describe: 'Path of the document to validate',
normalize: true
})
})
.strict()
.alias({ h: 'help' })
.help()
.version()
.argv
// Get package version
const cliDir = path.dirname(fileURLToPath(import.meta.url))
const pkgInfo = JSON.parse(await readFile(path.join(cliDir, 'package.json'), 'utf8'))
if (argv.output === 'pretty') {
console.log(chalk.bgGray.white('▄'.repeat(64)))
console.log(chalk.bgWhite.black(`${pad('idnits ▶ ' + pkgInfo.version, 64)}`))
console.log(chalk.bgGray.white('▀'.repeat(64)))
console.log()
}
// Read document
const docPath = path.resolve(process.cwd(), argv.file)
const docPathObj = path.parse(docPath)
if (argv.output === 'pretty') {
console.log(chalk.bgWhite.black(' Path ') + ` ${docPath}`)
}
let docRaw = ''
try {
docRaw = await readFile(docPath)
} catch (err) {
console.error(chalk.redBright(`Failed to read document: ${err.message}`))
process.exit(1)
}
// Get Mode
const mode = getModeByName(argv.mode).mode
if (argv.output === 'pretty') {
console.log(chalk.bgWhite.black(' Mode ') + ` ${argv.mode} ` + chalk.grey(`[${mode}]`))
console.log()
}
// Initialize progress reporter
const spinner = ora({
text: 'Loading...',
isSilent: argv.output !== 'pretty' || !argv.progress
}).start()
function chalkAdapted (color) {
switch (color) {
case 'whiteBright':
return argv.solarized ? chalk.blackBright : chalk.whiteBright
case 'white':
return argv.solarized ? chalk.black : chalk.white
}
}
// Validate document
try {
let result = await checkNits(docRaw, docPathObj.base, {
mode,
progressReport: (msg) => { spinner.text = msg },
offline: argv.offline
})
spinner.stop()
// Filter severity types
if (argv.filter && argv.filter.length > 0) {
result = result.filter(entry => {
switch (entry.constructor.name) {
case 'ValidationError': {
return argv.filter.includes('errors')
}
case 'ValidationWarning': {
return argv.filter.includes('warnings')
}
case 'ValidationComment': {
return argv.filter.includes('comments')
}
default: {
return true
}
}
})
}
// Output results
switch (argv.output) {
// COUNT | Only return number of nits
case 'count': {
console.log(result.length)
break
}
// JSON | Return results as a stringified JSON object
case 'json': {
console.log(JSON.stringify({
result: result.length > 0 ? 'fail' : 'pass',
file: {
path: docPath,
size: 0
},
nits: result.map(r => ({
code: r.name,
desc: r.message,
...r.refUrl && { ref: r.refUrl },
...r.lines && { line: r.lines }
}))
}))
break
}
// PRETTY | Human-readable result view
case 'pretty': {
if (result.length === 0) {
console.log(chalk.bgGreen.whiteBright(' PASS ') + chalk.greenBright(' Document is VALID. 🎉\n'))
} else {
console.error(chalk.bgRed.whiteBright(' FAIL ') + chalk.redBright(' Document is INVALID. ❌\n'))
// Format errors
let entryIdx = 1
for (const entry of result) {
switch (entry.constructor.name) {
case 'ValidationError': {
console.log(chalk.bgRed.whiteBright(` ${entryIdx} `) + chalk.redBright(' Error'))
console.log(chalk.grey(' └- ') + chalkAdapted('white')('Code') + chalk.grey(' - ') + chalk.redBright(entry.name))
break
}
case 'ValidationWarning': {
console.log(chalk.bgYellow.whiteBright(` ${entryIdx} `) + chalk.yellowBright(' Warning'))
console.log(chalk.grey(' └- ') + chalkAdapted('white')('Code') + chalk.grey(' - ') + chalk.yellowBright(entry.name))
break
}
case 'ValidationComment': {
console.log(chalk.bgCyan.whiteBright(` ${entryIdx} `) + ' Comment')
console.log(chalk.grey(' └- ') + chalkAdapted('white')('Code') + chalk.grey(' - ') + chalk.cyanBright(entry.name))
break
}
default: {
console.log(chalk.bgRed.whiteBright(` ${entryIdx} `) + ' Unexpected Error')
}
}
console.log(chalk.grey(' └- ') + chalkAdapted('white')('Desc') + chalk.grey(' - ') + chalkAdapted('whiteBright')(entry.message))
if (entry.text) {
console.log(chalk.grey(' └- ') + chalkAdapted('white')('Text') + chalk.grey(' - ') + chalkAdapted('white')(entry.text))
}
if (entry.refUrl) {
console.log(chalk.grey(' └- ') + chalkAdapted('white')('Ref ') + chalk.grey(' - ') + chalk.cyan(entry.refUrl))
}
if (entry.path) {
console.log(chalk.grey(' └- ') + chalkAdapted('white')('Path') + chalk.grey(' - ') + chalkAdapted('white')(entry.path))
}
if (entry.lines) {
const lines = []
for (const line of entry.lines) {
lines.push(`Ln ${line.line} Col ${line.pos}`)
}
console.log(chalk.grey(' └- ') + chalkAdapted('white')('Line') + chalk.grey(' - ') + chalkAdapted('white')(lines.join(', ')))
}
console.log() // Empty line between entries
entryIdx++
}
}
break
}
default: {
throw new Error('Invalid Output Mode')
}
}
} catch (err) {
spinner.stop()
console.debug(err)
console.error(chalk.redBright(`Validation failed:\n- ${err.message}`))
process.exit(1)
}