Skip to content

Commit ed7db5d

Browse files
committed
cleanup: rootcmd use the common way of creating a cobra cmd
1 parent 5364bd1 commit ed7db5d

File tree

2 files changed

+58
-61
lines changed

2 files changed

+58
-61
lines changed

cmd/root.go

+57-60
Original file line numberDiff line numberDiff line change
@@ -56,51 +56,26 @@ type RootFlags struct {
5656

5757
var flags = RootFlags{}
5858

59-
// rootCmd represents the base command when called without any subcommands
60-
var rootCmd = &cobra.Command{
61-
Use: "k3d",
62-
Short: "https://k3d.io/ -> Run k3s in Docker!",
63-
Long: `https://k3d.io/
59+
func NewCmdK3d() *cobra.Command {
60+
61+
// rootCmd represents the base command when called without any subcommands
62+
rootCmd := &cobra.Command{
63+
Use: "k3d",
64+
Short: "https://k3d.io/ -> Run k3s in Docker!",
65+
Long: `https://k3d.io/
6466
k3d is a wrapper CLI that helps you to easily create k3s clusters inside docker.
6567
Nodes of a k3d cluster are docker containers running a k3s image.
6668
All Nodes of a k3d cluster are part of the same docker network.`,
67-
Run: func(cmd *cobra.Command, args []string) {
68-
if flags.version {
69-
printVersion()
70-
} else {
71-
if err := cmd.Usage(); err != nil {
72-
log.Fatalln(err)
73-
}
74-
}
75-
},
76-
}
77-
78-
// Execute adds all child commands to the root command and sets flags appropriately.
79-
// This is called by main.main(). It only needs to happen once to the rootCmd.
80-
func Execute() {
81-
if len(os.Args) > 1 {
82-
parts := os.Args[1:]
83-
// Check if it's a built-in command, else try to execute it as a plugin
84-
if _, _, err := rootCmd.Find(parts); err != nil {
85-
pluginFound, err := cliutil.HandlePlugin(context.Background(), parts)
86-
if err != nil {
87-
log.Errorf("Failed to execute plugin '%+v'", parts)
88-
log.Fatalln(err)
89-
} else if pluginFound {
90-
os.Exit(0)
69+
Run: func(cmd *cobra.Command, args []string) {
70+
if flags.version {
71+
printVersion()
72+
} else {
73+
if err := cmd.Usage(); err != nil {
74+
log.Fatalln(err)
75+
}
9176
}
92-
}
93-
}
94-
if err := rootCmd.Execute(); err != nil {
95-
log.Fatalln(err)
77+
},
9678
}
97-
}
98-
99-
func GetRootCmd() *cobra.Command {
100-
return rootCmd
101-
}
102-
103-
func init() {
10479

10580
rootCmd.PersistentFlags().BoolVar(&flags.debugLogging, "verbose", false, "Enable verbose output (debug logging)")
10681
rootCmd.PersistentFlags().BoolVar(&flags.traceLogging, "trace", false, "Enable super verbose output (trace logging)")
@@ -110,7 +85,7 @@ func init() {
11085
rootCmd.Flags().BoolVar(&flags.version, "version", false, "Show k3d and default k3s version")
11186

11287
// add subcommands
113-
rootCmd.AddCommand(NewCmdCompletion())
88+
rootCmd.AddCommand(NewCmdCompletion(rootCmd))
11489
rootCmd.AddCommand(cluster.NewCmdCluster())
11590
rootCmd.AddCommand(kubeconfig.NewCmdKubeconfig())
11691
rootCmd.AddCommand(node.NewCmdNode())
@@ -147,6 +122,30 @@ func init() {
147122

148123
// Init
149124
cobra.OnInitialize(initLogging, initRuntime)
125+
126+
return rootCmd
127+
}
128+
129+
// Execute adds all child commands to the root command and sets flags appropriately.
130+
// This is called by main.main(). It only needs to happen once to the rootCmd.
131+
func Execute() {
132+
cmd := NewCmdK3d()
133+
if len(os.Args) > 1 {
134+
parts := os.Args[1:]
135+
// Check if it's a built-in command, else try to execute it as a plugin
136+
if _, _, err := cmd.Find(parts); err != nil {
137+
pluginFound, err := cliutil.HandlePlugin(context.Background(), parts)
138+
if err != nil {
139+
log.Errorf("Failed to execute plugin '%+v'", parts)
140+
log.Fatalln(err)
141+
} else if pluginFound {
142+
os.Exit(0)
143+
}
144+
}
145+
}
146+
if err := cmd.Execute(); err != nil {
147+
log.Fatalln(err)
148+
}
150149
}
151150

152151
// initLogging initializes the logger
@@ -216,29 +215,27 @@ func printVersion() {
216215
fmt.Printf("k3s version %s (default)\n", version.K3sVersion)
217216
}
218217

219-
func generateFishCompletion(writer io.Writer) error {
220-
return rootCmd.GenFishCompletion(writer, true)
221-
}
218+
// NewCmdCompletion creates a new completion command
219+
func NewCmdCompletion(rootCmd *cobra.Command) *cobra.Command {
222220

223-
// Completion
224-
var completionFunctions = map[string]func(io.Writer) error{
225-
"bash": rootCmd.GenBashCompletion,
226-
"zsh": func(writer io.Writer) error {
227-
if err := rootCmd.GenZshCompletion(writer); err != nil {
228-
return err
229-
}
221+
completionFunctions := map[string]func(io.Writer) error{
222+
"bash": rootCmd.GenBashCompletion,
223+
"zsh": func(writer io.Writer) error {
224+
if err := rootCmd.GenZshCompletion(writer); err != nil {
225+
return err
226+
}
230227

231-
fmt.Fprintf(writer, "\n# source completion file\ncompdef _k3d k3d\n")
228+
fmt.Fprintf(writer, "\n# source completion file\ncompdef _k3d k3d\n")
232229

233-
return nil
234-
},
235-
"psh": rootCmd.GenPowerShellCompletion,
236-
"powershell": rootCmd.GenPowerShellCompletionWithDesc,
237-
"fish": generateFishCompletion,
238-
}
230+
return nil
231+
},
232+
"psh": rootCmd.GenPowerShellCompletion,
233+
"powershell": rootCmd.GenPowerShellCompletionWithDesc,
234+
"fish": func(writer io.Writer) error {
235+
return rootCmd.GenFishCompletion(writer, true)
236+
},
237+
}
239238

240-
// NewCmdCompletion creates a new completion command
241-
func NewCmdCompletion() *cobra.Command {
242239
// create new cobra command
243240
cmd := &cobra.Command{
244241
Use: "completion SHELL",

docgen/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
)
99

1010
func main() {
11-
k3d := cmd.GetRootCmd()
11+
k3d := cmd.NewCmdK3d()
1212
k3d.DisableAutoGenTag = true
1313

1414
if err := doc.GenMarkdownTree(k3d, "../docs/usage/commands"); err != nil {

0 commit comments

Comments
 (0)