From 742b597f1ec9392f09b6af181d9c9cee7f680ba6 Mon Sep 17 00:00:00 2001 From: Chen Asraf Date: Sat, 2 Dec 2023 02:05:52 +0200 Subject: [PATCH] fix: support help option with early quit --- src/command.ts | 6 ++++++ test/help.test.ts | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/command.ts b/src/command.ts index 0044a2f..792e7c2 100644 --- a/src/command.ts +++ b/src/command.ts @@ -326,6 +326,12 @@ export class MassargCommand { if (option.defaultValue !== undefined && _a[option.name] === undefined) { _args[option.getOutputName() as keyof Args] = option.defaultValue as Args[keyof Args] } + if (this.helpConfig.bindOption && option.name === 'help') { + if (parseCommands) { + this.printHelp() + } + return + } } // parse options diff --git a/test/help.test.ts b/test/help.test.ts index f8f5aab..1e1523e 100644 --- a/test/help.test.ts +++ b/test/help.test.ts @@ -34,6 +34,15 @@ test('binds command', () => { expect(command.commands.find((o) => o.name === 'help')).toBeTruthy() }) +test('prints help from command', () => { + const command = massarg(opts).help({ + bindCommand: true, + }) + const log = jest.spyOn(console, 'log').mockImplementation(() => { }) + command.parse(['help']) + expect(log).toHaveBeenCalled() +}) + test('binds option', () => { const command = massarg(opts).help({ bindOption: true, @@ -43,13 +52,35 @@ test('binds option', () => { expect(command.options.find((o) => o.name === 'help')).toBeTruthy() }) +describe('prints help from option', () => { + test('when no main command', () => { + const command = massarg(opts).help({ + bindOption: true, + }) + const log = jest.spyOn(console, 'log').mockImplementation(() => { }) + command.parse(['--help']) + expect(log).toHaveBeenCalled() + }) + + test('when main command', () => { + const mainCmd = jest.fn() + const command2 = massarg(opts) + .help({ + bindOption: true, + }) + .main(mainCmd) + command2.parse(['--help']) + expect(mainCmd).not.toHaveBeenCalled() + }) +}) + test('help string', () => { const command = massarg(opts) expect(command.helpString()).toContain(`Usage:`) }) test('print help', () => { - const log = jest.spyOn(console, 'log').mockImplementation(() => {}) + const log = jest.spyOn(console, 'log').mockImplementation(() => { }) const command = massarg(opts) command.printHelp() expect(log).toHaveBeenCalled()