-
Notifications
You must be signed in to change notification settings - Fork 73
/
command.ts
457 lines (381 loc) · 13.5 KB
/
command.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import {fileURLToPath} from 'node:url'
import {inspect} from 'node:util'
import Cache from './cache'
import {Config} from './config'
import * as Errors from './errors'
import {PrettyPrintableError} from './errors'
import {formatCommandDeprecationWarning, formatFlagDeprecationWarning, normalizeArgv} from './help/util'
import {LoadOptions} from './interfaces/config'
import {CommandError} from './interfaces/errors'
import {
ArgInput,
ArgOutput,
ArgProps,
BooleanFlagProps,
Deprecation,
FlagInput,
FlagOutput,
Arg as IArg,
Flag as IFlag,
Input,
OptionFlagProps,
ParserOutput,
} from './interfaces/parser'
import {Plugin} from './interfaces/plugin'
import {makeDebug} from './logger'
import * as Parser from './parser'
import {aggregateFlags} from './util/aggregate-flags'
import {toConfiguredId} from './util/ids'
import {uniq} from './util/util'
import {ux} from './ux'
const pjson = Cache.getInstance().get('@oclif/core')
/**
* swallows stdout epipe errors
* this occurs when stdout closes such as when piping to head
*/
process.stdout.on('error', (err: any) => {
if (err && err.code === 'EPIPE') return
throw err
})
/**
* An abstract class which acts as the base for each command
* in your project.
*/
export abstract class Command {
/** An array of aliases for this command. */
public static aliases: string[] = []
/** An order-dependent object of arguments for the command */
public static args: ArgInput = {}
public static baseFlags: FlagInput
/**
* Emit deprecation warning when a command alias is used
*/
static deprecateAliases?: boolean
public static deprecationOptions?: Deprecation
/**
* A full description of how to use the command.
*
* If no summary, the first line of the description will be used as the summary.
*/
public static description: string | undefined
public static enableJsonFlag = false
/**
* An array of examples to show at the end of the command's help.
*
* IF only a string is provided, it will try to look for a line that starts
* with the cmd.bin as the example command and the rest as the description.
* If found, the command will be formatted appropriately.
*
* ```
* EXAMPLES:
* A description of a particular use case.
*
* $ <%= config.bin => command flags
* ```
*/
public static examples: Command.Example[]
/** A hash of flags for the command */
public static flags: FlagInput
public static hasDynamicHelp = false
public static help: string | undefined
/** Hide the command from help */
public static hidden: boolean
/** An array of aliases for this command that are hidden from help. */
public static hiddenAliases: string[] = []
/** A command ID, used mostly in error or verbose reporting. */
public static id: string
public static plugin: Plugin | undefined
public static readonly pluginAlias?: string
public static readonly pluginName?: string
public static readonly pluginType?: string
/** Mark the command as a given state (e.g. beta or deprecated) in help */
public static state?: 'beta' | 'deprecated' | string
/** When set to false, allows a variable amount of arguments */
public static strict = true
/**
* The tweet-sized description for your class, used in a parent-commands
* sub-command listing and as the header for the command help.
*/
public static summary?: string
/**
* An override string (or strings) for the default usage documentation.
*/
public static usage: string | string[] | undefined
protected debug: (...args: any[]) => void
public id: string | undefined
private static readonly _base = `${pjson.name}@${pjson.version}`
public constructor(
public argv: string[],
public config: Config,
) {
this.id = this.ctor.id
try {
this.debug = makeDebug(this.id ? `${this.config.bin}:${this.id}` : this.config.bin)
} catch {
this.debug = () => {
// noop
}
}
}
/**
* actual command run code goes here
*/
public abstract run(): Promise<any>
/**
* instantiate and run the command
*
* @param {Command.Class} this - the command class
* @param {string[]} argv argv
* @param {LoadOptions} opts options
* @returns {Promise<unknown>} result
*/
public static async run<T extends Command>(
this: new (argv: string[], config: Config) => T,
argv?: string[],
opts?: LoadOptions,
): Promise<ReturnType<T['run']>> {
if (!argv) argv = process.argv.slice(2)
// Handle the case when a file URL string is passed in such as 'import.meta.url'; covert to file path.
if (typeof opts === 'string' && opts.startsWith('file://')) {
opts = fileURLToPath(opts)
}
const config = await Config.load(opts || require.main?.filename || __dirname)
const cache = Cache.getInstance()
if (!cache.has('config')) cache.set('config', config)
const cmd = new this(argv, config)
if (!cmd.id) {
const id = cmd.constructor.name.toLowerCase()
cmd.id = id
cmd.ctor.id = id
}
return cmd._run<ReturnType<T['run']>>()
}
protected get ctor(): typeof Command {
return this.constructor as typeof Command
}
protected async catch(err: CommandError): Promise<any> {
process.exitCode = process.exitCode ?? err.exitCode ?? 1
if (this.jsonEnabled()) {
this.logJson(this.toErrorJson(err))
} else {
if (!err.message) throw err
try {
ux.action.stop(ux.colorize('bold', ux.colorize('red', '!')))
} catch {}
throw err
}
}
public error(input: Error | string, options: {code?: string; exit: false} & PrettyPrintableError): void
public error(input: Error | string, options?: {code?: string; exit?: number} & PrettyPrintableError): never
public error(
input: Error | string,
options: {code?: string; exit?: false | number} & PrettyPrintableError = {},
): void {
return Errors.error(input, options as any)
}
public exit(code = 0): never {
Errors.exit(code)
}
protected async finally(_: Error | undefined): Promise<any> {}
protected async init(): Promise<any> {
this.debug('init version: %s argv: %o', this.ctor._base, this.argv)
const g: any = global
g['http-call'] = g['http-call'] || {}
g['http-call']!.userAgent = this.config.userAgent
this.warnIfCommandDeprecated()
}
/**
* Determine if the command is being run with the --json flag in a command that supports it.
*
* @returns {boolean} true if the command supports json and the --json flag is present
*/
public jsonEnabled(): boolean {
// If the command doesn't support json, return false
if (!this.ctor.enableJsonFlag) return false
// If the CONTENT_TYPE env var is set to json, return true
if (this.config.scopedEnvVar?.('CONTENT_TYPE')?.toLowerCase() === 'json') return true
const passThroughIndex = this.argv.indexOf('--')
const jsonIndex = this.argv.indexOf('--json')
return passThroughIndex === -1
? // If '--' is not present, then check for `--json` in this.argv
jsonIndex > -1
: // If '--' is present, return true only the --json flag exists and is before the '--'
jsonIndex > -1 && jsonIndex < passThroughIndex
}
public log(message = '', ...args: any[]): void {
if (!this.jsonEnabled()) {
message = typeof message === 'string' ? message : inspect(message)
ux.stdout(message, ...args)
}
}
protected logJson(json: unknown): void {
ux.stdout(ux.colorizeJson(json, {pretty: true, theme: this.config.theme?.json}))
}
public logToStderr(message = '', ...args: any[]): void {
if (!this.jsonEnabled()) {
message = typeof message === 'string' ? message : inspect(message)
ux.stderr(message, ...args)
}
}
protected async parse<F extends FlagOutput, B extends FlagOutput, A extends ArgOutput>(
options?: Input<F, B, A>,
argv = this.argv,
): Promise<ParserOutput<F, B, A>> {
if (!options) options = this.ctor as Input<F, B, A>
const opts = {
context: this,
...options,
flags: aggregateFlags<F, B>(options.flags, options.baseFlags, options.enableJsonFlag),
}
const hookResult = await this.config.runHook('preparse', {argv: [...argv], options: opts})
// Since config.runHook will only run the hook for the root plugin, hookResult.successes will always have a length of 0 or 1
// But to be extra safe, we find the result that matches the root plugin.
const argvToParse = hookResult.successes?.length
? hookResult.successes.find((s) => s.plugin.root === Cache.getInstance().get('rootPlugin')?.root)?.result ?? argv
: argv
this.argv = [...argvToParse]
const results = await Parser.parse<F, B, A>(argvToParse, opts)
this.warnIfFlagDeprecated(results.flags ?? {})
return results
}
protected toErrorJson(err: unknown): any {
return {error: err}
}
protected toSuccessJson(result: unknown): any {
return result
}
public warn(input: Error | string): Error | string {
if (!this.jsonEnabled()) Errors.warn(input)
return input
}
protected warnIfCommandDeprecated(): void {
const [id] = normalizeArgv(this.config)
if (this.ctor.deprecateAliases && this.ctor.aliases.includes(id)) {
const cmdName = toConfiguredId(this.ctor.id, this.config)
const aliasName = toConfiguredId(id, this.config)
this.warn(formatCommandDeprecationWarning(aliasName, {to: cmdName}))
}
if (this.ctor.state === 'deprecated') {
const cmdName = toConfiguredId(this.ctor.id, this.config)
this.warn(formatCommandDeprecationWarning(cmdName, this.ctor.deprecationOptions))
}
}
protected warnIfFlagDeprecated(flags: Record<string, unknown>): void {
const allFlags = aggregateFlags(this.ctor.flags, this.ctor.baseFlags, this.ctor.enableJsonFlag)
for (const flag of Object.keys(flags)) {
const flagDef = allFlags[flag]
const deprecated = flagDef?.deprecated
if (deprecated) {
this.warn(formatFlagDeprecationWarning(flag, deprecated))
}
const deprecateAliases = flagDef?.deprecateAliases
if (deprecateAliases) {
const aliases = uniq([...(flagDef?.aliases ?? []), ...(flagDef?.charAliases ?? [])]).map((a) =>
a.length === 1 ? `-${a}` : `--${a}`,
)
if (aliases.length === 0) return
const foundAliases = aliases.filter((alias) => this.argv.some((a) => a.startsWith(alias)))
for (const alias of foundAliases) {
let preferredUsage = `--${flagDef?.name}`
if (flagDef?.char) {
preferredUsage += ` | -${flagDef?.char}`
}
this.warn(formatFlagDeprecationWarning(alias, {to: preferredUsage}))
}
}
}
}
protected async _run<T>(): Promise<T> {
let err: Error | undefined
let result: T | undefined
try {
// remove redirected env var to allow subsessions to run autoupdated client
this.removeEnvVar('REDIRECTED')
await this.init()
result = await this.run()
} catch (error: any) {
err = error
await this.catch(error)
} finally {
await this.finally(err)
}
if (result && this.jsonEnabled()) this.logJson(this.toSuccessJson(result))
return result as T
}
private removeEnvVar(envVar: string): void {
const keys: string[] = []
try {
keys.push(...this.config.scopedEnvVarKeys(envVar))
} catch {
keys.push(this.config.scopedEnvVarKey(envVar))
}
keys.map((key) => delete process.env[key])
}
}
export namespace Command {
/**
* The Command class exported by a command file.
*/
export type Class = typeof Command & {
id: string
run(argv?: string[], config?: LoadOptions): Promise<any>
}
/**
* A cached command that's had a `load` method attached to it.
*
* The `Plugin` class loads the commands from the manifest (if it exists) or requires and caches
* the commands directly from the commands directory inside the plugin. At this point the plugin
* is working with `Command.Cached`. It then appends a `load` method to each one. If the a command
* is executed then the `load` method is used to require the command class.
*/
export type Loadable = Cached & {
load(): Promise<Command.Class>
}
/**
* A cached version of the command. This is created by the cachedCommand utility and
* stored in the oclif.manifest.json.
*/
export type Cached = {
[key: string]: unknown
aliasPermutations?: string[] | undefined
aliases: string[]
args: {[name: string]: Arg.Cached}
deprecateAliases?: boolean | undefined
deprecationOptions?: Deprecation | undefined
description?: string | undefined
examples?: Example[] | undefined
flags: {[name: string]: Flag.Cached}
hasDynamicHelp?: boolean
hidden: boolean
hiddenAliases: string[]
id: string
isESM?: boolean | undefined
permutations?: string[] | undefined
pluginAlias?: string | undefined
pluginName?: string | undefined
pluginType?: string | undefined
relativePath?: string[] | undefined
state?: 'beta' | 'deprecated' | string | undefined
strict?: boolean | undefined
summary?: string | undefined
type?: string | undefined
usage?: string | string[] | undefined
}
export type Flag = IFlag<any>
export namespace Flag {
export type Cached = Omit<Flag, 'input' | 'parse'> &
(BooleanFlagProps | OptionFlagProps) & {hasDynamicHelp?: boolean | undefined}
export type Any = Cached | Flag
}
export type Arg = IArg<any>
export namespace Arg {
export type Cached = Omit<Arg, 'input' | 'parse'> & ArgProps
export type Any = Arg | Cached
}
export type Example =
| {
command: string
description: string
}
| string
}