Skip to content

Commit

Permalink
change VersionFlag to a BeforeReset hook
Browse files Browse the repository at this point in the history
  • Loading branch information
pyqlsa authored and alecthomas committed Jul 28, 2022
1 parent a05a0c2 commit f48da24
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
26 changes: 25 additions & 1 deletion kong_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1544,7 +1544,8 @@ func TestPassthroughCmdOnlyStringArgs(t *testing.T) {

func TestHelpShouldStillWork(t *testing.T) {
type CLI struct {
Dir string `type:"existingdir" default:"missing-dir"`
Dir string `type:"existingdir" default:"missing-dir"`
File string `type:"existingfile" default:"testdata/missing.txt"`
}
var cli CLI
w := &strings.Builder{}
Expand All @@ -1563,6 +1564,29 @@ func TestHelpShouldStillWork(t *testing.T) {
assert.Error(t, err)
}

func TestVersionFlagShouldStillWork(t *testing.T) {
type CLI struct {
Dir string `type:"existingdir" default:"missing-dir"`
File string `type:"existingfile" default:"testdata/missing.txt"`
Version kong.VersionFlag
}
var cli CLI
w := &strings.Builder{}
k := mustNew(t, &cli, kong.Writers(w, w))
rc := -1 // init nonzero to help assert help hook was called
k.Exit = func(i int) {
rc = i
}
_, err := k.Parse([]string{"--version"})
t.Log(w.String())
// checking return code validates the help hook was called
assert.Zero(t, rc)
// allow for error propagation from other validation (only for the
// sake of this test, due to the exit function not actually exiting the
// program; errors will not propagate in the real world).
assert.Error(t, err)
}

func TestSliceDecoderHelpfulErrorMsg(t *testing.T) {
tests := []struct {
name string
Expand Down
4 changes: 2 additions & 2 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ func (c ConfigFlag) BeforeResolve(kong *Kong, ctx *Context, trace *Path) error {
// VersionFlag is a flag type that can be used to display a version number, stored in the "version" variable.
type VersionFlag bool

// BeforeApply writes the version variable and terminates with a 0 exit status.
func (v VersionFlag) BeforeApply(app *Kong, vars Vars) error {
// BeforeReset writes the version variable and terminates with a 0 exit status.
func (v VersionFlag) BeforeReset(app *Kong, vars Vars) error {
fmt.Fprintln(app.Stdout, vars["version"])
app.Exit(0)
return nil
Expand Down

0 comments on commit f48da24

Please sign in to comment.