diff --git a/src/CAC.ts b/src/CAC.ts index 7a3df11..7aaf4d7 100644 --- a/src/CAC.ts +++ b/src/CAC.ts @@ -220,7 +220,11 @@ class CAC extends EventEmitter { this.unsetMatchedCommand() } - if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) { + if ( + this.options.version && + this.showVersionOnExit && + this.matchedCommandName == null + ) { this.outputVersion() run = false this.unsetMatchedCommand() @@ -285,8 +289,14 @@ class CAC extends EventEmitter { for (const cliOption of cliOptions) { if (!ignoreDefault && cliOption.config.default !== undefined) { - for (const name of cliOption.names) { - options[name] = cliOption.config.default + // apply default value only if none of the names was parsed + const parsedOptionNames = cliOption.names.filter( + (name: PropertyKey) => parsed[name] !== undefined + ) + if (parsedOptionNames.length === 0) { + for (const name of cliOption.names) { + options[name] = cliOption.config.default + } } } diff --git a/src/__test__/index.test.ts b/src/__test__/index.test.ts index 6cb8406..506ec17 100644 --- a/src/__test__/index.test.ts +++ b/src/__test__/index.test.ts @@ -81,6 +81,71 @@ test('double dashes', () => { expect(options['--']).toEqual(['npm', 'test']) }) +test('default value for option', () => { + const cli = cac() + + cli.option('-b, --base-url ', 'Set the instance URL', { + default: 'https://github.com', + }) + + const { options } = cli.parse(`node bin`.split(' ')) + + expect(options).toEqual({ + '--': [], + b: 'https://github.com', + baseUrl: 'https://github.com', + }) +}) + +test('default value for option names 1', () => { + const cli = cac() + + cli.option('-b, --base-url ', 'Set the instance URL', { + default: 'https://github.com', + }) + + let { options } = cli.parse(`node bin -b https://gitlab.com`.split(' ')) + + expect(options).toEqual({ + '--': [], + b: 'https://gitlab.com', + baseUrl: 'https://gitlab.com', + }) +}) + +test('default value for option names 2', () => { + const cli = cac() + + cli.option('-b, --base-url ', 'Set the instance URL', { + default: 'https://github.com', + }) + + let { options } = cli.parse( + `node bin --base-url https://gitlab.com`.split(' ') + ) + + expect(options).toEqual({ + '--': [], + baseUrl: 'https://gitlab.com', + }) +}) + +test('default value for option names 3', () => { + const cli = cac() + + cli.option('-s, --skip', 'Skip process', { + default: false, + }) + + const { options } = cli.parse(`node bin`.split(' ')) + + expect(options).toEqual({ + '--': [], + s: false, + skip: false, + }) +}) + test('default value for negated option', () => { const cli = cac()