From 8e7715262b5bece12ad638c4d813fcc9bba99698 Mon Sep 17 00:00:00 2001 From: Tianzhou Date: Sat, 15 Aug 2026 12:20:01 +0800 Subject: [PATCH] feat: add --version flag to cli (#542) --- cmd/root.go | 3 +++ cmd/root_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/cmd/root.go b/cmd/root.go index af24ac11..f8b52eb0 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -37,6 +37,7 @@ Commands: Use "pgschema [command] --help" for more information about a command.`, version.App(), GitCommit, platform(), BuildDate), + Version: version.App(), PersistentPreRun: func(cmd *cobra.Command, args []string) { setupLogger() globallogger.SetGlobal(logger, Debug) @@ -45,6 +46,8 @@ Use "pgschema [command] --help" for more information about a command.`, func init() { RootCmd.PersistentFlags().BoolVar(&Debug, "debug", false, "Enable debug logging") + // Print a clean, machine-parseable version line, e.g. "1.12.3" + RootCmd.SetVersionTemplate("{{.Version}}\n") RootCmd.CompletionOptions.DisableDefaultCmd = true RootCmd.AddCommand(dump.DumpCmd) RootCmd.AddCommand(plan.PlanCmd) diff --git a/cmd/root_test.go b/cmd/root_test.go index bc785c0e..9839ff36 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -4,6 +4,8 @@ import ( "bytes" "strings" "testing" + + "github.com/pgplex/pgschema/internal/version" ) func TestRootCommand(t *testing.T) { @@ -40,6 +42,31 @@ func TestRootCommandWithoutArgs(t *testing.T) { } } +func TestRootCommandVersionFlag(t *testing.T) { + // Reset flags that earlier tests may have set on the shared global RootCmd. + // pflag does not reset flag values between Parse calls, and cobra checks + // the help flag before the version flag. + if err := RootCmd.Flags().Set("help", "false"); err != nil { + t.Fatalf("failed to reset help flag: %v", err) + } + + var buf bytes.Buffer + RootCmd.SetOut(&buf) + RootCmd.SetErr(&buf) + RootCmd.SetArgs([]string{"--version"}) + + err := RootCmd.Execute() + if err != nil { + t.Errorf("root command with --version failed: %v", err) + } + + output := buf.String() + expected := version.App() + "\n" + if output != expected { + t.Errorf("expected version output %q, got %q", expected, output) + } +} + func TestRootCommandHasSubcommands(t *testing.T) { commands := RootCmd.Commands()