From a3a7850e65c16f3ac7991a2b8ec813d9de3404a4 Mon Sep 17 00:00:00 2001 From: Riceball LEE Date: Wed, 8 Jul 2020 10:02:00 +0800 Subject: [PATCH] feat: supports the default command fallback when command not found (resolved #277) --- src/config.ts | 6 +++++- .../typescript/src/commands/foo/bar/default-result.ts | 7 +++++++ test/fixtures/typescript/src/hooks/postrun.ts | 2 ++ test/typescript.test.ts | 7 +++++++ 4 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/typescript/src/commands/foo/bar/default-result.ts diff --git a/src/config.ts b/src/config.ts index 6d6f957f..8a3d3777 100644 --- a/src/config.ts +++ b/src/config.ts @@ -349,7 +349,11 @@ export class Config implements IConfig { async runCommand(id: string, argv: string[] = []) { debug('runCommand %s %o', id, argv) - const c = this.findCommand(id) + let c = this.findCommand(id) + if (!c) { + c = this.findCommand('default') + argv.unshift(id) + } if (!c) { await this.runHook('command_not_found', {id}) throw new CLIError(`command ${id} not found`) diff --git a/test/fixtures/typescript/src/commands/foo/bar/default-result.ts b/test/fixtures/typescript/src/commands/foo/bar/default-result.ts new file mode 100644 index 00000000..3157bd34 --- /dev/null +++ b/test/fixtures/typescript/src/commands/foo/bar/default-result.ts @@ -0,0 +1,7 @@ +export class Command { + static run() { + console.log('it works!') + } + + static aliases = ['default'] +} diff --git a/test/fixtures/typescript/src/hooks/postrun.ts b/test/fixtures/typescript/src/hooks/postrun.ts index be765f28..b756329f 100644 --- a/test/fixtures/typescript/src/hooks/postrun.ts +++ b/test/fixtures/typescript/src/hooks/postrun.ts @@ -2,5 +2,7 @@ export default function postrun(options: any) { console.log('running ts postrun hook') if (options.Command.id === 'foo:bar:test-result') { console.log(options.result) + } else if (options.Command.id === 'foo:bar:default-result') { + console.log(options.argv) } } diff --git a/test/typescript.test.ts b/test/typescript.test.ts index 42883e7a..4b17dec1 100644 --- a/test/typescript.test.ts +++ b/test/typescript.test.ts @@ -50,4 +50,11 @@ describe('typescript', () => { await (ctx.config.runHook as any)('init', {id: 'myid', argv: ['foo']}) expect(ctx.stdout).to.equal('running ts init hook\n') }) + + withConfig + .stdout() + .it('runs ts default command if command not found', async ctx => { + await ctx.config.runCommand('no-such-command') + expect(ctx.stdout).to.equal('running ts prerun hook\nit works!\nrunning ts postrun hook\n[ \'no-such-command\' ]\n') + }) })