Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/CAC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
}
}
}

Expand Down
65 changes: 65 additions & 0 deletions src/__test__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <baseUrl>', '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 <baseUrl>', '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 <baseUrl>', '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()

Expand Down