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
+14 -7
View File
@@ -36,17 +36,19 @@ func (r *RootCmd) sharing() *serpent.Command {
}
func (r *RootCmd) statusWorkspaceSharing() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "status <workspace>",
Short: "List all users and groups the given Workspace is shared with.",
Aliases: []string{"list"},
Middleware: serpent.Chain(
r.InitClient(client),
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}
workspace, err := namedWorkspace(inv.Context(), client, inv.Args[0])
if err != nil {
return xerrors.Errorf("unable to fetch Workspace %s: %w", inv.Args[0], err)
@@ -72,7 +74,6 @@ func (r *RootCmd) statusWorkspaceSharing() *serpent.Command {
func (r *RootCmd) shareWorkspace() *serpent.Command {
var (
client = new(codersdk.Client)
users []string
groups []string
@@ -98,10 +99,14 @@ func (r *RootCmd) shareWorkspace() *serpent.Command {
},
},
Middleware: serpent.Chain(
r.InitClient(client),
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}
if len(users) == 0 && len(groups) == 0 {
return xerrors.New("at least one user or group must be provided")
}
@@ -171,7 +176,6 @@ func (r *RootCmd) shareWorkspace() *serpent.Command {
func (r *RootCmd) unshareWorkspace() *serpent.Command {
var (
client = new(codersdk.Client)
users []string
groups []string
)
@@ -194,13 +198,16 @@ func (r *RootCmd) unshareWorkspace() *serpent.Command {
},
},
Middleware: serpent.Chain(
r.InitClient(client),
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
if len(users) == 0 && len(groups) == 0 {
return xerrors.New("at least one user or group must be provided")
}
client, err := r.InitClient(inv)
if err != nil {
return err
}
workspace, err := namedWorkspace(inv.Context(), client, inv.Args[0])
if err != nil {