-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathmain.go
More file actions
356 lines (324 loc) · 13.7 KB
/
Copy pathmain.go
File metadata and controls
356 lines (324 loc) · 13.7 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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package main
import (
"bytes"
"errors"
"fmt"
"os"
"strings"
"github.com/alecthomas/kong"
"github.com/buildkite/cli/v3/cmd/agent"
"github.com/buildkite/cli/v3/cmd/api"
"github.com/buildkite/cli/v3/cmd/artifacts"
"github.com/buildkite/cli/v3/cmd/auth"
"github.com/buildkite/cli/v3/cmd/browse"
"github.com/buildkite/cli/v3/cmd/build"
"github.com/buildkite/cli/v3/cmd/cluster"
bkConfig "github.com/buildkite/cli/v3/cmd/config"
"github.com/buildkite/cli/v3/cmd/configure"
bkInit "github.com/buildkite/cli/v3/cmd/init"
"github.com/buildkite/cli/v3/cmd/job"
"github.com/buildkite/cli/v3/cmd/maintainer"
"github.com/buildkite/cli/v3/cmd/organization"
"github.com/buildkite/cli/v3/cmd/pipeline"
"github.com/buildkite/cli/v3/cmd/pkg"
"github.com/buildkite/cli/v3/cmd/preflight"
"github.com/buildkite/cli/v3/cmd/queue"
"github.com/buildkite/cli/v3/cmd/secret"
"github.com/buildkite/cli/v3/cmd/skill"
updatePkg "github.com/buildkite/cli/v3/cmd/update"
"github.com/buildkite/cli/v3/cmd/use"
"github.com/buildkite/cli/v3/cmd/user"
versionPkg "github.com/buildkite/cli/v3/cmd/version"
"github.com/buildkite/cli/v3/cmd/whoami"
"github.com/buildkite/cli/v3/internal/cli"
"github.com/buildkite/cli/v3/internal/config"
bkErrors "github.com/buildkite/cli/v3/internal/errors"
"github.com/buildkite/cli/v3/pkg/analytics"
"github.com/buildkite/cli/v3/pkg/cmd/factory"
)
// Kong CLI structure, with base commands defined as additional commands are defined in their respective files
type CLI struct {
// Global flags
Yes bool `help:"Skip all confirmation prompts" short:"y"`
NoInput bool `help:"Disable all interactive prompts" name:"no-input"`
Quiet bool `help:"Suppress progress output" short:"q"`
NoPager bool `help:"Disable pager for text output" name:"no-pager"`
Debug bool `help:"Enable debug output for REST API calls"`
Agent AgentCmd `cmd:"" help:"Manage agents"`
Api ApiCmd `cmd:"" help:"Interact with the Buildkite API"`
Artifacts ArtifactsCmd `cmd:"" help:"Manage pipeline build artifacts"`
Auth AuthCmd `cmd:"" help:"Authenticate with Buildkite"`
Browse BrowseCmd `cmd:"" help:"Open Buildkite resources in a web browser"`
Build BuildCmd `cmd:"" help:"Manage pipeline builds"`
Cluster ClusterCmd `cmd:"" help:"Manage organization clusters"`
Maintainer MaintainerCmd `cmd:"" help:"Manage cluster maintainers"`
Queue QueueCmd `cmd:"" help:"Manage cluster queues"`
Secret SecretCmd `cmd:"" help:"Manage cluster secrets"`
Skill SkillCmd `cmd:"" help:"Manage Buildkite skills for AI coding agents"`
Config bkConfig.ConfigCmd `cmd:"" help:"Manage CLI configuration"`
Configure ConfigureCmd `cmd:"" help:"Configure Buildkite API token" hidden:""`
Init bkInit.InitCmd `cmd:"" help:"Initialize a pipeline.yaml file"`
Job JobCmd `cmd:"" help:"Manage jobs within a build"`
Organization OrganizationCmd `cmd:"" help:"Manage organizations" aliases:"org"`
Pipeline PipelineCmd `cmd:"" help:"Manage pipelines"`
Package PackageCmd `cmd:"" help:"Manage packages"`
Preflight PreflightCmd `cmd:"" help:"Run a build against a snapshot of the local working tree (experimental)"`
Use use.UseCmd `cmd:"" help:"Select an organization" hidden:""`
User UserCmd `cmd:"" help:"Invite users to the organization"`
Update updatePkg.UpdateCmd `cmd:"" help:"Update the installed bk CLI or print update instructions"`
Version VersionCmd `cmd:"" help:"Print the version of the CLI being used"`
Whoami whoami.WhoAmICmd `cmd:"" help:"Print the current user and organization" hidden:""`
}
type (
VersionCmd struct {
versionPkg.VersionCmd `cmd:"" help:"Print the version of the CLI being used"`
}
AuthCmd struct {
Login auth.LoginCmd `cmd:"" help:"Login to Buildkite using OAuth or an API token"`
Logout auth.LogoutCmd `cmd:"" help:"Logout and remove stored credentials"`
Status auth.StatusCmd `cmd:"" help:"Print the current user auth status"`
Switch auth.SwitchCmd `cmd:"" help:"Switch to a different organization" aliases:"use"`
Token auth.TokenCmd `cmd:"" help:"Print the stored API token for the current organization"`
}
AgentCmd struct {
Install agent.InstallCmd `cmd:"" help:"Install the buildkite-agent binary locally."`
Run agent.RunCmd `cmd:"" help:"Run an ephemeral buildkite-agent locally."`
Pause agent.PauseCmd `cmd:"" help:"Pause a Buildkite agent."`
List agent.ListCmd `cmd:"" help:"List agents." alias:"ls"`
Resume agent.ResumeCmd `cmd:"" help:"Resume a Buildkite agent."`
Stop agent.StopCmd `cmd:"" help:"Stop Buildkite agents."`
View agent.ViewCmd `cmd:"" help:"View details of an agent."`
}
ApiCmd struct {
api.ApiCmd `cmd:"" help:"Interact with the Buildkite API"`
}
BrowseCmd struct {
browse.BrowseCmd `cmd:"" help:"Open Buildkite resources in a web browser"`
}
ArtifactsCmd struct {
Download artifacts.DownloadCmd `cmd:"" help:"Download artifacts from a build."`
List artifacts.ListCmd `cmd:"" help:"List artifacts for a build or a job in a build." aliases:"ls"`
}
BuildCmd struct {
Create build.CreateCmd `cmd:"" aliases:"new" help:"Create a new build."` // Aliasing "new" because we've renamed this to "create", but we need to support backwards compatibility
Cancel build.CancelCmd `cmd:"" help:"Cancel a build."`
View build.ViewCmd `cmd:"" help:"View build information."`
List build.ListCmd `cmd:"" help:"List builds." aliases:"ls"`
Download build.DownloadCmd `cmd:"" help:"Download resources for a build."`
Rebuild build.RebuildCmd `cmd:"" help:"Rebuild a build."`
Watch build.WatchCmd `cmd:"" help:"Watch a build's progress in real-time."`
}
ClusterCmd struct {
List cluster.ListCmd `cmd:"" help:"List clusters." aliases:"ls"`
View cluster.ViewCmd `cmd:"" help:"View cluster information."`
Create cluster.CreateCmd `cmd:"" help:"Create a new cluster."`
Update cluster.UpdateCmd `cmd:"" help:"Update a cluster."`
Delete cluster.DeleteCmd `cmd:"" help:"Delete a cluster." aliases:"rm"`
}
ConfigureCmd struct {
configure.ConfigureCmd `cmd:"" help:"Configure Buildkite API token"`
}
JobCmd struct {
Cancel job.CancelCmd `cmd:"" help:"Cancel a job."`
List job.ListCmd `cmd:"" help:"List jobs." aliases:"ls"`
Log job.LogCmd `cmd:"" help:"Get logs for a job."`
Reprioritize job.ReprioritizeCmd `cmd:"" help:"Reprioritize a job." aliases:"priority"`
Retry job.RetryCmd `cmd:"" help:"Retry a job."`
Unblock job.UnblockCmd `cmd:"" help:"Unblock a job."`
}
MaintainerCmd struct {
List maintainer.ListCmd `cmd:"" help:"List cluster maintainers." aliases:"ls"`
Create maintainer.CreateCmd `cmd:"" help:"Create a cluster maintainer."`
Delete maintainer.DeleteCmd `cmd:"" help:"Delete a cluster maintainer." aliases:"rm"`
}
OrganizationCmd struct {
List organization.ListCmd `cmd:"" help:"List configured organizations." aliases:"ls"`
}
PackageCmd struct {
Push pkg.PushCmd `cmd:"" help:"Push a new package to a Buildkite registry"`
}
PipelineCmd struct {
Copy pipeline.CopyCmd `cmd:"" help:"Copy an existing pipeline." aliases:"cp"`
Create pipeline.CreateCmd `cmd:"" help:"Create a new pipeline."`
List pipeline.ListCmd `cmd:"" help:"List pipelines." aliases:"ls"`
Convert pipeline.ConvertCmd `cmd:"" help:"Convert a CI/CD pipeline configuration to Buildkite format." aliases:"migrate"`
Validate pipeline.ValidateCmd `cmd:"" help:"Validate a pipeline YAML file."`
View pipeline.ViewCmd `cmd:"" help:"View a pipeline."`
}
PreflightCmd struct {
Run preflight.RunCmd `cmd:"" default:"withargs" help:"Run a build against a snapshot of the local working tree (experimental)"`
Cleanup preflight.CleanupCmd `cmd:"" help:"Clean up completed preflight branches (experimental)"`
}
QueueCmd struct {
List queue.ListCmd `cmd:"" help:"List cluster queues." aliases:"ls"`
View queue.ViewCmd `cmd:"" help:"View a cluster queue."`
Create queue.CreateCmd `cmd:"" help:"Create a new cluster queue."`
Update queue.UpdateCmd `cmd:"" help:"Update a cluster queue."`
Delete queue.DeleteCmd `cmd:"" help:"Delete a cluster queue." aliases:"rm"`
Pause queue.PauseCmd `cmd:"" help:"Pause dispatch for a cluster queue."`
Resume queue.ResumeCmd `cmd:"" help:"Resume dispatch for a cluster queue."`
}
SecretCmd struct {
List secret.ListCmd `cmd:"" help:"List secrets for a cluster." aliases:"ls"`
Get secret.GetCmd `cmd:"" help:"View a cluster secret."`
Create secret.CreateCmd `cmd:"" help:"Create a new cluster secret."`
Update secret.UpdateCmd `cmd:"" help:"Update a cluster secret."`
Delete secret.DeleteCmd `cmd:"" help:"Delete a cluster secret." aliases:"rm"`
}
SkillCmd struct {
Add skill.AddCmd `cmd:"" help:"Install a Buildkite skill."`
Update skill.UpdateCmd `cmd:"" help:"Update an installed Buildkite skill."`
Delete skill.DeleteCmd `cmd:"" help:"Delete an installed Buildkite skill." aliases:"rm"`
}
UserCmd struct {
Invite user.InviteCmd `cmd:"" help:"Invite users to your organization."`
}
)
func (c PreflightCmd) Help() string {
return preflight.HelpText()
}
func handleError(err error) {
bkErrors.NewHandler().Handle(err)
}
func newKongParser(cli *CLI, options ...kong.Option) (*kong.Kong, error) {
baseOptions := []kong.Option{
kong.Name("bk"),
kong.Description("Work with Buildkite from the command line."),
kong.Vars{
// Empty default allows commands to fall back to config value
"output_default_format": "",
"skill_repo": "buildkite/skills",
"skill_branch": "main",
},
}
baseOptions = append(baseOptions, options...)
return kong.New(cli, baseOptions...)
}
func renderHelp(args []string) (string, error) {
cli := &CLI{}
var stdout, stderr bytes.Buffer
parser, err := newKongParser(
cli,
kong.Writers(&stdout, &stderr),
kong.Exit(func(int) {}),
)
if err != nil {
return "", err
}
applyExperiments(parser, config.New(nil, nil))
if _, err := parser.Parse(args); err != nil {
if stdout.Len() > 0 {
return stdout.String(), nil
}
return "", err
}
return stdout.String(), nil
}
func renderPreflightHelp() (string, error) {
parentHelp, err := renderHelp([]string{"preflight", "--help"})
if err != nil {
return "", err
}
runHelp, err := renderHelp([]string{"preflight", "run", "--help"})
if err != nil {
return "", err
}
parentFlagsStart := strings.Index(parentHelp, "\nFlags:\n")
parentCommandsStart := strings.Index(parentHelp, "\nCommands:\n")
runFlagsStart := strings.Index(runHelp, "\nFlags:\n")
if parentFlagsStart == -1 || parentCommandsStart == -1 || runFlagsStart == -1 {
return parentHelp, nil
}
return parentHelp[:parentFlagsStart] + runHelp[runFlagsStart:] + parentHelp[parentCommandsStart:], nil
}
func isPreflightHelpRequest(args []string) bool {
switch {
case len(args) == 2 && args[0] == "preflight" && (args[1] == "--help" || args[1] == "-h"):
return true
case len(args) == 2 && args[0] == "help" && args[1] == "preflight":
return true
default:
return false
}
}
// applyExperiments toggles visibility of experimental commands based on config.
func applyExperiments(parser *kong.Kong, conf *config.Config) {
for _, node := range parser.Model.Children {
switch node.Name {
case config.ExperimentPreflight:
node.Hidden = !conf.HasExperiment(config.ExperimentPreflight)
}
}
}
func main() {
os.Exit(run())
}
func run() int {
// Handle no-args and "help" cases by showing help instead of error
// This addresses the Kong limitation described in https://github.com/alecthomas/kong/issues/33
if len(os.Args) <= 1 || (len(os.Args) == 2 && os.Args[1] == "help") {
cli := &CLI{}
parser, err := newKongParser(cli)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 1
}
applyExperiments(parser, config.New(nil, nil))
_, _ = parser.Parse([]string{"--help"})
return 0
}
// Handle --version and -V flags at the top level
if len(os.Args) == 2 && (os.Args[1] == "--version" || os.Args[1] == "-V") {
fmt.Print(versionPkg.Format(versionPkg.Version))
return 0
}
args := os.Args[1:]
if isPreflightHelpRequest(args) {
help, err := renderPreflightHelp()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 1
}
fmt.Print(help)
return 0
}
cliInstance := &CLI{}
conf := config.New(nil, nil)
// Must run before kong dispatches: bk auth login builds its keyring
// before factory.New() does.
factory.ApplyCredentialStoreFromConfig(conf)
tracker := analytics.Init("dev", conf.TelemetryEnabled())
defer tracker.Close()
tracker.SetOrg(conf.OrganizationSlug())
parser, err := newKongParser(cliInstance)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 1
}
applyExperiments(parser, conf)
ctx, err := parser.Parse(args)
if err != nil {
tracker.TrackCommand("unknown command", args, nil)
var parseErr *kong.ParseError
if errors.As(err, &parseErr) && !strings.Contains(err.Error(), "did you mean") {
_ = parseErr.Context.PrintUsage(false)
fmt.Fprintln(os.Stderr)
}
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 1
}
tracker.TrackCommand(analytics.ParseSubcommand(ctx.Command()), args, nil)
globals := cli.Globals{
Yes: cliInstance.Yes,
NoInput: cliInstance.NoInput,
Quiet: cliInstance.Quiet,
NoPager: cliInstance.NoPager,
Debug: cliInstance.Debug,
}
ctx.BindTo(cli.GlobalFlags(globals), (*cli.GlobalFlags)(nil))
if err := ctx.Run(cliInstance); err != nil {
handleError(err)
return 1
}
return 0
}