internal/control/issue.go
583 lines · 18715 bytes
1package control
2
3import (
4 "errors"
5 "fmt"
6 "io"
7 "strconv"
8 "strings"
9
10 "gitbay.org/gitbay/internal/policy"
11 "gitbay.org/gitbay/internal/protocol"
12 "gitbay.org/gitbay/internal/store"
13)
14
15const maxBodyBytes = 64 << 10
16
17func init() {
18 register(Command{Path: []string{"issue", "create"},
19 Summary: "open an issue",
20 Usage: "issue create <owner/name> --title <t> [--body <b> | --file -] [--format md|org]",
21 ReadsStdin: true, Run: runIssueCreate})
22 register(Command{Path: []string{"issue", "list"},
23 Summary: "list issues",
24 Usage: "issue list <owner/name> [--state open|closed|all] [--limit <n>] [--cursor <c>]", ReadOnly: true, Run: runIssueList})
25 register(Command{Path: []string{"issue", "show"},
26 Summary: "show an issue with comments",
27 Usage: "issue show <owner/name> <n>", ReadOnly: true, Run: runIssueShow})
28 register(Command{Path: []string{"issue", "edit"},
29 Summary: "edit title or body",
30 Usage: "issue edit <owner/name> <n> [--title <t>] [--body <b> | --file -] [--format md|org]",
31 ReadsStdin: true, Run: runIssueEdit})
32 register(Command{Path: []string{"issue", "comment"},
33 Summary: "comment",
34 Usage: "issue comment <owner/name> <n> [--message <m> | --file -] [--format md|org]",
35 ReadsStdin: true, Run: runIssueComment})
36 register(Command{Path: []string{"issue", "close"},
37 Summary: "close an issue",
38 Usage: "issue close <owner/name> <n>", Run: runIssueClose})
39 register(Command{Path: []string{"issue", "reopen"},
40 Summary: "reopen an issue",
41 Usage: "issue reopen <owner/name> <n>", Run: runIssueReopen})
42 register(Command{Path: []string{"issue", "label"},
43 Summary: "labels",
44 Usage: "issue label <owner/name> <n> [--add <l>]... [--remove <l>]...", Run: runIssueLabel})
45 register(Command{Path: []string{"issue", "assign"},
46 Summary: "assignees",
47 Usage: "issue assign <owner/name> <n> [--add <user>]... [--remove <user>]...", Run: runIssueAssign})
48}
49
50// issueArgs parses "<owner/name> <n>" plus flags handled by the caller.
51func issueRef(c *Ctx, args []string, perm func(store.User, store.Repo, string) bool) (store.Repo, store.Issue, int) {
52 if len(args) < 2 {
53 return store.Repo{}, store.Issue{}, c.fail(protocol.ExitUsage, "expected <owner/name> <number>")
54 }
55 repo, code := resolveRepo(c, args[0], perm)
56 if code >= 0 {
57 return repo, store.Issue{}, code
58 }
59 n, err := strconv.ParseInt(args[1], 10, 64)
60 if err != nil {
61 return repo, store.Issue{}, c.fail(protocol.ExitUsage, "bad issue number %q", args[1])
62 }
63 issue, err := c.Store.IssueByNumber(repo.ID, n)
64 if errors.Is(err, store.ErrNotFound) {
65 return repo, issue, c.fail(protocol.ExitNotFound, "issue #%d not found in %s", n, repo.Path())
66 }
67 if err != nil {
68 return repo, issue, c.fail(protocol.ExitFailure, "%v", err)
69 }
70 return repo, issue, -1
71}
72
73// bodyFrom resolves --body/--message inline text or --file - (stdin).
74func bodyFrom(c *Ctx, inline, file string) (string, error) {
75 if inline != "" && file != "" {
76 return "", errors.New("give either an inline message or --file -, not both")
77 }
78 if file != "" {
79 if file != "-" {
80 return "", errors.New("--file only supports - (stdin) over ssh")
81 }
82 raw, err := io.ReadAll(io.LimitReader(c.Stdin, maxBodyBytes))
83 return string(raw), err
84 }
85 return inline, nil
86}
87
88// markupFormat normalizes a --format value. Empty means the caller did not ask,
89// which the caller turns into "md" on create or "unchanged" on edit.
90func markupFormat(v string) (string, error) {
91 switch strings.ToLower(strings.TrimSpace(v)) {
92 case "":
93 return "", nil
94 case "md", "markdown":
95 return "md", nil
96 case "org", "org-mode":
97 return "org", nil
98 }
99 return "", fmt.Errorf("unknown --format %q (want md or org)", v)
100}
101
102type issueOut struct {
103 Number int64 `json:"number"`
104 Title string `json:"title"`
105 State string `json:"state"`
106 Author string `json:"author"`
107 Milestone string `json:"milestone,omitempty"`
108 Labels []string `json:"labels,omitempty"`
109 Assignees []string `json:"assignees,omitempty"`
110 Body string `json:"body,omitempty"`
111 BodyFormat string `json:"body_format,omitempty"`
112 CreatedAt string `json:"created_at"`
113}
114
115func issueToOut(i store.Issue, withBody bool) issueOut {
116 o := issueOut{Number: i.Number, Title: i.Title, State: i.State, Author: i.Author,
117 Milestone: i.Milestone, Labels: i.Labels, Assignees: i.Assignees, CreatedAt: i.CreatedAt}
118 if withBody {
119 o.Body = i.Body
120 o.BodyFormat = i.BodyFormat
121 }
122 return o
123}
124
125func runIssueCreate(c *Ctx, args []string) int {
126 var path, title, body, file, format string
127 for i := 0; i < len(args); i++ {
128 switch args[i] {
129 case "--format":
130 if i+1 >= len(args) {
131 return c.fail(protocol.ExitUsage, "--format requires a value")
132 }
133 format = args[i+1]
134 i++
135 case "--title":
136 if i+1 >= len(args) {
137 return c.fail(protocol.ExitUsage, "--title requires a value")
138 }
139 title = args[i+1]
140 i++
141 case "--body":
142 if i+1 >= len(args) {
143 return c.fail(protocol.ExitUsage, "--body requires a value")
144 }
145 body = args[i+1]
146 i++
147 case "--file":
148 if i+1 >= len(args) {
149 return c.fail(protocol.ExitUsage, "--file requires a value")
150 }
151 file = args[i+1]
152 i++
153 default:
154 if path != "" {
155 return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
156 }
157 path = args[i]
158 }
159 }
160 if path == "" || title == "" {
161 return c.fail(protocol.ExitUsage, "usage: issue create <owner/name> --title <t> [--body <b> | --file -] [--format md|org]")
162 }
163 fmtName, err := markupFormat(format)
164 if err != nil {
165 return c.fail(protocol.ExitUsage, "%v", err)
166 }
167 if fmtName == "" {
168 fmtName = "md"
169 }
170 // Anyone who can read the repo can file an issue.
171 repo, code := resolveRepo(c, path, policy.CanRead)
172 if code >= 0 {
173 return code
174 }
175 if code := refuseArchived(c, repo); code >= 0 {
176 return code
177 }
178 b, err := bodyFrom(c, body, file)
179 if err != nil {
180 return c.fail(protocol.ExitUsage, "%v", err)
181 }
182 n, err := c.Store.CreateIssue(repo.ID, c.User.ID, title, b, fmtName)
183 if err != nil {
184 return c.fail(protocol.ExitFailure, "%v", err)
185 }
186 c.Store.RecordEvent(repo.ID, c.User.ID, "issue.created", fmt.Sprintf(`{"number":%d}`, n))
187 if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
188 notifyUsers(c, targets, issueSubject(repo, n, title),
189 notifyBody(c, fmt.Sprintf("opened issue #%d", n), b, fmt.Sprintf("%s/issues/%d", repo.Path(), n)))
190 }
191 return c.emit(map[string]any{"number": n}, func(w io.Writer) {
192 fmt.Fprintf(w, "created %s#%d\n", repo.Path(), n)
193 })
194}
195
196func runIssueList(c *Ctx, args []string) int {
197 args, p, code := parsePageFlags(c, args, "issue", true)
198 if code >= 0 {
199 return code
200 }
201 state := "open"
202 var path string
203 for i := 0; i < len(args); i++ {
204 switch args[i] {
205 case "--state":
206 if i+1 >= len(args) {
207 return c.fail(protocol.ExitUsage, "--state requires open|closed|all")
208 }
209 state = args[i+1]
210 i++
211 default:
212 if path != "" {
213 return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
214 }
215 path = args[i]
216 }
217 }
218 if path == "" || (state != "open" && state != "closed" && state != "all") {
219 return c.fail(protocol.ExitUsage, "usage: issue list <owner/name> [--state open|closed|all] [--limit <n>] [--cursor <c>]")
220 }
221 repo, code := resolveRepo(c, path, policy.CanRead)
222 if code >= 0 {
223 return code
224 }
225 issues, err := c.Store.ListIssues(repo.ID, state, p.queryLimit(), p.keyInt())
226 if err != nil {
227 return c.fail(protocol.ExitFailure, "%v", err)
228 }
229 issues, next := trimPage(p, issues, "issue", func(i store.Issue) string {
230 return strconv.FormatInt(i.Number, 10)
231 })
232 var ds []issueOut
233 for _, i := range issues {
234 ds = append(ds, issueToOut(i, false))
235 }
236 return c.emitPage(p, ds, next, func(w io.Writer) {
237 for _, d := range ds {
238 fmt.Fprintf(w, "#%d\t%s\t%s\t%s\n", d.Number, d.State, d.Title, d.Author)
239 }
240 })
241}
242
243func runIssueShow(c *Ctx, args []string) int {
244 repo, issue, code := issueRef(c, args, policy.CanRead)
245 if code >= 0 {
246 return code
247 }
248 if len(args) != 2 {
249 return c.fail(protocol.ExitUsage, "usage: issue show <owner/name> <n>")
250 }
251 comments, err := c.Store.ListIssueComments(issue.ID)
252 if err != nil {
253 return c.fail(protocol.ExitFailure, "%v", err)
254 }
255 type commentOut struct {
256 Author string `json:"author"`
257 Body string `json:"body"`
258 BodyFormat string `json:"body_format,omitempty"`
259 CreatedAt string `json:"created_at"`
260 }
261 var cs []commentOut
262 for _, cm := range comments {
263 cs = append(cs, commentOut{cm.Author, cm.Body, cm.BodyFormat, cm.CreatedAt})
264 }
265 d := struct {
266 issueOut
267 Comments []commentOut `json:"comments,omitempty"`
268 }{issueToOut(issue, true), cs}
269 _ = repo
270 return c.emit(d, func(w io.Writer) {
271 fmt.Fprintf(w, "#%d %s [%s] by %s\n", d.Number, d.Title, d.State, d.Author)
272 if len(d.Labels) > 0 {
273 fmt.Fprintf(w, "labels: %s\n", strings.Join(d.Labels, ", "))
274 }
275 if len(d.Assignees) > 0 {
276 fmt.Fprintf(w, "assignees: %s\n", strings.Join(d.Assignees, ", "))
277 }
278 if d.Body != "" {
279 fmt.Fprintf(w, "\n%s\n", d.Body)
280 }
281 for _, cm := range cs {
282 fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
283 }
284 })
285}
286
287func runIssueComment(c *Ctx, args []string) int {
288 var rest []string
289 var message, file, format string
290 for i := 0; i < len(args); i++ {
291 switch args[i] {
292 case "--format":
293 if i+1 >= len(args) {
294 return c.fail(protocol.ExitUsage, "--format requires a value")
295 }
296 format = args[i+1]
297 i++
298 case "--message":
299 if i+1 >= len(args) {
300 return c.fail(protocol.ExitUsage, "--message requires a value")
301 }
302 message = args[i+1]
303 i++
304 case "--file":
305 if i+1 >= len(args) {
306 return c.fail(protocol.ExitUsage, "--file requires a value")
307 }
308 file = args[i+1]
309 i++
310 default:
311 rest = append(rest, args[i])
312 }
313 }
314 fmtName, err := markupFormat(format)
315 if err != nil {
316 return c.fail(protocol.ExitUsage, "%v", err)
317 }
318 if fmtName == "" {
319 fmtName = "md"
320 }
321 repo, issue, code := issueRef(c, rest, policy.CanRead)
322 if code >= 0 {
323 return code
324 }
325 if code := refuseArchived(c, repo); code >= 0 {
326 return code
327 }
328 body, err := bodyFrom(c, message, file)
329 if err != nil {
330 return c.fail(protocol.ExitUsage, "%v", err)
331 }
332 if strings.TrimSpace(body) == "" {
333 return c.fail(protocol.ExitUsage, "empty comment; use --message or --file -")
334 }
335 if err := c.Store.AddIssueComment(issue.ID, c.User.ID, body, fmtName); err != nil {
336 return c.fail(protocol.ExitFailure, "%v", err)
337 }
338 c.Store.RecordEvent(repo.ID, c.User.ID, "issue.commented", fmt.Sprintf(`{"number":%d}`, issue.Number))
339 if parts, err := c.Store.IssueParticipants(issue.ID); err == nil {
340 notifyUsers(c, parts, issueSubject(repo, issue.Number, issue.Title),
341 notifyBody(c, fmt.Sprintf("commented on #%d", issue.Number), body, fmt.Sprintf("%s/issues/%d", repo.Path(), issue.Number)))
342 }
343 return c.emit(map[string]any{"number": issue.Number}, func(w io.Writer) {
344 fmt.Fprintf(w, "commented on %s#%d\n", repo.Path(), issue.Number)
345 })
346}
347
348func setIssueState(c *Ctx, args []string, state string) int {
349 // Author may close/reopen their own issue; otherwise write access.
350 repo, issue, code := issueRef(c, args, policy.CanRead)
351 if code >= 0 {
352 return code
353 }
354 if code := refuseArchived(c, repo); code >= 0 {
355 return code
356 }
357 if len(args) != 2 {
358 return c.fail(protocol.ExitUsage, "usage: issue %s <owner/name> <n>", state)
359 }
360 grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
361 if err != nil {
362 return c.fail(protocol.ExitFailure, "%v", err)
363 }
364 if issue.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
365 return c.fail(protocol.ExitDenied, "only the author or users with write access can %s this issue",
366 map[string]string{"open": "reopen", "closed": "close"}[state])
367 }
368 if issue.State == state {
369 return c.fail(protocol.ExitUsage, "issue #%d is already %s", issue.Number, state)
370 }
371 if err := c.Store.SetIssueState(issue.ID, state); err != nil {
372 return c.fail(protocol.ExitFailure, "%v", err)
373 }
374 c.Store.RecordEvent(repo.ID, c.User.ID, "issue."+state, fmt.Sprintf(`{"number":%d}`, issue.Number))
375 if parts, err := c.Store.IssueParticipants(issue.ID); err == nil {
376 verb := map[string]string{"open": "reopened", "closed": "closed"}[state]
377 notifyUsers(c, parts, issueSubject(repo, issue.Number, issue.Title),
378 notifyBody(c, fmt.Sprintf("%s #%d", verb, issue.Number), "", fmt.Sprintf("%s/issues/%d", repo.Path(), issue.Number)))
379 }
380 return c.emit(map[string]any{"number": issue.Number, "state": state}, func(w io.Writer) {
381 fmt.Fprintf(w, "%s#%d is now %s\n", repo.Path(), issue.Number, state)
382 })
383}
384
385// editText parses --title/--body/--file -/--format and authorizes: author or
386// write. A nil format means the stored markup format stays as it is.
387func editText(c *Ctx, args []string, kind string) (rest []string, title, body, format *string, code int) {
388 var titleV, bodyV, file, formatV string
389 haveTitle, haveBody := false, false
390 for i := 0; i < len(args); i++ {
391 switch args[i] {
392 case "--title", "--body", "--file", "--format":
393 if i+1 >= len(args) {
394 return nil, nil, nil, nil, c.fail(protocol.ExitUsage, "%s requires a value", args[i])
395 }
396 switch args[i] {
397 case "--title":
398 titleV, haveTitle = args[i+1], true
399 case "--body":
400 bodyV, haveBody = args[i+1], true
401 case "--file":
402 file = args[i+1]
403 case "--format":
404 formatV = args[i+1]
405 }
406 i++
407 default:
408 rest = append(rest, args[i])
409 }
410 }
411 if file != "" {
412 b, err := bodyFrom(c, "", file)
413 if err != nil {
414 return nil, nil, nil, nil, c.fail(protocol.ExitUsage, "%v", err)
415 }
416 bodyV, haveBody = b, true
417 }
418 fmtName, err := markupFormat(formatV)
419 if err != nil {
420 return nil, nil, nil, nil, c.fail(protocol.ExitUsage, "%v", err)
421 }
422 if !haveTitle && !haveBody && fmtName == "" {
423 return nil, nil, nil, nil, c.fail(protocol.ExitUsage, "usage: %s edit <owner/name> <n> [--title <t>] [--body <b> | --file -] [--format md|org]", kind)
424 }
425 if haveTitle {
426 if strings.TrimSpace(titleV) == "" {
427 return nil, nil, nil, nil, c.fail(protocol.ExitUsage, "--title must not be empty")
428 }
429 title = &titleV
430 }
431 if haveBody {
432 body = &bodyV
433 }
434 if fmtName != "" {
435 format = &fmtName
436 }
437 return rest, title, body, format, -1
438}
439
440func runIssueEdit(c *Ctx, args []string) int {
441 rest, title, body, format, code := editText(c, args, "issue")
442 if code >= 0 {
443 return code
444 }
445 repo, issue, code := issueRef(c, rest, policy.CanRead)
446 if code >= 0 {
447 return code
448 }
449 if code := refuseArchived(c, repo); code >= 0 {
450 return code
451 }
452 grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
453 if err != nil {
454 return c.fail(protocol.ExitFailure, "%v", err)
455 }
456 if issue.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
457 return c.fail(protocol.ExitDenied, "only the author or users with write access can edit this issue")
458 }
459 if err := c.Store.UpdateIssueText(issue.ID, title, body, format); err != nil {
460 return c.fail(protocol.ExitFailure, "%v", err)
461 }
462 return c.emit(map[string]any{"number": issue.Number}, func(w io.Writer) {
463 fmt.Fprintf(w, "edited %s#%d\n", repo.Path(), issue.Number)
464 })
465}
466
467func runIssueClose(c *Ctx, args []string) int { return setIssueState(c, args, "closed") }
468func runIssueReopen(c *Ctx, args []string) int { return setIssueState(c, args, "open") }
469
470// addRemoveFlags parses repeated --add/--remove flags.
471func addRemoveFlags(args []string) (rest, adds, removes []string, err error) {
472 for i := 0; i < len(args); i++ {
473 switch args[i] {
474 case "--add":
475 if i+1 >= len(args) {
476 return nil, nil, nil, errors.New("--add requires a value")
477 }
478 adds = append(adds, args[i+1])
479 i++
480 case "--remove":
481 if i+1 >= len(args) {
482 return nil, nil, nil, errors.New("--remove requires a value")
483 }
484 removes = append(removes, args[i+1])
485 i++
486 default:
487 rest = append(rest, args[i])
488 }
489 }
490 return rest, adds, removes, nil
491}
492
493func runIssueLabel(c *Ctx, args []string) int {
494 rest, adds, removes, err := addRemoveFlags(args)
495 if err != nil {
496 return c.fail(protocol.ExitUsage, "%v", err)
497 }
498 if len(adds)+len(removes) == 0 {
499 return c.fail(protocol.ExitUsage, "usage: issue label <owner/name> <n> [--add <l>]... [--remove <l>]...")
500 }
501 repo, issue, code := issueRef(c, rest, policy.CanWrite)
502 if code >= 0 {
503 return code
504 }
505 if code := refuseArchived(c, repo); code >= 0 {
506 return code
507 }
508 for _, l := range adds {
509 if err := c.Store.SetIssueLabel(repo.ID, issue.ID, l, true); err != nil {
510 return c.fail(protocol.ExitFailure, "%v", err)
511 }
512 }
513 for _, l := range removes {
514 if err := c.Store.SetIssueLabel(repo.ID, issue.ID, l, false); err != nil {
515 if errors.Is(err, store.ErrNotFound) {
516 return c.fail(protocol.ExitNotFound, "%v", err)
517 }
518 return c.fail(protocol.ExitFailure, "%v", err)
519 }
520 }
521 updated, err := c.Store.IssueByNumber(repo.ID, issue.Number)
522 if err != nil {
523 return c.fail(protocol.ExitFailure, "%v", err)
524 }
525 return c.emit(map[string]any{"number": issue.Number, "labels": updated.Labels}, func(w io.Writer) {
526 fmt.Fprintf(w, "labels on %s#%d: %s\n", repo.Path(), issue.Number, strings.Join(updated.Labels, ", "))
527 })
528}
529
530func runIssueAssign(c *Ctx, args []string) int {
531 rest, adds, removes, err := addRemoveFlags(args)
532 if err != nil {
533 return c.fail(protocol.ExitUsage, "%v", err)
534 }
535 if len(adds)+len(removes) == 0 {
536 return c.fail(protocol.ExitUsage, "usage: issue assign <owner/name> <n> [--add <user>]... [--remove <user>]...")
537 }
538 repo, issue, code := issueRef(c, rest, policy.CanWrite)
539 if code >= 0 {
540 return code
541 }
542 if code := refuseArchived(c, repo); code >= 0 {
543 return code
544 }
545 resolve := func(name string) (store.User, int) {
546 u, err := c.Store.UserByUsername(name)
547 if errors.Is(err, store.ErrNotFound) {
548 return u, c.fail(protocol.ExitNotFound, "no such user %q", name)
549 }
550 if err != nil {
551 return u, c.fail(protocol.ExitFailure, "%v", err)
552 }
553 return u, -1
554 }
555 for _, name := range adds {
556 u, code := resolve(name)
557 if code >= 0 {
558 return code
559 }
560 if err := c.Store.SetIssueAssignee(issue.ID, u.ID, true); err != nil {
561 return c.fail(protocol.ExitFailure, "%v", err)
562 }
563 }
564 for _, name := range removes {
565 u, code := resolve(name)
566 if code >= 0 {
567 return code
568 }
569 if err := c.Store.SetIssueAssignee(issue.ID, u.ID, false); err != nil {
570 if errors.Is(err, store.ErrNotFound) {
571 return c.fail(protocol.ExitNotFound, "%s is not assigned", name)
572 }
573 return c.fail(protocol.ExitFailure, "%v", err)
574 }
575 }
576 updated, err := c.Store.IssueByNumber(repo.ID, issue.Number)
577 if err != nil {
578 return c.fail(protocol.ExitFailure, "%v", err)
579 }
580 return c.emit(map[string]any{"number": issue.Number, "assignees": updated.Assignees}, func(w io.Writer) {
581 fmt.Fprintf(w, "assignees on %s#%d: %s\n", repo.Path(), issue.Number, strings.Join(updated.Assignees, ", "))
582 })
583}