github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/alias/delete/delete.go (about)

     1  package delete
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/ungtb10d/cli/v2/internal/config"
     7  	"github.com/ungtb10d/cli/v2/pkg/cmdutil"
     8  	"github.com/ungtb10d/cli/v2/pkg/iostreams"
     9  	"github.com/spf13/cobra"
    10  )
    11  
    12  type DeleteOptions struct {
    13  	Config func() (config.Config, error)
    14  	IO     *iostreams.IOStreams
    15  
    16  	Name string
    17  }
    18  
    19  func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command {
    20  	opts := &DeleteOptions{
    21  		IO:     f.IOStreams,
    22  		Config: f.Config,
    23  	}
    24  
    25  	cmd := &cobra.Command{
    26  		Use:   "delete <alias>",
    27  		Short: "Delete an alias",
    28  		Args:  cobra.ExactArgs(1),
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			opts.Name = args[0]
    31  
    32  			if runF != nil {
    33  				return runF(opts)
    34  			}
    35  			return deleteRun(opts)
    36  		},
    37  	}
    38  
    39  	return cmd
    40  }
    41  
    42  func deleteRun(opts *DeleteOptions) error {
    43  	cfg, err := opts.Config()
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	aliasCfg := cfg.Aliases()
    49  
    50  	expansion, err := aliasCfg.Get(opts.Name)
    51  	if err != nil {
    52  		return fmt.Errorf("no such alias %s", opts.Name)
    53  
    54  	}
    55  
    56  	err = aliasCfg.Delete(opts.Name)
    57  	if err != nil {
    58  		return fmt.Errorf("failed to delete alias %s: %w", opts.Name, err)
    59  	}
    60  
    61  	err = cfg.Write()
    62  	if err != nil {
    63  		return err
    64  	}
    65  
    66  	if opts.IO.IsStdoutTTY() {
    67  		cs := opts.IO.ColorScheme()
    68  		fmt.Fprintf(opts.IO.ErrOut, "%s Deleted alias %s; was %s\n", cs.SuccessIconWithColor(cs.Red), opts.Name, expansion)
    69  	}
    70  
    71  	return nil
    72  }