File: create.go

package info (click to toggle)
gh 2.46.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,548 kB
  • sloc: sh: 227; makefile: 117
file content (186 lines) | stat: -rw-r--r-- 4,843 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package label

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"math/rand"
	"net/http"
	"strings"
	"time"

	"github.com/MakeNowJust/heredoc"
	"github.com/cli/cli/v2/api"
	"github.com/cli/cli/v2/internal/ghrepo"
	"github.com/cli/cli/v2/pkg/cmdutil"
	"github.com/cli/cli/v2/pkg/iostreams"
	"github.com/spf13/cobra"
)

var randomColors = []string{
	"B60205",
	"D93F0B",
	"FBCA04",
	"0E8A16",
	"006B75",
	"1D76DB",
	"0052CC",
	"5319E7",
	"E99695",
	"F9D0C4",
	"FEF2C0",
	"C2E0C6",
	"BFDADC",
	"C5DEF5",
	"BFD4F2",
	"D4C5F9",
}

type createOptions struct {
	BaseRepo   func() (ghrepo.Interface, error)
	HttpClient func() (*http.Client, error)
	IO         *iostreams.IOStreams

	Color       string
	Description string
	Name        string
	Force       bool
}

func newCmdCreate(f *cmdutil.Factory, runF func(*createOptions) error) *cobra.Command {
	opts := createOptions{
		HttpClient: f.HttpClient,
		IO:         f.IOStreams,
	}

	cmd := &cobra.Command{
		Use:   "create <name>",
		Short: "Create a new label",
		Long: heredoc.Docf(`
			Create a new label on GitHub, or update an existing one with %[1]s--force%[1]s.

			Must specify name for the label. The description and color are optional.
			If a color isn't provided, a random one will be chosen.

			The label color needs to be 6 character hex value.
		`, "`"),
		Example: heredoc.Doc(`
			# create new bug label
			$ gh label create bug --description "Something isn't working" --color E99695
		`),
		Args: cmdutil.ExactArgs(1, "cannot create label: name argument required"),
		RunE: func(c *cobra.Command, args []string) error {
			opts.BaseRepo = f.BaseRepo
			opts.Name = args[0]
			opts.Color = strings.TrimPrefix(opts.Color, "#")
			if runF != nil {
				return runF(&opts)
			}
			return createRun(&opts)
		},
	}

	cmd.Flags().StringVarP(&opts.Description, "description", "d", "", "Description of the label")
	cmd.Flags().StringVarP(&opts.Color, "color", "c", "", "Color of the label")
	cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Update the label color and description if label already exists")

	return cmd
}

var errLabelAlreadyExists = errors.New("label already exists")

func createRun(opts *createOptions) error {
	httpClient, err := opts.HttpClient()
	if err != nil {
		return err
	}

	baseRepo, err := opts.BaseRepo()
	if err != nil {
		return err
	}

	if opts.Color == "" {
		r := rand.New(rand.NewSource(time.Now().UnixNano()))
		opts.Color = randomColors[r.Intn(len(randomColors)-1)]
	}

	opts.IO.StartProgressIndicator()
	err = createLabel(httpClient, baseRepo, opts)
	opts.IO.StopProgressIndicator()
	if err != nil {
		if errors.Is(err, errLabelAlreadyExists) {
			return fmt.Errorf("label with name %q already exists; use `--force` to update its color and description", opts.Name)
		}
		return err
	}

	if opts.IO.IsStdoutTTY() {
		cs := opts.IO.ColorScheme()
		successMsg := fmt.Sprintf("%s Label %q created in %s\n", cs.SuccessIcon(), opts.Name, ghrepo.FullName(baseRepo))
		fmt.Fprint(opts.IO.Out, successMsg)
	}

	return nil
}

func createLabel(client *http.Client, repo ghrepo.Interface, opts *createOptions) error {
	apiClient := api.NewClientFromHTTP(client)
	path := fmt.Sprintf("repos/%s/%s/labels", repo.RepoOwner(), repo.RepoName())
	requestByte, err := json.Marshal(map[string]string{
		"name":        opts.Name,
		"description": opts.Description,
		"color":       opts.Color,
	})
	if err != nil {
		return err
	}
	requestBody := bytes.NewReader(requestByte)
	err = apiClient.REST(repo.RepoHost(), "POST", path, requestBody, nil)

	if httpError, ok := err.(api.HTTPError); ok && isLabelAlreadyExistsError(httpError) {
		err = errLabelAlreadyExists
	}

	if opts.Force && errors.Is(err, errLabelAlreadyExists) {
		editOpts := editOptions{
			Description: opts.Description,
			Color:       opts.Color,
			Name:        opts.Name,
		}
		return updateLabel(apiClient, repo, &editOpts)
	}

	return err
}

func updateLabel(apiClient *api.Client, repo ghrepo.Interface, opts *editOptions) error {
	path := fmt.Sprintf("repos/%s/%s/labels/%s", repo.RepoOwner(), repo.RepoName(), opts.Name)
	properties := map[string]string{}
	if opts.Description != "" {
		properties["description"] = opts.Description
	}
	if opts.Color != "" {
		properties["color"] = opts.Color
	}
	if opts.NewName != "" {
		properties["new_name"] = opts.NewName
	}
	requestByte, err := json.Marshal(properties)
	if err != nil {
		return err
	}
	requestBody := bytes.NewReader(requestByte)
	err = apiClient.REST(repo.RepoHost(), "PATCH", path, requestBody, nil)

	if httpError, ok := err.(api.HTTPError); ok && isLabelAlreadyExistsError(httpError) {
		err = errLabelAlreadyExists
	}

	return err
}

func isLabelAlreadyExistsError(err api.HTTPError) bool {
	return err.StatusCode == 422 && len(err.Errors) == 1 && err.Errors[0].Field == "name" && err.Errors[0].Code == "already_exists"
}