Skip to content

Commit

Permalink
Handle --version just like --help
Browse files Browse the repository at this point in the history
when the version flag is passed, the application should do nothing but
print the version and exit. But currently, the pre-action for the
version flag got executed AFTER the default for all the other flags were
set.

Setting defaults involves validation like checking for file's
existence etc. These validation are not necessary when the --version
flag is passed. This commit fixes that
  • Loading branch information
arjunmahishi authored and alecthomas committed Apr 7, 2023
1 parent 649b5a2 commit b4b1df3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,10 @@ func (a *Application) setDefaults(context *ParseContext) error {
if flag.name == "help" {
return nil
}

if flag.name == "version" {
return nil
}
flagElements[flag.name] = element
}
}
Expand Down
11 changes: 11 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,14 @@ func TestCmdValidation(t *testing.T) {
_, err = c.Parse([]string{"cmd", "--a", "A"})
assert.NoError(t, err)
}

func TestVersion(t *testing.T) {
c := newTestApp()
c.Flag("config", "path to config file").Default("config.yaml").ExistingFile()
c.Version("1.0.0")

// the pre-action for version should be executed without running validation
// for ExistingFile
_, err := c.Parse([]string{"--version"})
assert.NoError(t, err)
}

0 comments on commit b4b1df3

Please sign in to comment.