Skip to content

Commit 0774ed9

Browse files
committed
fix: improve version and help flag handling with proper Cobra integration
1 parent b5c1032 commit 0774ed9

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

cmd/kdiff/main.go

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,7 @@ Prerequisites:
4848
• kubectl command-line tool
4949
• kubectl neat plugin (optional, for cleaner YAML output)
5050
• colordiff (optional, for colored output)`,
51-
Args: func(cmd *cobra.Command, args []string) error {
52-
// Allow version flag to bypass argument validation
53-
showVersion, _ := cmd.Flags().GetBool("version")
54-
if showVersion {
55-
fmt.Printf("kdiff %s (commit %s, built %s)\n", version, commit, date)
56-
os.Exit(0)
57-
}
58-
return cobra.ExactArgs(4)(cmd, args)
59-
},
51+
Args: cobra.ExactArgs(4),
6052
Run: func(cmd *cobra.Command, args []string) {
6153
opts.Namespace1 = args[0]
6254
opts.Resource1 = args[1]
@@ -70,12 +62,27 @@ Prerequisites:
7062
},
7163
}
7264

65+
var versionCmd = &cobra.Command{
66+
Use: "version",
67+
Short: "Print the version number",
68+
Run: func(cmd *cobra.Command, args []string) {
69+
fmt.Printf("kdiff %s (commit %s, built %s)\n", version, commit, date)
70+
},
71+
}
72+
7373
func init() {
7474
rootCmd.Flags().BoolVar(&opts.NoColor, "no-color", false, "disable colored output (useful for CI/CD pipelines)")
7575
rootCmd.Flags().BoolVar(&opts.NoNeat, "no-neat", false, "skip kubectl neat processing (show raw YAML)")
7676
rootCmd.Flags().StringVar(&opts.OutputFormat, "output", "unified", "output format: unified, context, side-by-side")
7777
rootCmd.Flags().BoolVar(&opts.Verbose, "verbose", false, "enable verbose logging for debugging")
78-
rootCmd.Flags().Bool("version", false, "show version information")
78+
79+
// Add version flag that shows version and exits
80+
rootCmd.Flags().BoolP("version", "v", false, "show version information")
81+
rootCmd.SetVersionTemplate("kdiff {{.Version}} (commit " + commit + ", built " + date + ")\n")
82+
rootCmd.Version = version
83+
84+
// Add version subcommand
85+
rootCmd.AddCommand(versionCmd)
7986
}
8087

8188
// Execute runs the root command - called from main.go

0 commit comments

Comments
 (0)