github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/label/delete.go (about) 1 package label 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/ungtb10d/cli/v2/api" 8 "github.com/ungtb10d/cli/v2/internal/ghrepo" 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 iprompter interface { 15 ConfirmDeletion(string) error 16 } 17 18 type deleteOptions struct { 19 BaseRepo func() (ghrepo.Interface, error) 20 HttpClient func() (*http.Client, error) 21 IO *iostreams.IOStreams 22 Prompter iprompter 23 24 Name string 25 Confirmed bool 26 } 27 28 func newCmdDelete(f *cmdutil.Factory, runF func(*deleteOptions) error) *cobra.Command { 29 opts := deleteOptions{ 30 HttpClient: f.HttpClient, 31 IO: f.IOStreams, 32 Prompter: f.Prompter, 33 } 34 35 cmd := &cobra.Command{ 36 Use: "delete <name>", 37 Short: "Delete a label from a repository", 38 Args: cmdutil.ExactArgs(1, "cannot delete label: name argument required"), 39 RunE: func(c *cobra.Command, args []string) error { 40 // support `-R, --repo` override 41 opts.BaseRepo = f.BaseRepo 42 opts.Name = args[0] 43 44 if !opts.IO.CanPrompt() && !opts.Confirmed { 45 return cmdutil.FlagErrorf("--confirm required when not running interactively") 46 } 47 48 if runF != nil { 49 return runF(&opts) 50 } 51 return deleteRun(&opts) 52 }, 53 } 54 55 cmd.Flags().BoolVar(&opts.Confirmed, "confirm", false, "Confirm deletion without prompting") 56 57 return cmd 58 } 59 60 func deleteRun(opts *deleteOptions) error { 61 httpClient, err := opts.HttpClient() 62 if err != nil { 63 return err 64 } 65 66 baseRepo, err := opts.BaseRepo() 67 if err != nil { 68 return err 69 } 70 71 if !opts.Confirmed { 72 if err := opts.Prompter.ConfirmDeletion(opts.Name); err != nil { 73 return err 74 } 75 } 76 77 opts.IO.StartProgressIndicator() 78 err = deleteLabel(httpClient, baseRepo, opts.Name) 79 opts.IO.StopProgressIndicator() 80 if err != nil { 81 return err 82 } 83 84 if opts.IO.IsStdoutTTY() { 85 cs := opts.IO.ColorScheme() 86 successMsg := fmt.Sprintf("%s Label %q deleted from %s\n", cs.SuccessIcon(), opts.Name, ghrepo.FullName(baseRepo)) 87 fmt.Fprint(opts.IO.Out, successMsg) 88 } 89 90 return nil 91 } 92 93 func deleteLabel(client *http.Client, repo ghrepo.Interface, name string) error { 94 apiClient := api.NewClientFromHTTP(client) 95 path := fmt.Sprintf("repos/%s/%s/labels/%s", repo.RepoOwner(), repo.RepoName(), name) 96 97 return apiClient.REST(repo.RepoHost(), "DELETE", path, nil, nil) 98 }