diff --git a/cmd/root.go b/cmd/root.go index 6bf12711d89..57a64325deb 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -48,8 +48,12 @@ func newRootCommand(gs *state.GlobalState) *rootCommand { SilenceUsage: true, SilenceErrors: true, PersistentPreRunE: c.persistentPreRunE, + Version: versionString(), } + rootCmd.SetVersionTemplate( + `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "v%s\n" .Version}}`, + ) rootCmd.PersistentFlags().AddFlagSet(rootCmdPersistentFlagSet(gs)) rootCmd.SetArgs(gs.CmdArgs[1:]) rootCmd.SetOut(gs.Stdout) diff --git a/cmd/tests/cmd_run_test.go b/cmd/tests/cmd_run_test.go index bbc372690ea..1c874963bf5 100644 --- a/cmd/tests/cmd_run_test.go +++ b/cmd/tests/cmd_run_test.go @@ -37,15 +37,25 @@ import ( func TestVersion(t *testing.T) { t.Parallel() + tests := map[string]struct { + args string + }{ + "flag": {"--version"}, + "subcommand": {"version"}, + } + ts := NewGlobalTestState(t) - ts.CmdArgs = []string{"k6", "version"} - cmd.ExecuteWithGlobalState(ts.GlobalState) - stdout := ts.Stdout.String() - assert.Contains(t, stdout, "k6 v"+consts.Version) - assert.Contains(t, stdout, runtime.Version()) - assert.Contains(t, stdout, runtime.GOOS) - assert.Contains(t, stdout, runtime.GOARCH) + for _, tc := range tests { + ts.CmdArgs = []string{"k6", tc.args} + cmd.ExecuteWithGlobalState(ts.GlobalState) + + stdout := ts.Stdout.String() + assert.Contains(t, stdout, "k6 v"+consts.Version) + assert.Contains(t, stdout, runtime.Version()) + assert.Contains(t, stdout, runtime.GOOS) + assert.Contains(t, stdout, runtime.GOARCH) + } assert.Empty(t, ts.Stderr.Bytes()) assert.Empty(t, ts.LoggerHook.Drain()) diff --git a/cmd/version.go b/cmd/version.go index 9a9e71d1891..e5f977c48a1 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -10,23 +10,30 @@ import ( "go.k6.io/k6/lib/consts" ) +func versionString() string { + v := consts.FullVersion() + + if exts := ext.GetAll(); len(exts) > 0 { + extsDesc := make([]string, 0, len(exts)) + for _, e := range exts { + extsDesc = append(extsDesc, fmt.Sprintf(" %s", e.String())) + } + v += fmt.Sprintf("\nExtensions:\n%s\n", + strings.Join(extsDesc, "\n")) + } + return v +} + func getCmdVersion(gs *state.GlobalState) *cobra.Command { // versionCmd represents the version command. return &cobra.Command{ Use: "version", Short: "Show application version", Long: `Show the application version and exit.`, - Run: func(_ *cobra.Command, _ []string) { - printToStdout(gs, fmt.Sprintf("k6 v%s\n", consts.FullVersion())) - - if exts := ext.GetAll(); len(exts) > 0 { - extsDesc := make([]string, 0, len(exts)) - for _, e := range exts { - extsDesc = append(extsDesc, fmt.Sprintf(" %s", e.String())) - } - printToStdout(gs, fmt.Sprintf("Extensions:\n%s\n", - strings.Join(extsDesc, "\n"))) - } + Run: func(cmd *cobra.Command, _ []string) { + root := cmd.Root() + root.SetArgs([]string{"--version"}) + _ = root.Execute() }, } }