Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make 'version' subcommand call 'root --version' #724

Closed
eine opened this issue Aug 8, 2018 · 4 comments
Closed

How to make 'version' subcommand call 'root --version' #724

eine opened this issue Aug 8, 2018 · 4 comments

Comments

@eine
Copy link

eine commented Aug 8, 2018

I am trying to add a version subcommand to rootCmd which will produce the same result as executing root --version.

The following code is properly compiled but it produces a runtime error:

package cmd
import "github.com/spf13/cobra"

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version number of Hugo",
	Long:  `All software has versions. This is Hugo's`,
	Run: func(cmd *cobra.Command, args []string) {
		rootCmd.Run(cmd, []string{"--version"})
	},
}

func init() {
	rootCmd.AddCommand(versionCmd)
}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x78ab9e]

So I looked in the sources of cobra and came up with:

package cmd

import (
	"text/template"
	"github.com/spf13/cobra"
)

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version number of Hugo",
	Long:  `All software has versions. This is Hugo's`,
	Run: func(cmd *cobra.Command, args []string) {
		t := template.New("version")
		template.Must(t.Parse(rootCmd.VersionTemplate()))
		err := t.Execute(rootCmd.OutOrStdout(), rootCmd)
		if err != nil {
			rootCmd.Println(err)
		}
	},
}

func init() {
	rootCmd.AddCommand(versionCmd)
}

This produces the desired result: root version and root --version produce the same output. However, I find the requirement to replicate the snippet strange.

Can anyone help me find the correct single instruction that allows to execute the root 'recursively'?

@github-actions
Copy link

github-actions bot commented Apr 9, 2020

This issue is being marked as stale due to a long period of inactivity

@eine
Copy link
Author

eine commented Apr 9, 2020

This is still relevant.

@marckhouzam
Copy link
Collaborator

@eine This works for me in a small test program:

var version = &cobra.Command{
	Use:   "version",
	Short: "the version",
	Run: func(cmd *cobra.Command, args []string) {
		root := cmd.Root()
		root.SetArgs([]string{"--version"})
		root.Execute()
	},
}

@johnSchnake
Copy link
Collaborator

Asked and answered. Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants