Skip to content

Commit

Permalink
feat: improve the instantiation of global flags (#445)
Browse files Browse the repository at this point in the history
* feat: improve the instantiation of global flags

* chore: code review

* Update src/command.ts

Co-authored-by: Rodrigo Espinosa de los Monteros <1084688+RodEsp@users.noreply.github.com>

* chore: satisfy linter

Co-authored-by: Rodrigo Espinosa de los Monteros <1084688+RodEsp@users.noreply.github.com>
  • Loading branch information
mdonnalley and RodEsp committed Jul 20, 2022
1 parent b645bdc commit d264535
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/command.ts
Expand Up @@ -96,7 +96,16 @@ export default abstract class Command {

static parserOptions = {}

static enableJsonFlag = false
static _enableJsonFlag = false

static get enableJsonFlag(): boolean {
return this._enableJsonFlag
}

static set enableJsonFlag(value: boolean) {
this._enableJsonFlag = value
if (value) this.globalFlags = jsonFlag
}

// eslint-disable-next-line valid-jsdoc
/**
Expand Down Expand Up @@ -126,9 +135,8 @@ export default abstract class Command {
}

static set globalFlags(flags: Interfaces.FlagInput<any>) {
this._globalFlags = this.enableJsonFlag ?
Object.assign({}, jsonFlag, this.globalFlags, flags) :
Object.assign({}, this.globalFlags, flags)
this._globalFlags = Object.assign({}, this.globalFlags, flags)
this.flags = this.globalFlags
}

/** A hash of flags for the command */
Expand All @@ -139,7 +147,6 @@ export default abstract class Command {
}

static set flags(flags: Interfaces.FlagInput<any>) {
this.globalFlags = {}
this._flags = Object.assign({}, this.globalFlags, flags)
}

Expand Down Expand Up @@ -239,7 +246,7 @@ export default abstract class Command {
if (!options) options = this.constructor as any
const opts = {context: this, ...options}
// the spread operator doesn't work with getters so we have to manually add it here
opts.flags = options?.flags
opts.flags = Object.assign({}, options?.flags, options?.globalFlags)
return Parser.parse(argv, opts)
}

Expand Down
1 change: 1 addition & 0 deletions src/interfaces/parser.ts
Expand Up @@ -164,6 +164,7 @@ export type Flag<T> = BooleanFlag<T> | OptionFlag<T>

export type Input<TFlags extends FlagOutput> = {
flags?: FlagInput<TFlags>;
globalFlags?: FlagInput<TFlags>;
args?: ArgInput;
strict?: boolean;
context?: any;
Expand Down

0 comments on commit d264535

Please sign in to comment.