From f5053a566538d2692383387c31f8d2145f222d42 Mon Sep 17 00:00:00 2001 From: Randall Wood <297232+rhwood@users.noreply.github.com> Date: Tue, 16 Oct 2018 21:33:13 -0400 Subject: [PATCH] feat: Allow a default to be specified for boolean flags (#41) This allows the use of boolean flag symantecs where the default behavior for the application is as if `--flag` had been passed, and `--no-flag` is not the default behavoir. --- src/flags.ts | 4 ++++ src/parse.ts | 6 +++--- test/parse.test.ts | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/flags.ts b/src/flags.ts index 25a90f9..522c664 100644 --- a/src/flags.ts +++ b/src/flags.ts @@ -22,6 +22,10 @@ export type IFlagBase = { export type IBooleanFlag = IFlagBase & { type: 'boolean' allowNo: boolean + /** + * specifying a default of false is the same not specifying a default + */ + default?: boolean | ((context: DefaultContext) => boolean) } export type IOptionFlag = IFlagBase & { diff --git a/src/parse.ts b/src/parse.ts index 910f2dc..85a5b76 100644 --- a/src/parse.ts +++ b/src/parse.ts @@ -185,12 +185,12 @@ export class Parser { + 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})