Skip to content

Commit

Permalink
Merge pull request cli#5703 from cli/version-flag-fix
Browse files Browse the repository at this point in the history
Fix --version flag printing to stdout
  • Loading branch information
mislav authored May 24, 2022
2 parents 31bee2e + cfaca91 commit ec12d27
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
11 changes: 11 additions & 0 deletions pkg/cmd/root/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,17 @@ func isRootCmd(command *cobra.Command) bool {
}

func rootHelpFunc(f *cmdutil.Factory, command *cobra.Command, args []string) {
if isRootCmd(command) {
if versionVal, err := command.Flags().GetBool("version"); err == nil && versionVal {
fmt.Fprint(f.IOStreams.Out, command.Annotations["versionInfo"])
return
} else if err != nil {
fmt.Fprintln(f.IOStreams.ErrOut, err)
hasFailed = true
return
}
}

cs := f.IOStreams.ColorScheme()

if isRootCmd(command.Parent()) && len(args) >= 2 && args[1] != "--help" && args[1] != "-h" {
Expand Down
7 changes: 2 additions & 5 deletions pkg/cmd/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,14 @@ func NewCmdRoot(f *cmdutil.Factory, version, buildDate string) *cobra.Command {
"help:feedback": heredoc.Doc(`
Open an issue using 'gh issue create -R github.com/cli/cli'
`),
"versionInfo": versionCmd.Format(version, buildDate),
},
}

cmd.SetOut(f.IOStreams.ErrOut) // command usage summary and deprecation warnings
cmd.SetErr(f.IOStreams.ErrOut) // error messages

cmd.Flags().Bool("version", false, "Show gh version")
cmd.PersistentFlags().Bool("help", false, "Show help for command")
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
rootHelpFunc(f, c, args)
Expand All @@ -68,11 +70,6 @@ func NewCmdRoot(f *cmdutil.Factory, version, buildDate string) *cobra.Command {
})
cmd.SetFlagErrorFunc(rootFlagErrorFunc)

formattedVersion := versionCmd.Format(version, buildDate)
cmd.SetVersionTemplate(formattedVersion)
cmd.Version = formattedVersion
cmd.Flags().Bool("version", false, "Show gh version")

// Child commands
cmd.AddCommand(versionCmd.NewCmdVersion(f, version, buildDate))
cmd.AddCommand(actionsCmd.NewCmdActions(f))
Expand Down
2 changes: 1 addition & 1 deletion pkg/cmd/version/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func NewCmdVersion(f *cmdutil.Factory, version, buildDate string) *cobra.Command
Use: "version",
Hidden: true,
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprint(f.IOStreams.Out, Format(version, buildDate))
fmt.Fprint(f.IOStreams.Out, cmd.Root().Annotations["versionInfo"])
},
}

Expand Down

0 comments on commit ec12d27

Please sign in to comment.