cli/pkg/cmd/alias/delete/delete.go
Kynan Ware b8ee5c5eba Add godoc comments to exported symbols in remaining packages
Add documentation comments to exported symbols across all remaining
smaller packages including cmd/gen-docs, context, internal/browser,
internal/gh, internal/ghcmd, internal/ghinstance, internal/ghrepo,
internal/keyring, internal/run, internal/safepaths, internal/tableprinter,
internal/text, internal/update, pkg/cmd/accessibility, pkg/cmd/actions,
pkg/cmd/alias, pkg/cmd/api, pkg/cmd/browse, pkg/cmd/cache,
pkg/cmd/completion, pkg/cmd/copilot, pkg/cmd/factory, pkg/cmd/gpg-key,
pkg/cmd/label, pkg/cmd/licenses, pkg/cmd/org, pkg/cmd/preview,
pkg/cmd/ssh-key, pkg/cmd/version, pkg/extensions, pkg/jsoncolor,
pkg/markdown, pkg/option, pkg/set, pkg/ssh, pkg/surveyext, test,
internal/authflow, and utils.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-04 16:14:20 -07:00

100 lines
2.2 KiB
Go

package delete
import (
"fmt"
"sort"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
// DeleteOptions holds the options for the command.
type DeleteOptions struct {
Config func() (gh.Config, error)
IO *iostreams.IOStreams
Name string
All bool
}
// NewCmdDelete creates a new cobra command for the delete subcommand.
func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command {
opts := &DeleteOptions{
IO: f.IOStreams,
Config: f.Config,
}
cmd := &cobra.Command{
Use: "delete {<alias> | --all}",
Short: "Delete set aliases",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 && !opts.All {
return cmdutil.FlagErrorf("specify an alias to delete or `--all`")
}
if len(args) > 0 && opts.All {
return cmdutil.FlagErrorf("cannot use `--all` with alias name")
}
if len(args) > 0 {
opts.Name = args[0]
}
if runF != nil {
return runF(opts)
}
return deleteRun(opts)
},
}
cmd.Flags().BoolVar(&opts.All, "all", false, "Delete all aliases")
return cmd
}
func deleteRun(opts *DeleteOptions) error {
cfg, err := opts.Config()
if err != nil {
return err
}
aliasCfg := cfg.Aliases()
aliases := make(map[string]string)
if opts.All {
aliases = aliasCfg.All()
if len(aliases) == 0 {
return cmdutil.NewNoResultsError("no aliases configured")
}
} else {
expansion, err := aliasCfg.Get(opts.Name)
if err != nil {
return fmt.Errorf("no such alias %s", opts.Name)
}
aliases[opts.Name] = expansion
}
for name := range aliases {
if err := aliasCfg.Delete(name); err != nil {
return fmt.Errorf("failed to delete alias %s: %w", name, err)
}
}
if err := cfg.Write(); err != nil {
return err
}
if opts.IO.IsStdoutTTY() {
cs := opts.IO.ColorScheme()
keys := make([]string, 0, len(aliases))
for k := range aliases {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Fprintf(opts.IO.ErrOut, "%s Deleted alias %s; was %s\n", cs.SuccessIconWithColor(cs.Red), k, aliases[k])
}
}
return nil
}