-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_root_exec_test.go
76 lines (67 loc) · 2.41 KB
/
example_root_exec_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package cobrax_test
import (
"bufio"
"fmt"
"runtime/debug"
"github.com/spf13/cobra"
"github.com/zepatrik/cobrax"
)
// NewRootCmd creates a new root greetme command. This function takes care of all the flag initialization and registering all subcommands.
func NewRootCmd() *cobra.Command {
var errorExitCode int
cmd := &cobra.Command{
Use: "greetme",
Short: "This is a friendly program to greet you.",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Fprintln(cmd.ErrOrStderr(), "Hello, what is your name?")
name, err := bufio.NewReader(cmd.InOrStdin()).ReadString('\n')
if err != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "Error reading name: %v", err)
return cobrax.WithExitCode(cobrax.FailSilently(cmd), errorExitCode)
}
fmt.Fprintf(cmd.ErrOrStderr(), "Hello %s\n", name)
return nil
},
}
cmd.Flags().IntVar(&errorExitCode, "exit-code", 1, "Exit code to return on error")
cmd.AddCommand(NewVersionCmd(""))
return cmd
}
// NewVersionCmd returns a new version subcommand. This could be in a totally different package, and reused by multiple projects.
// The version can be passed as a string. If the version is empty, the version embedded by [runtime/debug.ReadBuildInfo] is used.
func NewVersionCmd(version string) *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Short: "Prints the version of this program.",
RunE: func(cmd *cobra.Command, args []string) error {
if version == "" {
bi, ok := debug.ReadBuildInfo()
if !ok {
fmt.Fprintln(cmd.ErrOrStderr(), "No version information available.")
return cobrax.FailSilently(cmd)
}
version = bi.Main.Version
}
fmt.Fprintf(cmd.OutOrStdout(), "Version: %s", version)
return nil
},
}
cmd.AddCommand(newVersionSubCmd())
return cmd
}
// NewVersionSubCmd returns a new version subcommand. This would be in the same package as the version command.
// It could depend on the version command as a parent, e.g. to access persistent flags, and would therefore not be exported.
func newVersionSubCmd() *cobra.Command {
return &cobra.Command{
Use: "deeply-nested",
Short: "This commmand is an example for a deeply nested subcommand.",
RunE: func(cmd *cobra.Command, args []string) error {
// Do stuff
return nil
},
}
}
// ExampleExecuteRoot shows how to use the helpers for the [spf13/cobra.Command.RunE] and main function.
func Example_executeRoot() {
cobrax.ExecuteRootCommand(NewRootCmd())
}