github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/label/edit.go (about) 1 package label 2 3 import ( 4 "errors" 5 "fmt" 6 "net/http" 7 "strings" 8 9 "github.com/MakeNowJust/heredoc" 10 "github.com/ungtb10d/cli/v2/api" 11 "github.com/ungtb10d/cli/v2/internal/ghrepo" 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 editOptions struct { 18 BaseRepo func() (ghrepo.Interface, error) 19 HttpClient func() (*http.Client, error) 20 IO *iostreams.IOStreams 21 22 Color string 23 Description string 24 Name string 25 NewName string 26 } 27 28 func newCmdEdit(f *cmdutil.Factory, runF func(*editOptions) error) *cobra.Command { 29 opts := editOptions{ 30 HttpClient: f.HttpClient, 31 IO: f.IOStreams, 32 } 33 34 cmd := &cobra.Command{ 35 Use: "edit <name>", 36 Short: "Edit a label", 37 Long: heredoc.Docf(` 38 Update a label on GitHub. 39 40 A label can be renamed using the %[1]s--name%[1]s flag. 41 42 The label color needs to be 6 character hex value. 43 `, "`"), 44 Example: heredoc.Doc(` 45 # update the color of the bug label 46 $ gh label edit bug --color FF0000 47 48 # rename and edit the description of the bug label 49 $ gh label edit bug --name big-bug --description "Bigger than normal bug" 50 `), 51 Args: cmdutil.ExactArgs(1, "cannot update label: name argument required"), 52 RunE: func(c *cobra.Command, args []string) error { 53 opts.BaseRepo = f.BaseRepo 54 opts.Name = args[0] 55 opts.Color = strings.TrimPrefix(opts.Color, "#") 56 if opts.Description == "" && 57 opts.Color == "" && 58 opts.NewName == "" { 59 return cmdutil.FlagErrorf("specify at least one of `--color`, `--description`, or `--name`") 60 } 61 if runF != nil { 62 return runF(&opts) 63 } 64 return editRun(&opts) 65 }, 66 } 67 68 cmd.Flags().StringVarP(&opts.Description, "description", "d", "", "Description of the label") 69 cmd.Flags().StringVarP(&opts.Color, "color", "c", "", "Color of the label") 70 cmd.Flags().StringVarP(&opts.NewName, "name", "n", "", "New name of the label") 71 72 return cmd 73 } 74 75 func editRun(opts *editOptions) error { 76 httpClient, err := opts.HttpClient() 77 if err != nil { 78 return err 79 } 80 apiClient := api.NewClientFromHTTP(httpClient) 81 82 baseRepo, err := opts.BaseRepo() 83 if err != nil { 84 return err 85 } 86 87 opts.IO.StartProgressIndicator() 88 err = updateLabel(apiClient, baseRepo, opts) 89 opts.IO.StopProgressIndicator() 90 if err != nil { 91 if errors.Is(err, errLabelAlreadyExists) { 92 return fmt.Errorf("label with name %q already exists", opts.NewName) 93 } 94 return err 95 } 96 97 if opts.IO.IsStdoutTTY() { 98 cs := opts.IO.ColorScheme() 99 successMsg := fmt.Sprintf("%s Label %q updated in %s\n", cs.SuccessIcon(), opts.Name, ghrepo.FullName(baseRepo)) 100 fmt.Fprint(opts.IO.Out, successMsg) 101 } 102 103 return nil 104 }