Skip to content

Commit

Permalink
fix(command): help callback not working with global options and comma…
Browse files Browse the repository at this point in the history
…nds (#149)
  • Loading branch information
c4spar committed Feb 8, 2021
1 parent 84fba89 commit 0972cc0
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
11 changes: 9 additions & 2 deletions command/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ interface IDefaultOption<O = any, A extends Array<any> = any> {

type ITypeMap = Map<string, IType>;

type IHelpHandler = (this: Command) => string;

// deno-lint-ignore no-explicit-any
export class Command<O = any, A extends Array<any> = any> {
private types: ITypeMap = new Map<string, IType>([
Expand Down Expand Up @@ -106,7 +108,7 @@ export class Command<O = any, A extends Array<any> = any> {
private hasDefaults = false;
private _versionOption?: IDefaultOption<O, A> | false;
private _helpOption?: IDefaultOption<O, A> | false;
private _help?: (this: Command<O, A>) => string;
private _help?: IHelpHandler;

/** Disable version option. */
public versionOption(enable: false): this;
Expand Down Expand Up @@ -1163,7 +1165,12 @@ export class Command<O = any, A extends Array<any> = any> {
/** Get generated help. */
public getHelp(): string {
this.registerDefaults();
return (this._help!)();
return this.getHelpHandler().call(this);
}

/** Get generated help. */
private getHelpHandler(): IHelpHandler {
return this._help ?? this._parent?.getHelpHandler() as IHelpHandler;
}

/*****************************************************************************
Expand Down
36 changes: 36 additions & 0 deletions command/test/command/help_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { assertEquals } from "../../../dev_deps.ts";
import { Command } from "../../command.ts";

Deno.test("command help handler", () => {
const cmd = new Command()
.throwErrors()
.name("main")
.help(function () {
return `help: ${this.getName()}`;
})
.command("foo")
.command("bar")
.reset();

assertEquals(cmd.getHelp(), "help: main");
assertEquals(cmd.getCommand("foo")?.getHelp(), "help: foo");
assertEquals(cmd.getCommand("bar")?.getHelp(), "help: bar");
});

Deno.test("command help handler override", () => {
const cmd = new Command()
.throwErrors()
.name("main")
.help(function () {
return `help: ${this.getName()}`;
})
.command("foo")
.help(`foo help`)
.command("bar")
.help(() => `bar help`)
.reset();

assertEquals(cmd.getHelp(), "help: main");
assertEquals(cmd.getCommand("foo")?.getHelp(), "foo help");
assertEquals(cmd.getCommand("bar")?.getHelp(), "bar help");
});

0 comments on commit 0972cc0

Please sign in to comment.