-
Notifications
You must be signed in to change notification settings - Fork 3
/
root.go
80 lines (66 loc) · 2.28 KB
/
root.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
77
78
79
80
package cmd
import (
"fmt"
"os/exec"
"github.com/spf13/cobra"
config "github.com/get-bridge/muss/config"
)
// CommandBuilder is a function that takes the project config as an argument
// and returns a cobra command.
type CommandBuilder func(*config.ProjectConfig) *cobra.Command
var cmdBuilders = make([]CommandBuilder, 0)
// AddCommandBuilder takes the provided function and adds it to the list of
// commands that will be added to the root command when it is built.
func AddCommandBuilder(f CommandBuilder) {
cmdBuilders = append(cmdBuilders, f)
}
// NewRootCommand takes a config value and returns a new root command.
func NewRootCommand(cfg *config.ProjectConfig) *cobra.Command {
cmd := &cobra.Command{
Use: "muss",
Short: "Configure and run project services",
// Root command just shows help (which shows subcommands).
// SilenceUsage and Errors so that we don't print excessively when dc exits non-zero.
SilenceErrors: true,
SilenceUsage: true,
}
for _, f := range cmdBuilders {
cmd.AddCommand(f(cfg))
}
return cmd
}
// Execute loads the config and runs the root command with the provided arguments.
func Execute(args []string) int {
// We'll inspect the error later when we have command context.
cfg, _ := config.NewConfigFromDefaultFile()
cmd := NewRootCommand(cfg)
return ExecuteRoot(cmd, args)
}
// ExecuteRoot executes the passed root command with the provided args.
// This simplifies testing.
func ExecuteRoot(rootCmd *cobra.Command, args []string) int {
rootCmd.SetArgs(args)
if err := rootCmd.Execute(); err != nil {
// Propagate errors from command delegation.
if exitErr, ok := err.(*exec.ExitError); ok {
return exitErr.ExitCode()
}
stderr := rootCmd.ErrOrStderr()
// Print information about other errors.
fmt.Fprintln(stderr, "Error: ", err.Error())
// An alternative to marking it a QuietError is to call
// rootCmd.SetFlagErrorFunc and wrap flag errors with a flagError type.
if _, ok := err.(*QuietError); !ok {
// Print usage if it's a flag error
cmd, _, findErr := rootCmd.Find(args)
// If subcmd isn't found, print root command usage
if findErr != nil {
cmd = rootCmd
}
fmt.Fprintln(stderr, "") // Print blank line between "Error:" and "Usage:".
fmt.Fprintln(stderr, cmd.UsageString())
}
return 1
}
return 0
}