-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
labels.go
293 lines (258 loc) · 8.71 KB
/
labels.go
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package config
import (
"fmt"
"net/http"
"os"
"slices"
"sort"
mapset "github.com/deckarep/golang-set/v2"
"github.com/xanzy/go-gitlab"
"gitlab.com/tozd/go/errors"
)
// getLabels populates configuration struct with configuration available
// from GitLab labels API endpoint.
func (c *GetCommand) getLabels(client *gitlab.Client, configuration *Configuration) (bool, errors.E) { //nolint:unparam
fmt.Fprintf(os.Stderr, "Getting project labels...\n")
configuration.Labels = []map[string]interface{}{}
descriptions, errE := getLabelsDescriptions(c.DocsRef)
if errE != nil {
return false, errE
}
// We need "id" later on.
if _, ok := descriptions["id"]; !ok {
return false, errors.New(`"id" field is missing in project labels descriptions`)
}
configuration.LabelsComment = formatDescriptions(descriptions)
u := fmt.Sprintf("projects/%s/labels", gitlab.PathEscape(c.Project))
options := &gitlab.ListLabelsOptions{ //nolint:exhaustruct
ListOptions: gitlab.ListOptions{
PerPage: maxGitLabPageSize,
Page: 1,
},
IncludeAncestorGroups: gitlab.Bool(false),
}
for {
req, err := client.NewRequest(http.MethodGet, u, options, nil)
if err != nil {
errE := errors.WithMessage(err, "failed to get project labels")
errors.Details(errE)["page"] = options.Page
return false, errE
}
labels := []map[string]interface{}{}
response, err := client.Do(req, &labels)
if err != nil {
errE := errors.WithMessage(err, "failed to get project labels")
errors.Details(errE)["page"] = options.Page
return false, errE
}
if len(labels) == 0 {
break
}
for _, label := range labels {
// Making sure id and priority are an integer.
castFloatsToInts(label)
// Only retain those keys which can be edited through the API
// (which are those available in descriptions).
for key := range label {
_, ok := descriptions[key]
if !ok {
delete(label, key)
}
}
id, ok := label["id"]
if !ok {
return false, errors.New(`project label is missing field "id"`)
}
_, ok = id.(int)
if !ok {
errE := errors.New(`project label's field "id" is not an integer`)
errors.Details(errE)["type"] = fmt.Sprintf("%T", id)
errors.Details(errE)["value"] = id
return false, errE
}
configuration.Labels = append(configuration.Labels, label)
}
if response.NextPage == 0 {
break
}
options.Page = response.NextPage
}
// We sort by label ID so that we have deterministic order.
sort.Slice(configuration.Labels, func(i, j int) bool {
// We checked that id is int above.
return configuration.Labels[i]["id"].(int) < configuration.Labels[j]["id"].(int) //nolint:forcetypeassert
})
return false, nil
}
// parseLabelsDocumentation parses GitLab's documentation in Markdown for
// labels API endpoint and extracts description of fields used to describe
// an individual label.
func parseLabelsDocumentation(input []byte) (map[string]string, errors.E) {
newDescriptions, err := parseTable(input, "Create a new label", nil)
if err != nil {
return nil, err
}
editDescriptions, err := parseTable(input, "Edit an existing label", nil)
if err != nil {
return nil, err
}
// We want to preserve label IDs so we copy edit description for it.
newDescriptions["id"] = editDescriptions["label_id"]
return newDescriptions, nil
}
// getLabelsDescriptions obtains description of fields used to describe
// an individual label from GitLab's documentation for labels API endpoint.
func getLabelsDescriptions(gitRef string) (map[string]string, errors.E) {
data, err := downloadFile(fmt.Sprintf("https://gitlab.com/gitlab-org/gitlab/-/raw/%s/doc/api/labels.md", gitRef))
if err != nil {
return nil, errors.WithMessage(err, "failed to get project labels descriptions")
}
return parseLabelsDocumentation(data)
}
// updateLabels updates GitLab project's labels using GitLab labels API endpoint
// based on the configuration struct.
//
// Labels without the ID field are matched to existing labels based on the name.
// Unmatched labels are created as new. Save configuration with label IDs to be able
// to rename existing labels.
func (c *SetCommand) updateLabels(client *gitlab.Client, configuration *Configuration) errors.E {
if configuration.Labels == nil {
return nil
}
fmt.Fprintf(os.Stderr, "Updating project labels...\n")
options := &gitlab.ListLabelsOptions{ //nolint:exhaustruct
ListOptions: gitlab.ListOptions{
PerPage: maxGitLabPageSize,
Page: 1,
},
IncludeAncestorGroups: gitlab.Bool(false),
}
labels := []*gitlab.Label{}
for {
ls, response, err := client.Labels.ListLabels(c.Project, options)
if err != nil {
errE := errors.WithMessage(err, "failed to get project labels")
errors.Details(errE)["page"] = options.Page
return errE
}
labels = append(labels, ls...)
if response.NextPage == 0 {
break
}
options.Page = response.NextPage
}
existingLabelsSet := mapset.NewThreadUnsafeSet[int]()
namesToIDs := map[string]int{}
for _, label := range labels {
namesToIDs[label.Name] = label.ID
existingLabelsSet.Add(label.ID)
}
// Set label IDs if a matching existing label can be found.
for i, label := range configuration.Labels { //nolint:dupl
// Is label ID already set?
id, ok := label["id"]
if ok {
// If ID is provided, the label should exist.
iid, ok := id.(int) //nolint:govet
if !ok {
errE := errors.New(`project label's field "id" is not an integer`)
errors.Details(errE)["index"] = i
errors.Details(errE)["type"] = fmt.Sprintf("%T", id)
errors.Details(errE)["value"] = id
return errE
}
if existingLabelsSet.Contains(iid) {
continue
}
// Label does not exist with that ID. We remove the ID and leave to matching to
// find the correct ID, if it exists. Otherwise we will just create a new label.
delete(label, "id")
}
name, ok := label["name"]
if !ok {
errE := errors.Errorf(`project label is missing field "name"`)
errors.Details(errE)["index"] = i
return errE
}
n, ok := name.(string)
if !ok {
errE := errors.New(`project label's field "name" is not a string`)
errors.Details(errE)["index"] = i
errors.Details(errE)["type"] = fmt.Sprintf("%T", name)
errors.Details(errE)["value"] = name
return errE
}
id, ok = namesToIDs[n]
if ok {
label["id"] = id
}
}
wantedLabelsSet := mapset.NewThreadUnsafeSet[int]()
for _, label := range configuration.Labels {
id, ok := label["id"]
if ok {
// We checked that id is int above.
wantedLabelsSet.Add(id.(int)) //nolint:forcetypeassert
}
}
extraLabels := existingLabelsSet.Difference(wantedLabelsSet).ToSlice()
slices.Sort(extraLabels)
for _, labelID := range extraLabels {
// TODO: Use go-gitlab's function once it is updated to new API.
// See: https://github.com/xanzy/go-gitlab/issues/1321
u := fmt.Sprintf("projects/%s/labels/%d", gitlab.PathEscape(c.Project), labelID)
req, err := client.NewRequest(http.MethodDelete, u, nil, nil)
if err != nil {
errE := errors.WithMessage(err, "failed to delete project label")
errors.Details(errE)["label"] = labelID
return errE
}
_, err = client.Do(req, nil)
if err != nil {
errE := errors.WithMessage(err, "failed to delete project label")
errors.Details(errE)["label"] = labelID
return errE
}
}
for i, label := range configuration.Labels {
id, ok := label["id"]
if !ok { //nolint:dupl
u := fmt.Sprintf("projects/%s/labels", gitlab.PathEscape(c.Project))
req, err := client.NewRequest(http.MethodPost, u, label, nil)
if err != nil {
// We made sure above that all labels in configuration without label ID have name.
errE := errors.WithMessage(err, "failed to create project label")
errors.Details(errE)["index"] = i
errors.Details(errE)["label"] = label["name"]
return errE
}
_, err = client.Do(req, nil)
if err != nil { // We made sure above that all labels in configuration without label ID have name.
errE := errors.WithMessage(err, "failed to create project label")
errors.Details(errE)["index"] = i
errors.Details(errE)["label"] = label["name"]
return errE
}
} else {
// We made sure above that all labels in configuration with label ID exist
// and that they are ints.
iid := id.(int) //nolint:errcheck,forcetypeassert
u := fmt.Sprintf("projects/%s/labels/%d", gitlab.PathEscape(c.Project), iid)
req, err := client.NewRequest(http.MethodPut, u, label, nil)
if err != nil {
errE := errors.WithMessage(err, "failed to update project label")
errors.Details(errE)["index"] = i
errors.Details(errE)["label"] = iid
return errE
}
_, err = client.Do(req, nil)
if err != nil {
errE := errors.WithMessage(err, "failed to update project label")
errors.Details(errE)["index"] = i
errors.Details(errE)["label"] = iid
return errE
}
}
}
return nil
}