Skip to content
This repository has been archived by the owner on Aug 22, 2023. It is now read-only.

Allow a default to be specified for boolean flags #41

Merged
merged 1 commit into from
Oct 17, 2018
Merged
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
4 changes: 4 additions & 0 deletions src/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export type IFlagBase<T, I> = {
export type IBooleanFlag<T> = IFlagBase<T, boolean> & {
type: 'boolean'
allowNo: boolean
/**
* specifying a default of false is the same not specifying a default
*/
default?: boolean | ((context: DefaultContext<boolean>) => boolean)
}

export type IOptionFlag<T> = IFlagBase<T, string> & {
Expand Down
6 changes: 3 additions & 3 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,12 @@ export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']
}
for (const k of Object.keys(this.input.flags)) {
const flag = this.input.flags[k]
if (flags[k] || flag.type !== 'option') continue
if (flag.env) {
if (flags[k]) continue
if (flag.type === 'option' && flag.env) {
let input = process.env[flag.env]
if (input) flags[k] = flag.parse(input, this.context)
}
if (!flags[k] && flag.default) {
if (!(k in flags) && flag.default !== undefined) {
if (typeof flag.default === 'function') {
flags[k] = flag.default({options: flag, flags, ...this.context})
} else {
Expand Down
47 changes: 47 additions & 0 deletions test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,53 @@ See more help with --help`)
})
})

describe('boolean defaults', () => {
it('default is true', () => {
const out = parse([], {
flags: {
color: flags.boolean({default: true})
}
})
expect(out).to.deep.include({flags: {color: true}})
})

it('default is false', () => {
const out = parse([], {
flags: {
color: flags.boolean({default: false})
}
})
expect(out).to.deep.include({flags: {color: false}})
})

it('default as function', () => {
const out = parse([], {
flags: {
color: flags.boolean({default: () => true})
}
})
expect(out).to.deep.include({flags: {color: true}})
})

it('overridden true default', () => {
const out = parse(['--no-color'], {
flags: {
color: flags.boolean({allowNo: true, default: true})
}
})
expect(out).to.deep.include({flags: {color: false}})
})

it('overridden false default', () => {
const out = parse(['--color'], {
flags: {
color: flags.boolean({default: false})
}
})
expect(out).to.deep.include({flags: {color: true}})
})
})

describe('custom option', () => {
it('can pass parse fn', () => {
const foo = flags.option({char: 'f', parse: () => 100})
Expand Down