internal/control/issue.go
423 lines · 13902 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: issue create <owner/name> --title <t> [--body <b> | --file -]",
20 ReadsStdin: true, Run: runIssueCreate})
21 register(Command{Path: []string{"issue", "list"},
22 Summary: "list issues: issue list <owner/name> [--state open|closed|all]", ReadOnly: true, Run: runIssueList})
23 register(Command{Path: []string{"issue", "show"},
24 Summary: "show an issue with comments: issue show <owner/name> <n>", ReadOnly: true, Run: runIssueShow})
25 register(Command{Path: []string{"issue", "comment"},
26 Summary: "comment: issue comment <owner/name> <n> [--message <m> | --file -]",
27 ReadsStdin: true, Run: runIssueComment})
28 register(Command{Path: []string{"issue", "close"},
29 Summary: "close an issue: issue close <owner/name> <n>", Run: runIssueClose})
30 register(Command{Path: []string{"issue", "reopen"},
31 Summary: "reopen an issue: issue reopen <owner/name> <n>", Run: runIssueReopen})
32 register(Command{Path: []string{"issue", "label"},
33 Summary: "labels: issue label <owner/name> <n> [--add <l>]... [--remove <l>]...", Run: runIssueLabel})
34 register(Command{Path: []string{"issue", "assign"},
35 Summary: "assignees: issue assign <owner/name> <n> [--add <user>]... [--remove <user>]...", Run: runIssueAssign})
36}
37
38// issueArgs parses "<owner/name> <n>" plus flags handled by the caller.
39func issueRef(c *Ctx, args []string, perm func(store.User, store.Repo, string) bool) (store.Repo, store.Issue, int) {
40 if len(args) < 2 {
41 return store.Repo{}, store.Issue{}, c.fail(protocol.ExitUsage, "expected <owner/name> <number>")
42 }
43 repo, code := resolveRepo(c, args[0], perm)
44 if code >= 0 {
45 return repo, store.Issue{}, code
46 }
47 n, err := strconv.ParseInt(args[1], 10, 64)
48 if err != nil {
49 return repo, store.Issue{}, c.fail(protocol.ExitUsage, "bad issue number %q", args[1])
50 }
51 issue, err := c.Store.IssueByNumber(repo.ID, n)
52 if errors.Is(err, store.ErrNotFound) {
53 return repo, issue, c.fail(protocol.ExitNotFound, "issue #%d not found in %s", n, repo.Path())
54 }
55 if err != nil {
56 return repo, issue, c.fail(protocol.ExitFailure, "%v", err)
57 }
58 return repo, issue, -1
59}
60
61// bodyFrom resolves --body/--message inline text or --file - (stdin).
62func bodyFrom(c *Ctx, inline, file string) (string, error) {
63 if inline != "" && file != "" {
64 return "", errors.New("give either an inline message or --file -, not both")
65 }
66 if file != "" {
67 if file != "-" {
68 return "", errors.New("--file only supports - (stdin) over ssh")
69 }
70 raw, err := io.ReadAll(io.LimitReader(c.Stdin, maxBodyBytes))
71 return string(raw), err
72 }
73 return inline, nil
74}
75
76type issueOut struct {
77 Number int64 `json:"number"`
78 Title string `json:"title"`
79 State string `json:"state"`
80 Author string `json:"author"`
81 Labels []string `json:"labels,omitempty"`
82 Assignees []string `json:"assignees,omitempty"`
83 Body string `json:"body,omitempty"`
84 CreatedAt string `json:"created_at"`
85}
86
87func issueToOut(i store.Issue, withBody bool) issueOut {
88 o := issueOut{Number: i.Number, Title: i.Title, State: i.State, Author: i.Author,
89 Labels: i.Labels, Assignees: i.Assignees, CreatedAt: i.CreatedAt}
90 if withBody {
91 o.Body = i.Body
92 }
93 return o
94}
95
96func runIssueCreate(c *Ctx, args []string) int {
97 var path, title, body, file string
98 for i := 0; i < len(args); i++ {
99 switch args[i] {
100 case "--title":
101 if i+1 >= len(args) {
102 return c.fail(protocol.ExitUsage, "--title requires a value")
103 }
104 title = args[i+1]
105 i++
106 case "--body":
107 if i+1 >= len(args) {
108 return c.fail(protocol.ExitUsage, "--body requires a value")
109 }
110 body = args[i+1]
111 i++
112 case "--file":
113 if i+1 >= len(args) {
114 return c.fail(protocol.ExitUsage, "--file requires a value")
115 }
116 file = args[i+1]
117 i++
118 default:
119 if path != "" {
120 return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
121 }
122 path = args[i]
123 }
124 }
125 if path == "" || title == "" {
126 return c.fail(protocol.ExitUsage, "usage: issue create <owner/name> --title <t> [--body <b> | --file -]")
127 }
128 // Anyone who can read the repo can file an issue.
129 repo, code := resolveRepo(c, path, policy.CanRead)
130 if code >= 0 {
131 return code
132 }
133 b, err := bodyFrom(c, body, file)
134 if err != nil {
135 return c.fail(protocol.ExitUsage, "%v", err)
136 }
137 n, err := c.Store.CreateIssue(repo.ID, c.User.ID, title, b)
138 if err != nil {
139 return c.fail(protocol.ExitFailure, "%v", err)
140 }
141 c.Store.RecordEvent(repo.ID, c.User.ID, "issue.created", fmt.Sprintf(`{"number":%d}`, n))
142 if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
143 notifyUsers(c, targets, issueSubject(repo, n, title),
144 notifyBody(c, fmt.Sprintf("opened issue #%d", n), b, fmt.Sprintf("%s/issues/%d", repo.Path(), n)))
145 }
146 return c.emit(map[string]any{"number": n}, func(w io.Writer) {
147 fmt.Fprintf(w, "created %s#%d\n", repo.Path(), n)
148 })
149}
150
151func runIssueList(c *Ctx, args []string) int {
152 state := "open"
153 var path string
154 for i := 0; i < len(args); i++ {
155 switch args[i] {
156 case "--state":
157 if i+1 >= len(args) {
158 return c.fail(protocol.ExitUsage, "--state requires open|closed|all")
159 }
160 state = args[i+1]
161 i++
162 default:
163 if path != "" {
164 return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
165 }
166 path = args[i]
167 }
168 }
169 if path == "" || (state != "open" && state != "closed" && state != "all") {
170 return c.fail(protocol.ExitUsage, "usage: issue list <owner/name> [--state open|closed|all]")
171 }
172 repo, code := resolveRepo(c, path, policy.CanRead)
173 if code >= 0 {
174 return code
175 }
176 issues, err := c.Store.ListIssues(repo.ID, state)
177 if err != nil {
178 return c.fail(protocol.ExitFailure, "%v", err)
179 }
180 var ds []issueOut
181 for _, i := range issues {
182 ds = append(ds, issueToOut(i, false))
183 }
184 return c.emit(ds, func(w io.Writer) {
185 for _, d := range ds {
186 fmt.Fprintf(w, "#%d\t%s\t%s\t%s\n", d.Number, d.State, d.Title, d.Author)
187 }
188 })
189}
190
191func runIssueShow(c *Ctx, args []string) int {
192 repo, issue, code := issueRef(c, args, policy.CanRead)
193 if code >= 0 {
194 return code
195 }
196 if len(args) != 2 {
197 return c.fail(protocol.ExitUsage, "usage: issue show <owner/name> <n>")
198 }
199 comments, err := c.Store.ListIssueComments(issue.ID)
200 if err != nil {
201 return c.fail(protocol.ExitFailure, "%v", err)
202 }
203 type commentOut struct {
204 Author string `json:"author"`
205 Body string `json:"body"`
206 CreatedAt string `json:"created_at"`
207 }
208 var cs []commentOut
209 for _, cm := range comments {
210 cs = append(cs, commentOut{cm.Author, cm.Body, cm.CreatedAt})
211 }
212 d := struct {
213 issueOut
214 Comments []commentOut `json:"comments,omitempty"`
215 }{issueToOut(issue, true), cs}
216 _ = repo
217 return c.emit(d, func(w io.Writer) {
218 fmt.Fprintf(w, "#%d %s [%s] by %s\n", d.Number, d.Title, d.State, d.Author)
219 if len(d.Labels) > 0 {
220 fmt.Fprintf(w, "labels: %s\n", strings.Join(d.Labels, ", "))
221 }
222 if len(d.Assignees) > 0 {
223 fmt.Fprintf(w, "assignees: %s\n", strings.Join(d.Assignees, ", "))
224 }
225 if d.Body != "" {
226 fmt.Fprintf(w, "\n%s\n", d.Body)
227 }
228 for _, cm := range cs {
229 fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
230 }
231 })
232}
233
234func runIssueComment(c *Ctx, args []string) int {
235 var rest []string
236 var message, file string
237 for i := 0; i < len(args); i++ {
238 switch args[i] {
239 case "--message":
240 if i+1 >= len(args) {
241 return c.fail(protocol.ExitUsage, "--message requires a value")
242 }
243 message = args[i+1]
244 i++
245 case "--file":
246 if i+1 >= len(args) {
247 return c.fail(protocol.ExitUsage, "--file requires a value")
248 }
249 file = args[i+1]
250 i++
251 default:
252 rest = append(rest, args[i])
253 }
254 }
255 repo, issue, code := issueRef(c, rest, policy.CanRead)
256 if code >= 0 {
257 return code
258 }
259 body, err := bodyFrom(c, message, file)
260 if err != nil {
261 return c.fail(protocol.ExitUsage, "%v", err)
262 }
263 if strings.TrimSpace(body) == "" {
264 return c.fail(protocol.ExitUsage, "empty comment; use --message or --file -")
265 }
266 if err := c.Store.AddIssueComment(issue.ID, c.User.ID, body); err != nil {
267 return c.fail(protocol.ExitFailure, "%v", err)
268 }
269 c.Store.RecordEvent(repo.ID, c.User.ID, "issue.commented", fmt.Sprintf(`{"number":%d}`, issue.Number))
270 if parts, err := c.Store.IssueParticipants(issue.ID); err == nil {
271 notifyUsers(c, parts, issueSubject(repo, issue.Number, issue.Title),
272 notifyBody(c, fmt.Sprintf("commented on #%d", issue.Number), body, fmt.Sprintf("%s/issues/%d", repo.Path(), issue.Number)))
273 }
274 return c.emit(map[string]any{"number": issue.Number}, func(w io.Writer) {
275 fmt.Fprintf(w, "commented on %s#%d\n", repo.Path(), issue.Number)
276 })
277}
278
279func setIssueState(c *Ctx, args []string, state string) int {
280 // Author may close/reopen their own issue; otherwise write access.
281 repo, issue, code := issueRef(c, args, policy.CanRead)
282 if code >= 0 {
283 return code
284 }
285 if len(args) != 2 {
286 return c.fail(protocol.ExitUsage, "usage: issue %s <owner/name> <n>", state)
287 }
288 grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
289 if err != nil {
290 return c.fail(protocol.ExitFailure, "%v", err)
291 }
292 if issue.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
293 return c.fail(protocol.ExitDenied, "only the author or users with write access can %s this issue",
294 map[string]string{"open": "reopen", "closed": "close"}[state])
295 }
296 if issue.State == state {
297 return c.fail(protocol.ExitUsage, "issue #%d is already %s", issue.Number, state)
298 }
299 if err := c.Store.SetIssueState(issue.ID, state); err != nil {
300 return c.fail(protocol.ExitFailure, "%v", err)
301 }
302 c.Store.RecordEvent(repo.ID, c.User.ID, "issue."+state, fmt.Sprintf(`{"number":%d}`, issue.Number))
303 if parts, err := c.Store.IssueParticipants(issue.ID); err == nil {
304 verb := map[string]string{"open": "reopened", "closed": "closed"}[state]
305 notifyUsers(c, parts, issueSubject(repo, issue.Number, issue.Title),
306 notifyBody(c, fmt.Sprintf("%s #%d", verb, issue.Number), "", fmt.Sprintf("%s/issues/%d", repo.Path(), issue.Number)))
307 }
308 return c.emit(map[string]any{"number": issue.Number, "state": state}, func(w io.Writer) {
309 fmt.Fprintf(w, "%s#%d is now %s\n", repo.Path(), issue.Number, state)
310 })
311}
312
313func runIssueClose(c *Ctx, args []string) int { return setIssueState(c, args, "closed") }
314func runIssueReopen(c *Ctx, args []string) int { return setIssueState(c, args, "open") }
315
316// addRemoveFlags parses repeated --add/--remove flags.
317func addRemoveFlags(args []string) (rest, adds, removes []string, err error) {
318 for i := 0; i < len(args); i++ {
319 switch args[i] {
320 case "--add":
321 if i+1 >= len(args) {
322 return nil, nil, nil, errors.New("--add requires a value")
323 }
324 adds = append(adds, args[i+1])
325 i++
326 case "--remove":
327 if i+1 >= len(args) {
328 return nil, nil, nil, errors.New("--remove requires a value")
329 }
330 removes = append(removes, args[i+1])
331 i++
332 default:
333 rest = append(rest, args[i])
334 }
335 }
336 return rest, adds, removes, nil
337}
338
339func runIssueLabel(c *Ctx, args []string) int {
340 rest, adds, removes, err := addRemoveFlags(args)
341 if err != nil {
342 return c.fail(protocol.ExitUsage, "%v", err)
343 }
344 if len(adds)+len(removes) == 0 {
345 return c.fail(protocol.ExitUsage, "usage: issue label <owner/name> <n> [--add <l>]... [--remove <l>]...")
346 }
347 repo, issue, code := issueRef(c, rest, policy.CanWrite)
348 if code >= 0 {
349 return code
350 }
351 for _, l := range adds {
352 if err := c.Store.SetIssueLabel(repo.ID, issue.ID, l, true); err != nil {
353 return c.fail(protocol.ExitFailure, "%v", err)
354 }
355 }
356 for _, l := range removes {
357 if err := c.Store.SetIssueLabel(repo.ID, issue.ID, l, false); err != nil {
358 if errors.Is(err, store.ErrNotFound) {
359 return c.fail(protocol.ExitNotFound, "%v", err)
360 }
361 return c.fail(protocol.ExitFailure, "%v", err)
362 }
363 }
364 updated, err := c.Store.IssueByNumber(repo.ID, issue.Number)
365 if err != nil {
366 return c.fail(protocol.ExitFailure, "%v", err)
367 }
368 return c.emit(map[string]any{"number": issue.Number, "labels": updated.Labels}, func(w io.Writer) {
369 fmt.Fprintf(w, "labels on %s#%d: %s\n", repo.Path(), issue.Number, strings.Join(updated.Labels, ", "))
370 })
371}
372
373func runIssueAssign(c *Ctx, args []string) int {
374 rest, adds, removes, err := addRemoveFlags(args)
375 if err != nil {
376 return c.fail(protocol.ExitUsage, "%v", err)
377 }
378 if len(adds)+len(removes) == 0 {
379 return c.fail(protocol.ExitUsage, "usage: issue assign <owner/name> <n> [--add <user>]... [--remove <user>]...")
380 }
381 repo, issue, code := issueRef(c, rest, policy.CanWrite)
382 if code >= 0 {
383 return code
384 }
385 resolve := func(name string) (store.User, int) {
386 u, err := c.Store.UserByUsername(name)
387 if errors.Is(err, store.ErrNotFound) {
388 return u, c.fail(protocol.ExitNotFound, "no such user %q", name)
389 }
390 if err != nil {
391 return u, c.fail(protocol.ExitFailure, "%v", err)
392 }
393 return u, -1
394 }
395 for _, name := range adds {
396 u, code := resolve(name)
397 if code >= 0 {
398 return code
399 }
400 if err := c.Store.SetIssueAssignee(issue.ID, u.ID, true); err != nil {
401 return c.fail(protocol.ExitFailure, "%v", err)
402 }
403 }
404 for _, name := range removes {
405 u, code := resolve(name)
406 if code >= 0 {
407 return code
408 }
409 if err := c.Store.SetIssueAssignee(issue.ID, u.ID, false); err != nil {
410 if errors.Is(err, store.ErrNotFound) {
411 return c.fail(protocol.ExitNotFound, "%s is not assigned", name)
412 }
413 return c.fail(protocol.ExitFailure, "%v", err)
414 }
415 }
416 updated, err := c.Store.IssueByNumber(repo.ID, issue.Number)
417 if err != nil {
418 return c.fail(protocol.ExitFailure, "%v", err)
419 }
420 return c.emit(map[string]any{"number": issue.Number, "assignees": updated.Assignees}, func(w io.Writer) {
421 fmt.Fprintf(w, "assignees on %s#%d: %s\n", repo.Path(), issue.Number, strings.Join(updated.Assignees, ", "))
422 })
423}