-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
216 lines (183 loc) · 6.03 KB
/
main.go
File metadata and controls
216 lines (183 loc) · 6.03 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"context"
"fmt"
"os"
"runtime"
"strings"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/stackvista/stackstate-cli/cmd"
stscobra "github.com/stackvista/stackstate-cli/internal/cobra"
"github.com/stackvista/stackstate-cli/internal/common"
"github.com/stackvista/stackstate-cli/internal/di"
"github.com/stackvista/stackstate-cli/internal/editor"
"github.com/stackvista/stackstate-cli/internal/printer"
"github.com/stackvista/stackstate-cli/pkg/pflags"
"github.com/stackvista/stackstate-cli/pkg/term"
"github.com/stackvista/stackstate-cli/static_info"
)
const MinSTSVersion = "5.0.0"
func main() {
ctx := log.Logger.WithContext(context.Background())
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
cli := &di.Deps{
Version: static_info.Version,
Commit: static_info.Commit,
BuildDate: static_info.BuildDate,
Editor: editor.NewEditor(),
Clock: pflags.NewFixedTimeClock(),
}
cmd := cmd.STSCommand(cli)
os.Exit(execute(ctx, cli, cmd))
}
func execute(ctx context.Context, cli *di.Deps, sts *cobra.Command) common.ExitCode {
common.AddPersistentFlags(sts)
stscobra.AddRequiredFlagsToUseString(sts)
setUsageTemplates(sts)
setMinSupportedSTSVersion(sts, MinSTSVersion)
throwErrorOnUnknownSubCommand(sts, cli)
sts.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
return common.NewCLIArgParseError(err)
})
if cli.Printer == nil {
cli.Printer = printer.NewPrinter()
}
zerolog.SetGlobalLevel(zerolog.Disabled)
sts.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
return PreRunCommand(cli, cmd)
}
// shush, cobra... we take care of this ourselves
sts.SilenceErrors = true
sts.SilenceUsage = true
if cmd, err := sts.ExecuteContextC(ctx); err != nil {
var showUsage bool
var exitCode int
switch v := err.(type) {
case common.CLIError:
exitCode = v.ExitCode()
showUsage = v.ShowUsage()
default:
showUsage = true
}
if exitCode == common.OkExitCode {
exitCode = common.CommandFailedRequirementExitCode
}
if cli.IsJson() {
cli.Printer.PrintErrJson(err)
} else {
cli.Printer.PrintErr(err)
if showUsage {
cli.Printer.PrintLn(strings.TrimRight(cmd.UsageString(), "\n"))
}
}
return exitCode
} else {
return common.OkExitCode
}
}
func PreRunCommand(cli *di.Deps, cmd *cobra.Command) error {
if err := stscobra.ValidateMutexFlags(cmd); err != nil {
return common.NewCLIArgParseError(err)
}
configPath, err := cmd.Flags().GetString(common.ConfigFlag)
if err != nil {
return err
}
cli.ConfigPath = configPath
noColorFlag, _ := cmd.Flags().GetBool(common.NoColorFlag)
if noColorFlag || !term.SupportsColor() {
cli.NoColor = true
}
output, err := pflags.GetEnum(cmd.Flags(), common.OutputFlag)
if err != nil {
return err
}
cli.Output = common.ToOutput(output)
if cli.Output == common.JSONOutput {
cli.NoColor = true
}
verbosity, _ := cmd.Flags().GetCount(common.VerboseFlag)
cli.IsVerBose = verbosity > 0
switch verbosity {
case 0:
// Nothing to do
case 1:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case 2: //nolint:mnd
zerolog.SetGlobalLevel(zerolog.DebugLevel)
default:
zerolog.SetGlobalLevel(zerolog.TraceLevel)
}
log.Info().
Strs("args", os.Args).
Str("os", runtime.GOOS).
Str("version", cli.Version).
Str("commit", cli.Commit).
Str("date", cli.BuildDate).
Msg("starting CLI")
cli.Printer.SetUseColor(!cli.NoColor)
return nil
}
// For commands that have sub-commands we can show a simpler usage template.
func setUsageTemplates(sts *cobra.Command) {
cobraCommand := cobra.Command{}
fullTemplate := "{{if .Version}}Minimum supported SUSE Observability version: {{.Version}}\n\n{{end}}" + cobraCommand.UsageTemplate()
subCommandTemplate := `Usage:{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
versionTemplate := "minimum supported SUSE Observability version: {{.Version}}"
sts.SetVersionTemplate(versionTemplate)
stscobra.ForAllCmd(sts, func(c *cobra.Command) {
c.SetUsageTemplate(fullTemplate)
})
sts.SetUsageTemplate(subCommandTemplate)
for _, c := range sts.Commands() {
if c.HasSubCommands() {
c.SetUsageTemplate(subCommandTemplate)
// We need to set verb command to the full template,
// because otherwise they will inherit the simple template from their noun command parent.
for _, verbCommands := range c.Commands() {
verbCommands.SetUsageTemplate(fullTemplate)
}
}
}
}
// Sets the minimum supported StackState version (unless specified
func setMinSupportedSTSVersion(sts *cobra.Command, version string) {
stscobra.ForAllCmd(sts, func(c *cobra.Command) {
if c.Version == "" {
c.Version = version
}
})
}
// By default Cobra does not provide an error when a wrong sub-command is entered.
// We got some customer feedback that this was missing.
func throwErrorOnUnknownSubCommand(sts *cobra.Command, cli *di.Deps) {
for _, c := range sts.Commands() {
if c.HasSubCommands() {
c.RunE = func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
// this behaves just like the root. Not calling a noun command with a verb sub-command
// simply prints the full usage string prefixed with the long description
cli.Printer.PrintLn(cmd.Long + "\n\n" + strings.TrimRight(cmd.UsageString(), "\n"))
return nil
}
for _, sub := range cmd.Commands() {
if args[0] == sub.Name() {
return nil
}
}
return common.NewCLIArgParseError(fmt.Errorf("unknown sub-command \"%s\" for \"%s\"", args[0], cmd.Name()))
}
}
}
}