github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/ssh-key/delete/delete.go (about) 1 package delete 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/ungtb10d/cli/v2/internal/config" 8 "github.com/ungtb10d/cli/v2/internal/prompter" 9 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 10 "github.com/ungtb10d/cli/v2/pkg/iostreams" 11 "github.com/spf13/cobra" 12 ) 13 14 type DeleteOptions struct { 15 IO *iostreams.IOStreams 16 Config func() (config.Config, error) 17 HttpClient func() (*http.Client, error) 18 19 KeyID string 20 Confirmed bool 21 Prompter prompter.Prompter 22 } 23 24 func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { 25 opts := &DeleteOptions{ 26 HttpClient: f.HttpClient, 27 Config: f.Config, 28 IO: f.IOStreams, 29 Prompter: f.Prompter, 30 } 31 32 cmd := &cobra.Command{ 33 Use: "delete <id>", 34 Short: "Delete an SSH key from your GitHub account", 35 Args: cmdutil.ExactArgs(1, "cannot delete: key id required"), 36 RunE: func(cmd *cobra.Command, args []string) error { 37 opts.KeyID = args[0] 38 39 if !opts.IO.CanPrompt() && !opts.Confirmed { 40 return cmdutil.FlagErrorf("--confirm required when not running interactively") 41 } 42 43 if runF != nil { 44 return runF(opts) 45 } 46 return deleteRun(opts) 47 }, 48 } 49 50 cmd.Flags().BoolVarP(&opts.Confirmed, "confirm", "y", false, "Skip the confirmation prompt") 51 return cmd 52 } 53 54 func deleteRun(opts *DeleteOptions) error { 55 httpClient, err := opts.HttpClient() 56 if err != nil { 57 return err 58 } 59 60 cfg, err := opts.Config() 61 if err != nil { 62 return err 63 } 64 65 host, _ := cfg.DefaultHost() 66 key, err := getSSHKey(httpClient, host, opts.KeyID) 67 if err != nil { 68 return err 69 } 70 71 if !opts.Confirmed { 72 if err := opts.Prompter.ConfirmDeletion(key.Title); err != nil { 73 return err 74 } 75 } 76 77 err = deleteSSHKey(httpClient, host, opts.KeyID) 78 if err != nil { 79 return err 80 } 81 82 if opts.IO.IsStdoutTTY() { 83 cs := opts.IO.ColorScheme() 84 fmt.Fprintf(opts.IO.Out, "%s SSH key %q (%s) deleted from your account\n", cs.SuccessIcon(), key.Title, opts.KeyID) 85 } 86 return nil 87 }