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