1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
package delete
import (
"fmt"
"sort"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type DeleteOptions struct {
Config func() (config.Config, error)
IO *iostreams.IOStreams
Name string
All bool
}
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
}
|