github.com/cli/cli@v1.14.1-0.20210902173923-1af6a669e342/pkg/cmd/release/delete/delete.go (about) 1 package delete 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/AlecAivazis/survey/v2" 8 "github.com/cli/cli/api" 9 "github.com/cli/cli/internal/ghrepo" 10 "github.com/cli/cli/pkg/cmd/release/shared" 11 "github.com/cli/cli/pkg/cmdutil" 12 "github.com/cli/cli/pkg/iostreams" 13 "github.com/cli/cli/pkg/prompt" 14 "github.com/spf13/cobra" 15 ) 16 17 type DeleteOptions struct { 18 HttpClient func() (*http.Client, error) 19 IO *iostreams.IOStreams 20 BaseRepo func() (ghrepo.Interface, error) 21 22 TagName string 23 SkipConfirm bool 24 } 25 26 func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { 27 opts := &DeleteOptions{ 28 IO: f.IOStreams, 29 HttpClient: f.HttpClient, 30 } 31 32 cmd := &cobra.Command{ 33 Use: "delete <tag>", 34 Short: "Delete a release", 35 Args: cobra.ExactArgs(1), 36 RunE: func(cmd *cobra.Command, args []string) error { 37 // support `-R, --repo` override 38 opts.BaseRepo = f.BaseRepo 39 40 opts.TagName = args[0] 41 42 if runF != nil { 43 return runF(opts) 44 } 45 return deleteRun(opts) 46 }, 47 } 48 49 cmd.Flags().BoolVarP(&opts.SkipConfirm, "yes", "y", false, "Skip the confirmation prompt") 50 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 baseRepo, err := opts.BaseRepo() 61 if err != nil { 62 return err 63 } 64 65 release, err := shared.FetchRelease(httpClient, baseRepo, opts.TagName) 66 if err != nil { 67 return err 68 } 69 70 if !opts.SkipConfirm && opts.IO.CanPrompt() { 71 var confirmed bool 72 err := prompt.SurveyAskOne(&survey.Confirm{ 73 Message: fmt.Sprintf("Delete release %s in %s?", release.TagName, ghrepo.FullName(baseRepo)), 74 Default: true, 75 }, &confirmed) 76 if err != nil { 77 return err 78 } 79 80 if !confirmed { 81 return cmdutil.CancelError 82 } 83 } 84 85 err = deleteRelease(httpClient, release.APIURL) 86 if err != nil { 87 return err 88 } 89 90 if !opts.IO.IsStdoutTTY() || !opts.IO.IsStderrTTY() { 91 return nil 92 } 93 94 iofmt := opts.IO.ColorScheme() 95 fmt.Fprintf(opts.IO.ErrOut, "%s Deleted release %s\n", iofmt.SuccessIconWithColor(iofmt.Red), release.TagName) 96 if !release.IsDraft { 97 fmt.Fprintf(opts.IO.ErrOut, "%s Note that the %s git tag still remains in the repository\n", iofmt.WarningIcon(), release.TagName) 98 } 99 100 return nil 101 } 102 103 func deleteRelease(httpClient *http.Client, releaseURL string) error { 104 req, err := http.NewRequest("DELETE", releaseURL, nil) 105 if err != nil { 106 return err 107 } 108 109 resp, err := httpClient.Do(req) 110 if err != nil { 111 return err 112 } 113 defer resp.Body.Close() 114 115 if resp.StatusCode > 299 { 116 return api.HandleHTTPError(resp) 117 } 118 return nil 119 }