chore: refactor to directly create Client in Command Handlers (#19760)

Refactors the CLI to create the `*codersdk.Client` in the handlers. This is groundwork for changing the `rootCmd.InitClient()` to use the new `ClientOption`​s.

It also improves variable locality, scoping the Client to the handler. This makes misuse less likely and reduces the memory allocations to just the command being executed, rather than allocating a Client for every command regardless of whether it is executed.
This commit is contained in:
Spike Curtis
2025-09-22 17:14:07 +04:00
committed by GitHub
parent 12496830d6
commit 606ae897b7
67 changed files with 605 additions and 431 deletions
+17 -8
View File
@@ -77,10 +77,12 @@ func (r *RootCmd) externalWorkspaceCreate() *serpent.Command {
cmd := r.Create(opts)
cmd.Use = "create [workspace]"
cmd.Short = "Create a new external workspace"
cmd.Middleware = serpent.Chain(
cmd.Middleware,
serpent.RequireNArgs(1),
)
newMiddlewares := []serpent.MiddlewareFunc{}
if cmd.Middleware != nil {
newMiddlewares = append(newMiddlewares, cmd.Middleware)
}
newMiddlewares = append(newMiddlewares, serpent.RequireNArgs(1))
cmd.Middleware = serpent.Chain(newMiddlewares...)
for i := range cmd.Options {
if cmd.Options[i].Flag == "template" {
@@ -93,7 +95,6 @@ func (r *RootCmd) externalWorkspaceCreate() *serpent.Command {
// externalWorkspaceAgentInstructions prints the instructions for an external agent.
func (r *RootCmd) externalWorkspaceAgentInstructions() *serpent.Command {
client := new(codersdk.Client)
formatter := cliui.NewOutputFormatter(
cliui.ChangeFormatterData(cliui.TextFormat(), func(data any) (any, error) {
agent, ok := data.(externalAgent)
@@ -109,8 +110,13 @@ func (r *RootCmd) externalWorkspaceAgentInstructions() *serpent.Command {
cmd := &serpent.Command{
Use: "agent-instructions [user/]workspace[.agent]",
Short: "Get the instructions for an external agent",
Middleware: serpent.Chain(r.InitClient(client), serpent.RequireNArgs(1)),
Middleware: serpent.Chain(serpent.RequireNArgs(1)),
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}
workspace, workspaceAgent, _, err := agpl.GetWorkspaceAndAgent(inv.Context(), inv, client, false, inv.Args[0])
if err != nil {
return xerrors.Errorf("find workspace and agent: %w", err)
@@ -162,7 +168,6 @@ func (r *RootCmd) externalWorkspaceList() *serpent.Command {
cliui.JSONFormat(),
)
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Annotations: map[string]string{
"workspaces": "",
@@ -172,9 +177,13 @@ func (r *RootCmd) externalWorkspaceList() *serpent.Command {
Aliases: []string{"ls"},
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}
baseFilter := filter.Filter()
if baseFilter.FilterQuery == "" {
+7 -6
View File
@@ -36,15 +36,16 @@ func (r *RootCmd) featuresList() *serpent.Command {
columns []string
outputFormat string
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "list",
Aliases: []string{"ls"},
Middleware: serpent.Chain(
r.InitClient(client),
),
Use: "list",
Aliases: []string{"ls"},
Middleware: serpent.Chain(),
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}
entitlements, err := client.Entitlements(inv.Context())
var apiError *codersdk.Error
if errors.As(err, &apiError) && apiError.StatusCode() == http.StatusNotFound {
+4 -2
View File
@@ -19,16 +19,18 @@ func (r *RootCmd) groupCreate() *serpent.Command {
orgContext = agpl.NewOrganizationContext()
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "create <name>",
Short: "Create a user group",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
+4 -3
View File
@@ -7,26 +7,27 @@ import (
agpl "github.com/coder/coder/v2/cli"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/pretty"
"github.com/coder/serpent"
)
func (r *RootCmd) groupDelete() *serpent.Command {
orgContext := agpl.NewOrganizationContext()
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "delete <name>",
Short: "Delete a user group",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
var (
ctx = inv.Context()
groupName = inv.Args[0]
)
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
+4 -2
View File
@@ -24,19 +24,21 @@ func (r *RootCmd) groupEdit() *serpent.Command {
rmUsers []string
orgContext = agpl.NewOrganizationContext()
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "edit <name>",
Short: "Edit a user group",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
var (
ctx = inv.Context()
groupName = inv.Args[0]
)
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
+4 -2
View File
@@ -20,16 +20,18 @@ func (r *RootCmd) groupList() *serpent.Command {
)
orgContext := agpl.NewOrganizationContext()
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "list",
Short: "List user groups",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
+15 -7
View File
@@ -42,16 +42,18 @@ func (r *RootCmd) licenseAdd() *serpent.Command {
license string
debug bool
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "add [-f file | -l license]",
Short: "Add license to Coder deployment",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
var err error
client, err := r.InitClient(inv)
if err != nil {
return err
}
switch {
case filename != "" && license != "":
return xerrors.New("only one of (--file, --license) may be specified")
@@ -137,16 +139,19 @@ func validJWT(s string) error {
func (r *RootCmd) licensesList() *serpent.Command {
formatter := cliutil.NewLicenseFormatter()
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "list",
Short: "List licenses (including expired)",
Aliases: []string{"ls"},
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}
licenses, err := client.Licenses(inv.Context())
if err != nil {
return err
@@ -170,16 +175,19 @@ func (r *RootCmd) licensesList() *serpent.Command {
}
func (r *RootCmd) licenseDelete() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "delete <id>",
Short: "Delete license by ID",
Aliases: []string{"del"},
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}
id, err := strconv.ParseInt(inv.Args[0], 10, 32)
if err != nil {
return xerrors.Errorf("license ID must be an integer: %s", inv.Args[0])
+12 -6
View File
@@ -38,16 +38,19 @@ func (r *RootCmd) prebuilds() *serpent.Command {
}
func (r *RootCmd) pausePrebuilds() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "pause",
Short: "Pause prebuilds",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
err := client.PutPrebuildsSettings(inv.Context(), codersdk.PrebuildsSettings{
client, err := r.InitClient(inv)
if err != nil {
return err
}
err = client.PutPrebuildsSettings(inv.Context(), codersdk.PrebuildsSettings{
ReconciliationPaused: true,
})
if err != nil {
@@ -62,16 +65,19 @@ func (r *RootCmd) pausePrebuilds() *serpent.Command {
}
func (r *RootCmd) resumePrebuilds() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "resume",
Short: "Resume prebuilds",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
err := client.PutPrebuildsSettings(inv.Context(), codersdk.PrebuildsSettings{
client, err := r.InitClient(inv)
if err != nil {
return err
}
err = client.PutPrebuildsSettings(inv.Context(), codersdk.PrebuildsSettings{
ReconciliationPaused: false,
})
if err != nil {
+4 -7
View File
@@ -53,19 +53,16 @@ func (r *RootCmd) provisionerDaemonStart() *serpent.Command {
prometheusAddress string
)
orgContext := agpl.NewOrganizationContext()
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "start",
Short: "Run a provisioner daemon",
Middleware: serpent.Chain(
// disable checks and warnings because this command starts a daemon; it is
// not meant for humans typing commands. Furthermore, the checks are
// incompatible with PSK auth that this command uses
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx, cancel := context.WithCancel(inv.Context())
defer cancel()
client, err := r.InitClient(inv)
if err != nil {
return err
}
stopCtx, stopCancel := inv.SignalNotifyContext(ctx, agpl.StopSignalsNoInterrupt...)
defer stopCancel()
+12 -6
View File
@@ -37,16 +37,18 @@ func (r *RootCmd) provisionerKeysCreate() *serpent.Command {
rawTags []string
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "create <name>",
Short: "Create a new provisioner key",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
@@ -100,17 +102,19 @@ func (r *RootCmd) provisionerKeysList() *serpent.Command {
)
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "list",
Short: "List provisioner keys in an organization",
Aliases: []string{"ls"},
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
@@ -147,16 +151,18 @@ func (r *RootCmd) provisionerKeysList() *serpent.Command {
func (r *RootCmd) provisionerKeysDelete() *serpent.Command {
orgContext := agpl.NewOrganizationContext()
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "delete <name>",
Short: "Delete a provisioner key",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
+20 -11
View File
@@ -42,17 +42,19 @@ func (r *RootCmd) workspaceProxy() *serpent.Command {
func (r *RootCmd) regenerateProxyToken() *serpent.Command {
formatter := newUpdateProxyResponseFormatter()
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "regenerate-token <name|id>",
Short: "Regenerate a workspace proxy authentication token. " +
"This will invalidate the existing authentication token.",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
formatter.primaryAccessURL = client.URL.String()
// This is cheeky, but you can also use a uuid string in
// 'DeleteWorkspaceProxyByName' and it will work.
@@ -112,16 +114,18 @@ func (r *RootCmd) patchProxy() *serpent.Command {
}),
)
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "edit <name|id>",
Short: "Edit a workspace proxy",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
if proxyIcon == "" && displayName == "" && proxyName == "" {
_ = inv.Command.HelpHandler(inv)
return xerrors.Errorf("specify at least one field to update")
@@ -187,7 +191,6 @@ func (r *RootCmd) patchProxy() *serpent.Command {
}
func (r *RootCmd) deleteProxy() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "delete <name|id>",
Short: "Delete a workspace proxy",
@@ -196,10 +199,13 @@ func (r *RootCmd) deleteProxy() *serpent.Command {
},
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
wsproxy, err := client.WorkspaceProxyByName(ctx, inv.Args[0])
if err != nil {
@@ -244,18 +250,19 @@ func (r *RootCmd) createProxy() *serpent.Command {
return nil
}
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "create",
Short: "Create a workspace proxy",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
formatter.primaryAccessURL = client.URL.String()
var err error
if proxyName == "" && !noPrompts {
proxyName, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Proxy Name:",
@@ -362,17 +369,19 @@ func (r *RootCmd) listProxies() *serpent.Command {
}),
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "ls",
Aliases: []string{"list"},
Short: "List all workspace proxies",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
proxies, err := client.WorkspaceProxies(ctx)
if err != nil {
return xerrors.Errorf("list workspace proxies: %w", err)