From b4b1df31f0defc03e8e20b51973dbcb4a6c462b1 Mon Sep 17 00:00:00 2001 From: Arjun mahishi Date: Fri, 7 Apr 2023 14:03:34 +0530 Subject: [PATCH] Handle --version just like --help 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 --- app.go | 4 ++++ app_test.go | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/app.go b/app.go index 3818010..43d816b 100644 --- a/app.go +++ b/app.go @@ -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 } } diff --git a/app_test.go b/app_test.go index 3e35fe5..27c95e5 100644 --- a/app_test.go +++ b/app_test.go @@ -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) +}