-
Notifications
You must be signed in to change notification settings - Fork 237
/
root.go
269 lines (219 loc) · 7.73 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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package cmd
import (
"fmt"
"os"
"github.com/CircleCI-Public/circleci-cli/data"
"github.com/CircleCI-Public/circleci-cli/md_docs"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/spf13/cobra"
)
var defaultEndpoint = "graphql-unstable"
var defaultHost = "https://circleci.com"
// rootCmd is used internally and global to the package but not exported
// therefore we can use it in other commands, like `usage`
// it should be set once when Execute is first called
var rootCmd *cobra.Command
// rootOptions is used internally for preparing CLI and passed to sub-commands
var rootOptions *settings.Config
// rootTokenFromFlag stores the value passed in through the flag --token
var rootTokenFromFlag string
// PackageManager defines the package manager which was used to install the CLI.
// You can override this value using -X flag to the compiler ldflags.
var PackageManager = "source"
// Execute adds all child commands to rootCmd and
// sets flags appropriately. This function is called
// by main.main(). It only needs to happen once to
// the rootCmd.
func Execute() {
command := MakeCommands()
if err := command.Execute(); err != nil {
os.Exit(-1)
}
}
func hasAnnotations(cmd *cobra.Command) bool {
return len(cmd.Annotations) > 0
}
var usageTemplate = `
Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if (HasAnnotations .)}}
{{$cmd := .}}
Args:
{{range (PositionalArgs .)}} {{(FormatPositionalArg $cmd .)}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{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}}
`
// MakeCommands creates the top level commands
func MakeCommands() *cobra.Command {
rootOptions = &settings.Config{
Debug: false,
Token: "",
Host: defaultHost,
Endpoint: defaultEndpoint,
GitHubAPI: "https://api.github.com/",
}
if err := rootOptions.Load(); err != nil {
panic(err)
}
loaded, err := data.LoadData()
if err != nil {
panic(err)
}
rootOptions.Data = loaded
rootCmd = &cobra.Command{
Use: "circleci",
Long: rootHelpLong(rootOptions),
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
return rootCmdPreRun(rootOptions)
},
}
// For supporting "Args" in command usage help
cobra.AddTemplateFunc("HasAnnotations", hasAnnotations)
cobra.AddTemplateFunc("PositionalArgs", md_docs.PositionalArgs)
cobra.AddTemplateFunc("FormatPositionalArg", md_docs.FormatPositionalArg)
rootCmd.SetUsageTemplate(usageTemplate)
rootCmd.DisableAutoGenTag = true
rootCmd.AddCommand(newOpenCommand())
rootCmd.AddCommand(newTestsCommand())
rootCmd.AddCommand(newContextCommand(rootOptions))
rootCmd.AddCommand(newQueryCommand(rootOptions))
rootCmd.AddCommand(newConfigCommand(rootOptions))
rootCmd.AddCommand(newOrbCommand(rootOptions))
rootCmd.AddCommand(newLocalCommand(rootOptions))
rootCmd.AddCommand(newBuildCommand(rootOptions))
rootCmd.AddCommand(newVersionCommand(rootOptions))
rootCmd.AddCommand(newDiagnosticCommand(rootOptions))
rootCmd.AddCommand(newSetupCommand(rootOptions))
if isUpdateIncluded(PackageManager) {
rootCmd.AddCommand(newUpdateCommand(rootOptions))
} else {
rootCmd.AddCommand(newDisabledCommand(rootOptions, "update"))
}
rootCmd.AddCommand(newNamespaceCommand(rootOptions))
rootCmd.AddCommand(newUsageCommand(rootOptions))
rootCmd.AddCommand(newStepCommand(rootOptions))
rootCmd.AddCommand(newSwitchCommand(rootOptions))
rootCmd.PersistentFlags().BoolVar(&rootOptions.Debug,
"debug", rootOptions.Debug, "Enable debug logging.")
rootCmd.PersistentFlags().StringVar(&rootTokenFromFlag,
"token", "", "your token for using CircleCI, also CIRCLECI_CLI_TOKEN")
rootCmd.PersistentFlags().StringVar(&rootOptions.Host,
"host", rootOptions.Host, "URL to your CircleCI host, also CIRCLECI_CLI_HOST")
rootCmd.PersistentFlags().StringVar(&rootOptions.Endpoint,
"endpoint", rootOptions.Endpoint, "URI to your CircleCI GraphQL API endpoint")
rootCmd.PersistentFlags().StringVar(&rootOptions.GitHubAPI, "github-api", "https://api.github.com/", "Change the default endpoint to GitHub API for retrieving updates")
if err := rootCmd.PersistentFlags().MarkHidden("github-api"); err != nil {
panic(err)
}
rootCmd.PersistentFlags().BoolVar(&rootOptions.SkipUpdateCheck, "skip-update-check", false, "Skip the check for updates check run before every command")
if err := rootCmd.PersistentFlags().MarkHidden("skip-update-check"); err != nil {
panic(err)
}
if err := rootCmd.PersistentFlags().MarkHidden("debug"); err != nil {
panic(err)
}
if err := rootCmd.PersistentFlags().MarkHidden("endpoint"); err != nil {
panic(err)
}
// Cobra has a peculiar default behaviour:
// https://github.com/spf13/cobra/issues/340
// If you expose a command with `RunE`, and return an error from your
// command, then Cobra will print the error message, followed by the usage
// information for the command. This makes it really difficult to see what's
// gone wrong. It usually prints a one line error message followed by 15
// lines of usage information.
// This flag disables that behaviour, so that if a comment fails, it prints
// just the error message.
rootCmd.SilenceUsage = true
setFlagErrorFuncAndValidateArgs(rootCmd)
return rootCmd
}
func init() {
cobra.OnInitialize(prepare)
}
func prepare() {
if rootTokenFromFlag != "" {
rootOptions.Token = rootTokenFromFlag
}
}
func rootCmdPreRun(rootOptions *settings.Config) error {
return checkForUpdates(rootOptions)
}
func validateToken(rootOptions *settings.Config) error {
var (
err error
url string
)
if rootOptions.Host == defaultHost {
url = rootOptions.Data.Links.NewAPIToken
} else {
url = fmt.Sprintf("%s/account/api", rootOptions.Host)
}
if rootOptions.Token == "token" || rootOptions.Token == "" {
err = fmt.Errorf(`please set a token with 'circleci setup'
You can create a new personal API token here:
%s`, url)
}
return err
}
func setFlagErrorFunc(cmd *cobra.Command, err error) error {
if e := cmd.Help(); e != nil {
return e
}
fmt.Println("")
return err
}
func setFlagErrorFuncAndValidateArgs(command *cobra.Command) {
visitAll(command, func(cmd *cobra.Command) {
cmd.SetFlagErrorFunc(setFlagErrorFunc)
if cmd.Args == nil {
return
}
cmdArgs := cmd.Args
cmd.Args = func(cccmd *cobra.Command, args []string) error {
if err := cmdArgs(cccmd, args); err != nil {
if e := cccmd.Help(); e != nil {
return e
}
fmt.Println("")
return err
}
return nil
}
})
}
func visitAll(root *cobra.Command, fn func(*cobra.Command)) {
for _, cmd := range root.Commands() {
visitAll(cmd, fn)
}
fn(root)
}
func isUpdateIncluded(packageManager string) bool {
switch packageManager {
case "homebrew":
return false
default:
return true
}
}
func rootHelpLong(config *settings.Config) string {
long := `Use CircleCI from the command line.
This project is the seed for CircleCI's new command-line application.`
// We should only print this for cloud users
if config.Host != defaultHost {
return long
}
return fmt.Sprintf(`%s
For more help, see the documentation here: %s`, long, config.Data.Links.CLIDocs)
}