Skip to content

Commit 61654ad

Browse files
committed
Show version command in help and add short flag for displaying version -v
1 parent 57d326d commit 61654ad

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

.goreleaser.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ builds:
1717
ldflags:
1818
- "-s -w -X 'github.com/cnopslabs/oshiv/cmd.version={{.Version}}'"
1919

20-
2120
release:
2221
prerelease: auto
2322

cmd/version.go

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ var version = "unknown"
1212
var versionCmd = &cobra.Command{
1313
Use: "version",
1414
Short: "Print the version number of oshiv CLI",
15-
Long: `Print the version number of oshiv CLI`,
15+
Long: "Print the version number of oshiv CLI",
1616
Run: func(cmd *cobra.Command, args []string) {
1717
printVersion()
1818
},
@@ -26,14 +26,16 @@ func printVersion() {
2626
func init() {
2727
// Add the version command for long form (e.g., `oshiv version`)
2828
rootCmd.AddCommand(versionCmd)
29-
rootCmd.PersistentFlags().BoolP("version", "v", false, "Print the version number of oshiv CLI")
30-
rootCmd.Flags().BoolP("version", "v", false, "Print the short version number of oshiv CLI")
3129

32-
cobra.OnInitialize(checkVersionFlag)
33-
}
30+
// Register a global persistent flag to support short form (e.g., `oshiv -v`)
31+
rootCmd.PersistentFlags().BoolP("version", "v", false, "Print the version number of oshiv CLI")
3432

35-
func checkVersionFlag() {
36-
if versionFlag, _ := rootCmd.Flags().GetBool("version"); versionFlag {
37-
printVersion()
33+
// Override the persistent pre-run hook to check for the `-v` flag
34+
rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {
35+
if versionFlag, _ := cmd.Flags().GetBool("version"); versionFlag {
36+
printVersion()
37+
// Exit to avoid running another command if -v is passed
38+
cobra.CheckErr(nil)
39+
}
3840
}
3941
}

0 commit comments

Comments
 (0)