Files
coder/cli/templatedelete.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

88 lines
2.0 KiB
Go

package cli
import (
"fmt"
"strings"
"time"
"golang.org/x/xerrors"
"github.com/coder/pretty"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
func (r *RootCmd) templateDelete() *serpent.Command {
orgContext := NewOrganizationContext()
cmd := &serpent.Command{
Use: "delete [name...]",
Short: "Delete templates",
Options: serpent.OptionSet{
cliui.SkipPromptOption(),
},
Handler: func(inv *serpent.Invocation) error {
var (
ctx = inv.Context()
templateNames = []string{}
templates = []codersdk.Template{}
)
client, err := r.InitClient(inv)
if err != nil {
return err
}
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
if len(inv.Args) > 0 {
templateNames = inv.Args
for _, templateName := range templateNames {
template, err := client.TemplateByName(ctx, organization.ID, templateName)
if err != nil {
return xerrors.Errorf("get template by name: %w", err)
}
templates = append(templates, template)
}
} else {
template, err := selectTemplate(inv, client, organization)
if err != nil {
return err
}
templates = append(templates, template)
templateNames = append(templateNames, template.Name)
}
// Confirm deletion of the template.
_, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: fmt.Sprintf("Delete these templates: %s?", pretty.Sprint(cliui.DefaultStyles.Code, strings.Join(templateNames, ", "))),
IsConfirm: true,
Default: cliui.ConfirmNo,
})
if err != nil {
return err
}
for _, template := range templates {
err := client.DeleteTemplate(ctx, template.ID)
if err != nil {
return xerrors.Errorf("delete template %q: %w", template.Name, err)
}
_, _ = fmt.Fprintln(
inv.Stdout, "Deleted template "+pretty.Sprint(cliui.DefaultStyles.Keyword, template.Name)+" at "+cliui.Timestamp(time.Now()),
)
}
return nil
},
}
orgContext.AttachOptions(cmd)
return cmd
}