diff --git a/main.go b/main.go index edea357..a5043d0 100644 --- a/main.go +++ b/main.go @@ -394,8 +394,19 @@ func newRootCmd() *cobra.Command { }, } - var rootCmd = &cobra.Command{Use: "scharf", Long: asciiLogo, Version: cliVersion()} - rootCmd.SetVersionTemplate("{{.Version}}\n") + var rootCmd = &cobra.Command{ + Use: "scharf", + Long: asciiLogo, + Run: func(cmd *cobra.Command, args []string) { + showVersion, _ := cmd.Flags().GetBool("version") + if showVersion { + fmt.Fprintln(cmd.OutOrStdout(), cliVersion()) + return + } + _ = cmd.Help() + }, + } + rootCmd.Flags().BoolP("version", "V", false, "Print Scharf version information") rootCmd.AddCommand(cmdLookup, cmdFind, cmdList, cmdAudit, cmdAutoFix, cmdUpgrade, cmdUpgradeAllSHA, cmdVersion) return rootCmd diff --git a/main_test.go b/main_test.go index 3895d26..b07f1f9 100644 --- a/main_test.go +++ b/main_test.go @@ -40,7 +40,8 @@ func TestUpgradeSHAWithoutFromVersionShowsUsage(t *testing.T) { } func TestVersionInfoExposedOnCLI(t *testing.T) { - for _, args := range [][]string{{"--version"}, {"version"}} { + var expected string + for _, args := range [][]string{{"--version"}, {"version"}, {"-V"}} { stdout, stderr, err := executeRoot(args...) if err != nil { t.Fatalf("unexpected error for %v: %v (stderr: %s)", args, err, stderr) @@ -49,5 +50,15 @@ func TestVersionInfoExposedOnCLI(t *testing.T) { if !strings.Contains(stdout, "commit") || !strings.Contains(stdout, "built") { t.Fatalf("stdout = %q; want version details including commit and build metadata", stdout) } + if !strings.HasPrefix(stdout, "version: ") { + t.Fatalf("stdout = %q; want direct version output without Cobra prefix", stdout) + } + if expected == "" { + expected = stdout + continue + } + if stdout != expected { + t.Fatalf("stdout for %v = %q; want %q", args, stdout, expected) + } } }