github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/gist/delete/delete.go (about) 1 package delete 2 3 import ( 4 "errors" 5 "fmt" 6 "net/http" 7 "strings" 8 9 "github.com/ungtb10d/cli/v2/api" 10 "github.com/ungtb10d/cli/v2/internal/config" 11 "github.com/ungtb10d/cli/v2/pkg/cmd/gist/shared" 12 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 13 "github.com/ungtb10d/cli/v2/pkg/iostreams" 14 "github.com/spf13/cobra" 15 ) 16 17 type DeleteOptions struct { 18 IO *iostreams.IOStreams 19 Config func() (config.Config, error) 20 HttpClient func() (*http.Client, error) 21 22 Selector string 23 } 24 25 func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { 26 opts := DeleteOptions{ 27 IO: f.IOStreams, 28 Config: f.Config, 29 HttpClient: f.HttpClient, 30 } 31 32 cmd := &cobra.Command{ 33 Use: "delete {<id> | <url>}", 34 Short: "Delete a gist", 35 Args: cmdutil.ExactArgs(1, "cannot delete: gist argument required"), 36 RunE: func(c *cobra.Command, args []string) error { 37 opts.Selector = args[0] 38 if runF != nil { 39 return runF(&opts) 40 } 41 return deleteRun(&opts) 42 }, 43 } 44 return cmd 45 } 46 47 func deleteRun(opts *DeleteOptions) error { 48 gistID := opts.Selector 49 50 if strings.Contains(gistID, "/") { 51 id, err := shared.GistIDFromURL(gistID) 52 if err != nil { 53 return err 54 } 55 gistID = id 56 } 57 client, err := opts.HttpClient() 58 if err != nil { 59 return err 60 } 61 62 cfg, err := opts.Config() 63 if err != nil { 64 return err 65 } 66 67 host, _ := cfg.DefaultHost() 68 69 apiClient := api.NewClientFromHTTP(client) 70 if err := deleteGist(apiClient, host, gistID); err != nil { 71 if errors.Is(err, shared.NotFoundErr) { 72 return fmt.Errorf("unable to delete gist %s: either the gist is not found or it is not owned by you", gistID) 73 } 74 return err 75 } 76 77 return nil 78 } 79 80 func deleteGist(apiClient *api.Client, hostname string, gistID string) error { 81 path := "gists/" + gistID 82 err := apiClient.REST(hostname, "DELETE", path, nil, nil) 83 if err != nil { 84 var httpErr api.HTTPError 85 if errors.As(err, &httpErr) && httpErr.StatusCode == 404 { 86 return shared.NotFoundErr 87 } 88 return err 89 } 90 return nil 91 }