This repository has been archived by the owner on Aug 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathparse.ts
286 lines (260 loc) · 8.25 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
// tslint:disable interface-over-type-literal
import {Arg} from './args'
import Deps from './deps'
import * as Errors from './errors'
import * as Flags from './flags'
import {Metadata} from './metadata'
import * as Util from './util'
// eslint-disable-next-line new-cap
const m = Deps()
// eslint-disable-next-line node/no-missing-require
.add('errors', () => require('./errors') as typeof Errors)
// eslint-disable-next-line node/no-missing-require
.add('util', () => require('./util') as typeof Util)
let debug: any
try {
// eslint-disable-next-line no-negated-condition
if (process.env.CLI_FLAGS_DEBUG !== '1') debug = () => {}
else
// eslint-disable-next-line node/no-extraneous-require
debug = require('debug')('@oclif/parser')
} catch {
debug = () => {}
}
export type OutputArgs = { [name: string]: any }
export type OutputFlags<T extends ParserInput['flags']> = { [P in keyof T]: any }
export type ParserOutput<TFlags extends OutputFlags<any>, TArgs extends OutputArgs> = {
flags: TFlags;
args: TArgs;
argv: string[];
raw: ParsingToken[];
metadata: Metadata;
}
export type ArgToken = { type: 'arg'; input: string }
export type FlagToken = { type: 'flag'; flag: string; input: string }
export type ParsingToken = ArgToken | FlagToken
export interface ParserInput {
argv: string[];
flags: Flags.Input<any>;
args: Arg<any>[];
strict: boolean;
context: any;
'--'?: boolean;
}
export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']>, TArgs extends OutputArgs> {
private readonly argv: string[]
private readonly raw: ParsingToken[] = []
private readonly booleanFlags: { [k: string]: Flags.IBooleanFlag<any> }
private readonly context: any
private readonly metaData: any
private currentFlag?: Flags.IOptionFlag<any>
constructor(private readonly input: T) {
const {pickBy} = m.util
this.context = input.context || {}
this.argv = input.argv.slice(0)
this._setNames()
this.booleanFlags = pickBy(input.flags, f => f.type === 'boolean') as any
this.metaData = {}
}
public parse() {
this._debugInput()
const findLongFlag = (arg: string) => {
const name = arg.slice(2)
if (this.input.flags[name]) {
return name
}
if (arg.startsWith('--no-')) {
const flag = this.booleanFlags[arg.slice(5)]
if (flag && flag.allowNo) return flag.name
}
}
const findShortFlag = (arg: string) => {
return Object.keys(this.input.flags).find(k => this.input.flags[k].char === arg[1])
}
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
let input
if (long || arg.length < 3) {
input = this.argv.shift()
} else {
input = arg.slice(arg[2] === '=' ? 3 : 2)
}
if (typeof input !== 'string') {
throw new m.errors.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
while (this.argv.length) {
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
}
// not actually a flag if it reaches here so parse as an arg
}
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 = this.input.args[this._argTokens.length]
if (arg) arg.input = input
this.raw.push({type: 'arg', input})
}
const argv = this._argv()
const args = this._args(argv)
const flags = this._flags()
this._debugOutput(argv, args, flags)
return {
args,
argv,
flags,
raw: this.raw,
metadata: this.metaData,
}
}
private _args(argv: any[]): TArgs {
const args = {} as any
for (let i = 0; i < this.input.args.length; i++) {
const arg = this.input.args[i]
args[arg.name!] = argv[i]
}
return args
}
private _flags(): TFlags {
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 m.errors.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] = flag.parse(flags[token.flag], this.context)
} else {
const input = token.input
if (flag.options && !flag.options.includes(input)) {
throw new m.errors.FlagInvalidOptionError(flag, input)
}
const value = flag.parse ? flag.parse(input, this.context) : input
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.type === 'option' && flag.env) {
const input = process.env[flag.env]
if (input) flags[k] = flag.parse(input, this.context)
}
if (!(k in flags) && flag.default !== undefined) {
this.metaData.flags[k] = {setFromDefault: true}
if (typeof flag.default === 'function') {
flags[k] = flag.default({options: flag, flags, ...this.context})
} else {
flags[k] = flag.default
}
}
}
return flags
}
private _argv(): any[] {
const args: any[] = []
const tokens = this._argTokens
for (let i = 0; i < Math.max(this.input.args.length, tokens.length); i++) {
const token = tokens[i]
const arg = this.input.args[i]
if (token) {
if (arg) {
if (arg.options && !arg.options.includes(token.input)) {
throw new m.errors.ArgInvalidOptionError(arg, token.input)
}
args[i] = arg.parse(token.input)
} else {
args[i] = token.input
}
} else if ('default' in arg) {
if (typeof arg.default === 'function') {
args[i] = arg.default()
} else {
args[i] = arg.default
}
}
}
return 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(' '))
if (this.input.args.length > 0) {
debug('available args: %s', this.input.args.map(a => a.name).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
}
}
}