From b39c22eb5c35e818765580c01b64ea35317d2e1b Mon Sep 17 00:00:00 2001 From: John Gee Date: Sun, 28 Feb 2021 15:57:09 +1300 Subject: [PATCH 1/2] Add globalOpts --- index.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/index.js b/index.js index ec9887905..84947dba5 100644 --- a/index.js +++ b/index.js @@ -1719,6 +1719,19 @@ class Command extends EventEmitter { return this._optionValues; }; + /** + * Return an object containing global options as key-value pairs + * + * @return {Object} + */ + globalOpts() { + const result = {}; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + Object.assign(result, parentCmd.opts()); + } + return result; + } + /** * Internal bottleneck for handling of parsing errors. * From 105d630caccf9b5ec5458927f2d50084b64a8e14 Mon Sep 17 00:00:00 2001 From: John Gee Date: Sun, 28 Feb 2021 17:51:22 +1300 Subject: [PATCH 2/2] Add TypeScript types for globalOpts --- index.js | 2 +- typings/index.d.ts | 5 +++++ typings/index.test-d.ts | 6 ++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 84947dba5..3eff059d1 100644 --- a/index.js +++ b/index.js @@ -1720,7 +1720,7 @@ class Command extends EventEmitter { }; /** - * Return an object containing global options as key-value pairs + * Return an object containing global options as key-value pairs, from parent command(s). * * @return {Object} */ diff --git a/typings/index.d.ts b/typings/index.d.ts index 6fe954083..6ec368878 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -481,6 +481,11 @@ declare namespace commander { */ opts(): OptionValues; + /** + * Return an object containing global options as key-value pairs, from parent command(s). + */ + globalOpts(): OptionValues; + /** * Set the description. * diff --git a/typings/index.test-d.ts b/typings/index.test-d.ts index 061cf4bb6..e68ac0da6 100644 --- a/typings/index.test-d.ts +++ b/typings/index.test-d.ts @@ -171,6 +171,12 @@ expectType(opts); expectType(opts.foo); expectType(opts['bar']); +// globalOpts +const globalOpts = program.globalOpts(); +expectType(globalOpts); +expectType(globalOpts.foo); +expectType(globalOpts['bar']); + // description expectType(program.description('my description')); expectType(program.description());