/
edit.go
497 lines (447 loc) · 12 KB
/
edit.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/google/go-github/github"
)
func editIssue(original []byte, issue *github.Issue) {
updated := editText(original)
if bytes.Equal(original, updated) {
log.Print("no changes made")
return
}
newIssue, err := writeIssue(issue, updated, false)
if err != nil {
log.Fatal(err)
}
if newIssue != nil {
issue = newIssue
}
log.Printf("https://github.com/%s/issues/%d updated", *project, getInt(issue.Number))
}
func editText(original []byte) []byte {
f, err := ioutil.TempFile("", "issue-edit-")
if err != nil {
log.Fatal(err)
}
if err := ioutil.WriteFile(f.Name(), original, 0666); err != nil {
log.Fatal(err)
}
if err := runEditor(f.Name()); err != nil {
log.Fatal(err)
}
updated, err := ioutil.ReadFile(f.Name())
if err != nil {
log.Fatal(err)
}
name := f.Name()
f.Close()
os.Remove(name)
return updated
}
func runEditor(filename string) error {
ed := os.Getenv("VISUAL")
if ed == "" {
ed = os.Getenv("EDITOR")
}
if ed == "" {
ed = "ed"
}
// If the editor contains spaces or other magic shell chars,
// invoke it as a shell command. This lets people have
// environment variables like "EDITOR=emacs -nw".
// The magic list of characters and the idea of running
// sh -c this way is taken from git/run-command.c.
var cmd *exec.Cmd
if strings.ContainsAny(ed, "|&;<>()$`\\\"' \t\n*?[#~=%") {
cmd = exec.Command("sh", "-c", ed+` "$@"`, "$EDITOR", filename)
} else {
cmd = exec.Command(ed, filename)
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("invoking editor: %v", err)
}
return nil
}
const bulkHeader = "\nBulk editing these issues:"
func diff(line, field, old string) *string {
old = strings.TrimSpace(old)
line = strings.TrimSpace(strings.TrimPrefix(line, field))
if old == line {
return nil
}
return &line
}
func writeIssue(old *github.Issue, updated []byte, isBulk bool) (issue *github.Issue, err error) {
var errbuf bytes.Buffer
defer func() {
if errbuf.Len() > 0 {
err = errors.New(strings.TrimSpace(errbuf.String()))
}
}()
sdata := string(updated)
off := 0
var edit github.IssueRequest
var addLabels, removeLabels []string
for _, line := range strings.SplitAfter(sdata, "\n") {
off += len(line)
line = strings.TrimSpace(line)
if line == "" {
break
}
switch {
case strings.HasPrefix(line, "#"):
continue
case strings.HasPrefix(line, "Title:"):
edit.Title = diff(line, "Title:", getString(old.Title))
case strings.HasPrefix(line, "State:"):
edit.State = diff(line, "State:", getString(old.State))
case strings.HasPrefix(line, "Assignee:"):
edit.Assignee = diff(line, "Assignee:", getUserLogin(old.Assignee))
case strings.HasPrefix(line, "Closed:"):
continue
case strings.HasPrefix(line, "Labels:"):
if isBulk {
addLabels, removeLabels = diffList2(line, "Labels:", getLabelNames(old.Labels))
} else {
edit.Labels = diffList(line, "Labels:", getLabelNames(old.Labels))
}
case strings.HasPrefix(line, "Milestone:"):
edit.Milestone = findMilestone(&errbuf, diff(line, "Milestone:", getMilestoneTitle(old.Milestone)))
case strings.HasPrefix(line, "URL:"):
continue
default:
fmt.Fprintf(&errbuf, "unknown summary line: %s\n", line)
}
}
if errbuf.Len() > 0 {
return nil, nil
}
if getInt(old.Number) == 0 {
comment := strings.TrimSpace(sdata[off:])
edit.Body = &comment
issue, _, err := client.Issues.Create(context.Background(), projectOwner, projectRepo, &edit)
if err != nil {
fmt.Fprintf(&errbuf, "error creating issue: %v\n", err)
return nil, nil
}
return issue, nil
}
if getInt(old.Number) == -1 {
// Asking to just sanity check the text parsing.
return nil, nil
}
marker := "\nReported by "
if isBulk {
marker = bulkHeader
}
var comment string
if i := strings.Index(sdata, marker); i >= off {
comment = strings.TrimSpace(sdata[off:i])
}
if comment == "<optional comment here>" {
comment = ""
}
var failed bool
var did []string
if comment != "" {
_, _, err := client.Issues.CreateComment(context.Background(), projectOwner, projectRepo, getInt(old.Number), &github.IssueComment{
Body: &comment,
})
if err != nil {
fmt.Fprintf(&errbuf, "error saving comment: %v\n", err)
failed = true
} else {
did = append(did, "saved comment")
}
}
if edit.Title != nil || edit.State != nil || edit.Assignee != nil || edit.Labels != nil || edit.Milestone != nil {
_, _, err := client.Issues.Edit(context.Background(), projectOwner, projectRepo, getInt(old.Number), &edit)
if err != nil {
fmt.Fprintf(&errbuf, "error changing metadata: %v\n", err)
failed = true
} else {
did = append(did, "updated metadata")
}
}
if len(addLabels) > 0 {
_, _, err := client.Issues.AddLabelsToIssue(context.Background(), projectOwner, projectRepo, getInt(old.Number), addLabels)
if err != nil {
fmt.Fprintf(&errbuf, "error adding labels: %v\n", err)
failed = true
} else {
if len(addLabels) == 1 {
did = append(did, "added label "+addLabels[0])
} else {
did = append(did, "added labels")
}
}
}
if len(removeLabels) > 0 {
for _, label := range removeLabels {
_, err := client.Issues.RemoveLabelForIssue(context.Background(), projectOwner, projectRepo, getInt(old.Number), label)
if err != nil {
fmt.Fprintf(&errbuf, "error removing label %s: %v\n", label, err)
failed = true
} else {
did = append(did, "removed label "+label)
}
}
}
if failed && len(did) > 0 {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%s", did[0])
for i := 1; i < len(did)-1; i++ {
fmt.Fprintf(&buf, ", %s", did[i])
}
if len(did) >= 2 {
if len(did) >= 3 {
fmt.Fprintf(&buf, ",")
}
fmt.Fprintf(&buf, " and %s", did[len(did)-1])
}
all := buf.Bytes()
all[0] -= 'a' - 'A'
fmt.Fprintf(&errbuf, "(%s successfully.)\n", all)
}
return
}
func diffList(line, field string, old []string) *[]string {
line = strings.TrimSpace(strings.TrimPrefix(line, field))
had := make(map[string]bool)
for _, f := range old {
had[f] = true
}
changes := false
for _, f := range strings.Fields(line) {
if !had[f] {
changes = true
}
delete(had, f)
}
if len(had) != 0 {
changes = true
}
if changes {
ret := strings.Fields(line)
if ret == nil {
ret = []string{}
}
return &ret
}
return nil
}
func diffList2(line, field string, old []string) (added, removed []string) {
line = strings.TrimSpace(strings.TrimPrefix(line, field))
had := make(map[string]bool)
for _, f := range old {
had[f] = true
}
for _, f := range strings.Fields(line) {
if !had[f] {
added = append(added, f)
}
delete(had, f)
}
if len(had) != 0 {
for _, f := range old {
if had[f] {
removed = append(removed, f)
}
}
}
return
}
func findMilestone(w io.Writer, name *string) *int {
if name == nil {
return nil
}
all, err := loadMilestones()
if err != nil {
fmt.Fprintf(w, "Error loading milestone list: %v\n\tIgnoring milestone change.\n", err)
return nil
}
for _, m := range all {
if getString(m.Title) == *name {
return m.Number
}
}
fmt.Fprintf(w, "Unknown milestone: %s\n", *name)
return nil
}
func readBulkIDs(text []byte) []int {
var ids []int
for _, line := range strings.Split(string(text), "\n") {
if i := strings.Index(line, "\t"); i >= 0 {
line = line[:i]
}
if i := strings.Index(line, " "); i >= 0 {
line = line[:i]
}
n, err := strconv.Atoi(line)
if err != nil {
continue
}
ids = append(ids, n)
}
return ids
}
func bulkEditStartFromText(content []byte) (base *github.Issue, original []byte, err error) {
ids := readBulkIDs(content)
if len(ids) == 0 {
return nil, nil, fmt.Errorf("found no issues in selection")
}
issues, err := bulkReadIssuesCached(ids)
if err != nil {
return nil, nil, err
}
base, original = bulkEditStart(issues)
return base, original, nil
}
func suffix(n int) string {
if n == 1 {
return ""
}
return "s"
}
func bulkEditIssues(issues []*github.Issue) {
base, original := bulkEditStart(issues)
updated := editText(original)
if bytes.Equal(original, updated) {
log.Print("no changes made")
return
}
ids, err := bulkWriteIssue(base, updated, func(s string) { log.Print(s) })
if err != nil {
errText := strings.Replace(err.Error(), "\n", "\t\n", -1)
if len(ids) > 0 {
log.Fatal("updated %d issue%s with errors:\n\t%v", len(ids), suffix(len(ids)), errText)
}
log.Fatal(errText)
}
log.Printf("updated %d issue%s", len(ids), suffix)
}
func bulkEditStart(issues []*github.Issue) (*github.Issue, []byte) {
common := new(github.Issue)
for i, issue := range issues {
if i == 0 {
common.State = issue.State
common.Assignee = issue.Assignee
common.Labels = issue.Labels
common.Milestone = issue.Milestone
continue
}
if common.State != nil && getString(common.State) != getString(issue.State) {
common.State = nil
}
if common.Assignee != nil && getUserLogin(common.Assignee) != getUserLogin(issue.Assignee) {
common.Assignee = nil
}
if common.Milestone != nil && getMilestoneTitle(common.Milestone) != getMilestoneTitle(issue.Milestone) {
common.Milestone = nil
}
common.Labels = commonLabels(common.Labels, issue.Labels)
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "State: %s\n", getString(common.State))
fmt.Fprintf(&buf, "Assignee: %s\n", getUserLogin(common.Assignee))
fmt.Fprintf(&buf, "Labels: %s\n", strings.Join(getLabelNames(common.Labels), " "))
fmt.Fprintf(&buf, "Milestone: %s\n", getMilestoneTitle(common.Milestone))
fmt.Fprintf(&buf, "\n<optional comment here>\n")
fmt.Fprintf(&buf, "%s\n", bulkHeader)
for _, issue := range issues {
fmt.Fprintf(&buf, "%d\t%s\n", getInt(issue.Number), getString(issue.Title))
}
return common, buf.Bytes()
}
func commonString(x, y string) string {
if x != y {
x = ""
}
return x
}
func commonLabels(x, y []github.Label) []github.Label {
if len(x) == 0 || len(y) == 0 {
return nil
}
have := make(map[string]bool)
for _, lab := range y {
have[getString(lab.Name)] = true
}
var out []github.Label
for _, lab := range x {
if have[getString(lab.Name)] {
out = append(out, lab)
}
}
return out
}
func bulkWriteIssue(old *github.Issue, updated []byte, status func(string)) (ids []int, err error) {
i := bytes.Index(updated, []byte(bulkHeader))
if i < 0 {
return nil, fmt.Errorf("cannot find bulk edit issue list")
}
ids = readBulkIDs(updated[i:])
if len(ids) == 0 {
return nil, fmt.Errorf("found no issues in bulk edit issue list")
}
// Make a copy of the issue to modify.
x := *old
old = &x
// Try a write to issue -1, checking for formatting only.
old.Number = new(int)
*old.Number = -1
if _, err := writeIssue(old, updated, true); err != nil {
return nil, err
}
// Apply to all issues in list.
suffix := ""
if len(ids) != 1 {
suffix = "s"
}
status(fmt.Sprintf("updating %d issue%s", len(ids), suffix))
failed := false
for index, number := range ids {
if index%10 == 0 && index > 0 {
status(fmt.Sprintf("updated %d/%d issues", index, len(ids)))
}
// Check rate limits here (in contrast to everywhere else in this program)
// to avoid needless failure halfway through the loop.
// for client.Rate.Limit > 0 && client.Rate.Remaining == 0 {
// delta := (client.Rate.Reset.Sub(time.Now())/time.Minute + 2) * time.Minute
{
delta := time.Duration(0)
if delta < 0 {
delta = 2 * time.Minute
}
status(fmt.Sprintf("updated %d/%d issues; pausing %d minutes to respect GitHub rate limit", index, len(ids), int(delta/time.Minute)))
time.Sleep(delta)
// API calls in github.Client now read rate limits themselves.
}
*old.Number = number
if _, err := writeIssue(old, updated, true); err != nil {
status(fmt.Sprintf("writing #%d: %s", number, strings.Replace(err.Error(), "\n", "\n\t", -1)))
failed = true
}
}
if failed {
return ids, fmt.Errorf("failed to update all issues")
}
return ids, nil
}