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

Commit

Permalink
fix: show help for -h
Browse files Browse the repository at this point in the history
  • Loading branch information
jdx committed Feb 1, 2018
1 parent d879c54 commit d4d4bb1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 13 deletions.
24 changes: 14 additions & 10 deletions src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,25 +32,29 @@ export default abstract class Command {
* instantiate and run the command
*/
static run: Config.ICommand['run'] = async function (this: Config.ICommand, argv = process.argv.slice(2), opts = {}) {
class HelpErr extends Error {code = 'EHELP'}
class VersionErr extends Error {code = 'EVERSION'}

let config
if (opts.config && Config.isIConfig(opts.config)) config = opts.config
else config = await Config.read({root: opts.root || parentModule!})

g.anycli.command = {}
let cmd!: Command
try {
let config
if (opts.config && Config.isIConfig(opts.config)) config = opts.config
else config = await Config.read({root: opts.root || parentModule!})
cmd = new this(argv, {...opts, config})
if (g.anycli.command.showVersion) {
if (g.anycli.command.showVersion) throw new VersionErr()
if (argv.includes('--help') || g.anycli.command.showHelp) throw new HelpErr()
return await cmd.run()
} catch (err) {
if (err instanceof VersionErr) {
cli.info(config.userAgent)
return
}
if (argv.includes('--help') || g.anycli.command.showHelp) {
} else if (err instanceof HelpErr || err.message.match(/Unexpected argument: -h/)) {
const Helper: typeof Help = require('@anycli/help').default
const help = new Helper(config)
help.command(this.convertToCached())
cli.info(help.command(this.convertToCached()))
return
}
return await cmd.run()
} else throw err
} finally {
if (cmd) await cmd.finally()
}
Expand Down
26 changes: 23 additions & 3 deletions test/command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,14 +232,34 @@ describe('command', () => {
describe('help', () => {
fancy
.stdout()
.it('shows help', async ctx => {
.it('--helpflag', async ctx => {
class CMD extends Command {
static flags = {help: flags.help()}
static flags = {helpflag: flags.help()}
options = parse(this.argv, CMD)
}
await CMD.run(['--help'])
await CMD.run(['--helpflag'])
expect(ctx.stdout).to.contain(`USAGE
$ @anycli/command [OPTIONS]`)
})

fancy
.stdout()
.it('--help', async ctx => {
class CMD extends Command {}
await CMD.run(['--help'])
expect(ctx.stdout).to.contain(`USAGE
$ @anycli/command`)
})

fancy
.stdout()
.it('-h', async ctx => {
class CMD extends Command {
options = parse(this.argv, CMD)
}
await CMD.run(['-h'])
expect(ctx.stdout).to.contain(`USAGE
$ @anycli/command`)
})
})
})

0 comments on commit d4d4bb1

Please sign in to comment.