-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathparse.ts
405 lines (336 loc) · 12.1 KB
/
parse.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/* eslint-disable no-await-in-loop */
import {ArgInvalidOptionError, CLIError, FlagInvalidOptionError} from './errors'
import {ArgToken, BooleanFlag, FlagToken, OptionFlag, OutputArgs, OutputFlags, ParserInput, ParserOutput, ParsingToken} from '../interfaces/parser'
import * as readline from 'readline'
import {isTruthy, pickBy} from '../util'
let debug: any
try {
// eslint-disable-next-line no-negated-condition
debug = process.env.CLI_FLAGS_DEBUG !== '1' ? () => {} : require('debug')('../parser')
} catch {
debug = () => {}
}
const readStdin = async (): Promise<string | null> => {
const {stdin, stdout} = process
debug('stdin.isTTY', stdin.isTTY)
if (stdin.isTTY) return null
// process.stdin.isTTY is true whenever it's running in a terminal.
// process.stdin.isTTY is undefined when it's running in a pipe, e.g. echo 'foo' | my-cli command
// process.stdin.isTTY is undefined when it's running in a spawned process, even if there's no pipe.
// This means that reading from stdin could hang indefinitely while waiting for a non-existent pipe.
// Because of this, we have to set a timeout to prevent the process from hanging.
return new Promise(resolve => {
let result = ''
const ac = new AbortController()
const signal = ac.signal
const timeout = setTimeout(() => ac.abort(), 100)
const rl = readline.createInterface({
input: stdin,
output: stdout,
terminal: false,
})
rl.on('line', line => {
result += line
})
rl.once('close', () => {
clearTimeout(timeout)
debug('resolved from stdin', result)
resolve(result)
})
signal.addEventListener('abort', () => {
debug('stdin aborted')
clearTimeout(timeout)
rl.close()
resolve(null)
}, {once: true})
})
}
function isNegativeNumber(input: string): boolean {
return /^-\d/g.test(input)
}
export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']>, BFlags extends OutputFlags<T['flags']>, TArgs extends OutputArgs<T['args']>> {
private readonly argv: string[]
private readonly raw: ParsingToken[] = []
private readonly booleanFlags: { [k: string]: BooleanFlag<any> }
private readonly flagAliases: { [k: string]: BooleanFlag<any> | OptionFlag<any> }
private readonly context: any
private readonly metaData: any
private currentFlag?: OptionFlag<any>
constructor(private readonly input: T) {
this.context = input.context || {}
this.argv = [...input.argv]
this._setNames()
this.booleanFlags = pickBy(input.flags, f => f.type === 'boolean') as any
this.flagAliases = Object.fromEntries(Object.values(input.flags).flatMap(flag => {
return (flag.aliases ?? []).map(a => [a, flag])
}))
this.metaData = {}
}
public async parse(): Promise<ParserOutput<TFlags, BFlags, TArgs>> {
this._debugInput()
const findLongFlag = (arg: string) => {
const name = arg.slice(2)
if (this.input.flags[name]) {
return name
}
if (this.flagAliases[name]) {
return this.flagAliases[name].name
}
if (arg.startsWith('--no-')) {
const flag = this.booleanFlags[arg.slice(5)]
if (flag && flag.allowNo) return flag.name
}
}
const findShortFlag = ([_, char]: string) => {
if (this.flagAliases[char]) {
return this.flagAliases[char].name
}
return Object.keys(this.input.flags).find(k => this.input.flags[k].char === char)
}
const parseFlag = (arg: string): boolean => {
const long = arg.startsWith('--')
const name = long ? findLongFlag(arg) : findShortFlag(arg)
if (!name) {
const i = arg.indexOf('=')
if (i !== -1) {
const sliced = arg.slice(i + 1)
this.argv.unshift(sliced)
const equalsParsed = parseFlag(arg.slice(0, i))
if (!equalsParsed) {
this.argv.shift()
}
return equalsParsed
}
return false
}
const flag = this.input.flags[name]
if (flag.type === 'option') {
this.currentFlag = flag
const input = long || arg.length < 3 ? this.argv.shift() : arg.slice(arg[2] === '=' ? 3 : 2)
if (typeof input !== 'string') {
throw new CLIError(`Flag --${name} expects a value`)
}
this.raw.push({type: 'flag', flag: flag.name, input})
} else {
this.raw.push({type: 'flag', flag: flag.name, input: arg})
// push the rest of the short characters back on the stack
if (!long && arg.length > 2) {
this.argv.unshift(`-${arg.slice(2)}`)
}
}
return true
}
let parsingFlags = true
const nonExistentFlags: string[] = []
let dashdash = false
const originalArgv = [...this.argv]
while (this.argv.length > 0) {
const input = this.argv.shift() as string
if (parsingFlags && input.startsWith('-') && input !== '-') {
// attempt to parse as arg
if (this.input['--'] !== false && input === '--') {
parsingFlags = false
continue
}
if (parseFlag(input)) {
continue
}
if (input === '--') {
dashdash = true
continue
}
if (this.input['--'] !== false && !isNegativeNumber(input)) {
// At this point we have a value that begins with '-' or '--'
// but doesn't match up to a flag definition. So we assume that
// this is a misspelled flag or a non-existent flag,
// e.g. --hekp instead of --help
nonExistentFlags.push(input)
continue
}
}
if (parsingFlags && this.currentFlag && this.currentFlag.multiple) {
this.raw.push({type: 'flag', flag: this.currentFlag.name, input})
continue
}
// not a flag, parse as arg
const arg = Object.keys(this.input.args)[this._argTokens.length]
this.raw.push({type: 'arg', arg, input})
}
const {argv, args} = await this._args()
const flags = await this._flags()
this._debugOutput(argv, args, flags)
const unsortedArgv = (dashdash ? [...argv, ...nonExistentFlags, '--'] : [...argv, ...nonExistentFlags]) as string[]
return {
argv: unsortedArgv.sort((a, b) => originalArgv.indexOf(a) - originalArgv.indexOf(b)),
flags,
args: args as TArgs,
raw: this.raw,
metadata: this.metaData,
nonExistentFlags,
}
}
// eslint-disable-next-line complexity
private async _flags(): Promise<TFlags & BFlags & { json: boolean | undefined }> {
const flags = {} as any
this.metaData.flags = {} as any
for (const token of this._flagTokens) {
const flag = this.input.flags[token.flag]
if (!flag) throw new CLIError(`Unexpected flag ${token.flag}`)
if (flag.type === 'boolean') {
if (token.input === `--no-${flag.name}`) {
flags[token.flag] = false
} else {
flags[token.flag] = true
}
flags[token.flag] = await this._parseFlag(flags[token.flag], flag, token)
} else {
const input = token.input
if (flag.delimiter && flag.multiple) {
// split, trim, and remove surrounding doubleQuotes (which would hav been needed if the elements contain spaces)
const values = await Promise.all(
input.split(flag.delimiter).map(async v => this._parseFlag(v.trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1'), flag, token)),
)
// then parse that each element aligns with the `options` property
for (const v of values) {
this._validateOptions(flag, v)
}
flags[token.flag] = flags[token.flag] || []
flags[token.flag].push(...values)
} else {
this._validateOptions(flag, input)
const value = await this._parseFlag(input, flag, token)
if (flag.multiple) {
flags[token.flag] = flags[token.flag] || []
flags[token.flag].push(value)
} else {
flags[token.flag] = value
}
}
}
}
for (const k of Object.keys(this.input.flags)) {
const flag = this.input.flags[k]
if (flags[k]) continue
if (flag.env && Object.prototype.hasOwnProperty.call(process.env, flag.env)) {
const input = process.env[flag.env]
if (flag.type === 'option') {
if (input) {
this._validateOptions(flag, input)
flags[k] = await this._parseFlag(input, flag)
}
} else if (flag.type === 'boolean') {
// eslint-disable-next-line no-negated-condition
flags[k] = input !== undefined ? isTruthy(input) : false
}
}
if (!(k in flags) && flag.default !== undefined) {
this.metaData.flags[k] = {setFromDefault: true}
const defaultValue = (typeof flag.default === 'function' ? await flag.default({options: flag, flags, ...this.context}) : flag.default)
flags[k] = defaultValue
}
}
return flags
}
private async _parseFlag(input: any, flag: BooleanFlag<any> | OptionFlag<any>, token?: FlagToken) {
if (!flag.parse) return input
try {
const ctx = this.context
ctx.token = token
if (flag.type === 'boolean') {
const ctx = this.context
ctx.token = token
return await flag.parse(input, ctx, flag)
}
return flag.parse ? await flag.parse(input, ctx, flag) : input
} catch (error: any) {
error.message = `Parsing --${flag.name} \n\t${error.message}\nSee more help with --help`
throw error
}
}
private _validateOptions(flag: OptionFlag<any>, input: string) {
if (flag.options && !flag.options.includes(input))
throw new FlagInvalidOptionError(flag, input)
}
private async _args(): Promise<{ argv: unknown[]; args: Record<string, unknown>}> {
const argv: unknown[] = []
const args = {} as Record<string, unknown>
const tokens = this._argTokens
let stdinRead = false
const ctx = this.context
for (const [name, arg] of Object.entries(this.input.args)) {
const token = tokens.find(t => t.arg === name)
ctx.token = token
if (token) {
if (arg.options && !arg.options.includes(token.input)) {
throw new ArgInvalidOptionError(arg, token.input)
}
const parsed = await arg.parse(token.input, ctx, arg)
argv.push(parsed)
args[token.arg] = parsed
} else if (!arg.ignoreStdin && !stdinRead) {
let stdin = await readStdin()
if (stdin) {
stdin = stdin.trim()
const parsed = await arg.parse(stdin, ctx, arg)
argv.push(parsed)
args[name] = parsed
}
stdinRead = true
}
if (!args[name] && (arg.default || arg.default === false)) {
if (typeof arg.default === 'function') {
const f = await arg.default()
argv.push(f)
args[name] = f
} else {
argv.push(arg.default)
args[name] = arg.default
}
}
}
for (const token of tokens) {
if (args[token.arg]) continue
argv.push(token.input)
}
return {argv, args: args}
}
private _debugOutput(args: any, flags: any, argv: any) {
if (argv.length > 0) {
debug('argv: %o', argv)
}
if (Object.keys(args).length > 0) {
debug('args: %o', args)
}
if (Object.keys(flags).length > 0) {
debug('flags: %o', flags)
}
}
private _debugInput() {
debug('input: %s', this.argv.join(' '))
const args = Object.keys(this.input.args)
if (args.length > 0) {
debug('available args: %s', args.join(' '))
}
if (Object.keys(this.input.flags).length === 0) return
debug(
'available flags: %s',
Object.keys(this.input.flags)
.map(f => `--${f}`)
.join(' '),
)
}
private get _argTokens(): ArgToken[] {
return this.raw.filter(o => o.type === 'arg') as ArgToken[]
}
private get _flagTokens(): FlagToken[] {
return this.raw.filter(o => o.type === 'flag') as FlagToken[]
}
private _setNames() {
for (const k of Object.keys(this.input.flags)) {
this.input.flags[k].name = k
}
for (const k of Object.keys(this.input.args)) {
this.input.args[k].name = k
}
}
}