Files
coder/cli/organizationmanage.go
T
Spike Curtis 606ae897b7 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.
2025-09-22 17:14:07 +04:00

59 lines
1.4 KiB
Go

package cli
import (
"fmt"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
func (r *RootCmd) createOrganization() *serpent.Command {
cmd := &serpent.Command{
Use: "create <organization name>",
Short: "Create a new organization.",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
),
Options: serpent.OptionSet{
cliui.SkipPromptOption(),
},
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}
orgName := inv.Args[0]
err = codersdk.NameValid(orgName)
if err != nil {
return xerrors.Errorf("organization name %q is invalid: %w", orgName, err)
}
// This check is not perfect since not all users can read all organizations.
// So ignore the error and if the org already exists, prevent the user
// from creating it.
existing, _ := client.OrganizationByName(inv.Context(), orgName)
if existing.ID != uuid.Nil {
return xerrors.Errorf("organization %q already exists", orgName)
}
organization, err := client.CreateOrganization(inv.Context(), codersdk.CreateOrganizationRequest{
Name: orgName,
})
if err != nil {
return xerrors.Errorf("failed to create organization: %w", err)
}
_, _ = fmt.Fprintf(inv.Stdout, "Organization %s (%s) created.\n", organization.Name, organization.ID)
return nil
},
}
return cmd
}