internal/control/issue.go

7effe3feb4612cffb5ed38c02300299559aa8971
gitbay/internal/control/issue.go history · blame · raw

445 lines · 15734 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] [--label <l>] [--assignee <user>] [--author <user>] [--milestone <title>|none] [--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	repo, n, code := refArgs(c, args, perm, "issue")
 53	if code >= 0 {
 54		return repo, store.Issue{}, code
 55	}
 56	issue, err := c.Store.IssueByNumber(repo.ID, n)
 57	if errors.Is(err, store.ErrNotFound) {
 58		return repo, issue, c.fail(protocol.ExitNotFound, "issue #%d not found in %s", n, repo.Path())
 59	}
 60	if err != nil {
 61		return repo, issue, c.fail(protocol.ExitFailure, "%v", err)
 62	}
 63	return repo, issue, -1
 64}
 65
 66// bodyFrom resolves --body/--message inline text or --file - (stdin).
 67func bodyFrom(c *Ctx, inline, file string) (string, error) {
 68	if inline != "" && file != "" {
 69		return "", errors.New("give either an inline message or --file -, not both")
 70	}
 71	if file != "" {
 72		if file != "-" {
 73			return "", errors.New("--file only supports - (stdin) over ssh")
 74		}
 75		raw, err := io.ReadAll(io.LimitReader(c.Stdin, maxBodyBytes))
 76		return string(raw), err
 77	}
 78	return inline, nil
 79}
 80
 81// markupFormat normalizes a --format value. Empty means the caller did not ask,
 82// which the caller turns into "md" on create or "unchanged" on edit.
 83func markupFormat(v string) (string, error) {
 84	switch strings.ToLower(strings.TrimSpace(v)) {
 85	case "":
 86		return "", nil
 87	case "md", "markdown":
 88		return "md", nil
 89	case "org", "org-mode":
 90		return "org", nil
 91	}
 92	return "", fmt.Errorf("unknown --format %q (want md or org)", v)
 93}
 94
 95type issueOut struct {
 96	Number     int64    `json:"number"`
 97	Title      string   `json:"title"`
 98	State      string   `json:"state"`
 99	Author     string   `json:"author"`
100	Milestone  string   `json:"milestone,omitempty"`
101	Labels     []string `json:"labels,omitempty"`
102	Assignees  []string `json:"assignees,omitempty"`
103	Body       string   `json:"body,omitempty"`
104	BodyFormat string   `json:"body_format,omitempty"`
105	CreatedAt  string   `json:"created_at"`
106}
107
108func issueToOut(i store.Issue, withBody bool) issueOut {
109	o := issueOut{Number: i.Number, Title: i.Title, State: i.State, Author: i.Author,
110		Milestone: i.Milestone, Labels: i.Labels, Assignees: i.Assignees, CreatedAt: i.CreatedAt}
111	if withBody {
112		o.Body = i.Body
113		o.BodyFormat = i.BodyFormat
114	}
115	return o
116}
117
118func runIssueCreate(c *Ctx, args []string) int {
119	f, err := parseFlags(args, flagSpec{Values: []string{"--format", "--title", "--body", "--file"}, MaxPos: 1,
120		Usage: "issue create <owner/name> --title <t> [--body <b> | --file -] [--format md|org]"})
121	if err != nil {
122		return c.fail(protocol.ExitUsage, "%v", err)
123	}
124	path, title, body, file, format := f.pos(0), f.Value("--title"), f.Value("--body"), f.Value("--file"), f.Value("--format")
125	if path == "" || title == "" {
126		return c.fail(protocol.ExitUsage, "usage: issue create <owner/name> --title <t> [--body <b> | --file -] [--format md|org]")
127	}
128	fmtName, err := markupFormat(format)
129	if err != nil {
130		return c.failErr(err)
131	}
132	if fmtName == "" {
133		fmtName = "md"
134	}
135	// Anyone who can read the repo can file an issue.
136	repo, code := resolveRepo(c, path, policy.CanRead)
137	if code >= 0 {
138		return code
139	}
140	if code := refuseArchived(c, repo); code >= 0 {
141		return code
142	}
143	b, err := bodyFrom(c, body, file)
144	if err != nil {
145		return c.failErr(err)
146	}
147	n, err := c.Store.CreateIssue(repo.ID, c.User.ID, title, b, fmtName)
148	if err != nil {
149		return c.fail(protocol.ExitFailure, "%v", err)
150	}
151	c.Store.RecordEvent(repo.ID, c.User.ID, "issue.created", fmt.Sprintf(`{"number":%d}`, n))
152	if targets, err := c.Store.RepoNotifyTargets(repo); err == nil {
153		notifyUsers(c, targets, issueSubject(repo, n, title),
154			notifyBody(c, fmt.Sprintf("opened issue #%d", n), b, fmt.Sprintf("%s/issues/%d", repo.Path(), n)))
155	}
156	return c.emit(Created{Number: n}, func(w io.Writer) {
157		fmt.Fprintf(w, "created %s#%d\n", repo.Path(), n)
158	})
159}
160
161func runIssueList(c *Ctx, args []string) int {
162	args, p, code := parsePageFlags(c, args, "issue", true)
163	if code >= 0 {
164		return code
165	}
166	const usage = "usage: issue list <owner/name> [--state open|closed|all] [--label <l>] [--assignee <user>] [--author <user>] [--milestone <title>|none] [--limit <n>] [--cursor <c>]"
167	f := store.IssueFilter{State: "open"}
168	fl, err := parseFlags(args, flagSpec{Values: []string{"--state", "--label", "--assignee", "--author", "--milestone"}, MaxPos: 1, Usage: usage})
169	if err != nil {
170		return c.fail(protocol.ExitUsage, "%v", err)
171	}
172	path := fl.pos(0)
173	if fl.Has("--state") {
174		f.State = fl.Value("--state")
175	}
176	f.Label, f.Assignee, f.Author, f.Milestone = fl.Value("--label"), fl.Value("--assignee"), fl.Value("--author"), fl.Value("--milestone")
177	if path == "" || (f.State != "open" && f.State != "closed" && f.State != "all") {
178		return c.fail(protocol.ExitUsage, usage)
179	}
180	repo, code := resolveRepo(c, path, policy.CanRead)
181	if code >= 0 {
182		return code
183	}
184	f.Limit, f.Before = p.queryLimit(), p.keyInt()
185	issues, err := c.Store.QueryIssues(repo.ID, f)
186	if err != nil {
187		return c.fail(protocol.ExitFailure, "%v", err)
188	}
189	issues, next := trimPage(p, issues, "issue", func(i store.Issue) string {
190		return strconv.FormatInt(i.Number, 10)
191	})
192	var ds []issueOut
193	for _, i := range issues {
194		ds = append(ds, issueToOut(i, false))
195	}
196	return c.emitPage(p, ds, next, func(w io.Writer) {
197		for _, d := range ds {
198			fmt.Fprintf(w, "#%d\t%s\t%s\t%s\n", d.Number, d.State, d.Title, d.Author)
199		}
200	})
201}
202
203func runIssueShow(c *Ctx, args []string) int {
204	repo, issue, code := issueRef(c, args, policy.CanRead)
205	if code >= 0 {
206		return code
207	}
208	if len(args) != 2 {
209		return c.fail(protocol.ExitUsage, "usage: issue show <owner/name> <n>")
210	}
211	comments, err := c.Store.ListIssueComments(issue.ID)
212	if err != nil {
213		return c.fail(protocol.ExitFailure, "%v", err)
214	}
215	var cs []commentOut
216	for _, cm := range comments {
217		cs = append(cs, commentOut{cm.Author, cm.Body, cm.BodyFormat, cm.CreatedAt})
218	}
219	d := IssueShow{issueOut: issueToOut(issue, true), Comments: cs}
220	_ = repo
221	return c.emit(d, func(w io.Writer) {
222		fmt.Fprintf(w, "#%d %s [%s] by %s\n", d.Number, d.Title, d.State, d.Author)
223		if len(d.Labels) > 0 {
224			fmt.Fprintf(w, "labels: %s\n", strings.Join(d.Labels, ", "))
225		}
226		if len(d.Assignees) > 0 {
227			fmt.Fprintf(w, "assignees: %s\n", strings.Join(d.Assignees, ", "))
228		}
229		if d.Body != "" {
230			fmt.Fprintf(w, "\n%s\n", d.Body)
231		}
232		for _, cm := range cs {
233			fmt.Fprintf(w, "\n--- %s at %s\n%s\n", cm.Author, cm.CreatedAt, cm.Body)
234		}
235	})
236}
237
238func runIssueComment(c *Ctx, args []string) int {
239	return runComment(c, args, issueThread, "issue",
240		func(rest []string) (store.Repo, int64, int64, string, int) {
241			repo, issue, code := issueRef(c, rest, policy.CanRead)
242			return repo, issue.ID, issue.Number, issue.Title, code
243		},
244		c.Store.AddIssueComment, c.Store.IssueParticipants)
245}
246
247func setIssueState(c *Ctx, args []string, state string) int {
248	// Author may close/reopen their own issue; otherwise write access.
249	repo, issue, code := issueRef(c, args, policy.CanRead)
250	if code >= 0 {
251		return code
252	}
253	if code := refuseArchived(c, repo); code >= 0 {
254		return code
255	}
256	if len(args) != 2 {
257		return c.fail(protocol.ExitUsage, "usage: issue %s <owner/name> <n>", state)
258	}
259	if code := authorOrWrite(c, repo, issue.Author, map[string]string{"open": "reopen", "closed": "close"}[state]+" this issue"); code >= 0 {
260		return code
261	}
262	if issue.State == state {
263		return c.fail(protocol.ExitUsage, "issue #%d is already %s", issue.Number, state)
264	}
265	if err := c.Store.SetIssueState(issue.ID, state); err != nil {
266		return c.fail(protocol.ExitFailure, "%v", err)
267	}
268	c.Store.RecordEvent(repo.ID, c.User.ID, "issue."+state, fmt.Sprintf(`{"number":%d}`, issue.Number))
269	if parts, err := c.Store.IssueParticipants(issue.ID); err == nil {
270		verb := map[string]string{"open": "reopened", "closed": "closed"}[state]
271		notifyUsers(c, parts, issueSubject(repo, issue.Number, issue.Title),
272			notifyBody(c, fmt.Sprintf("%s #%d", verb, issue.Number), "", fmt.Sprintf("%s/issues/%d", repo.Path(), issue.Number)))
273	}
274	return c.emit(map[string]any{"number": issue.Number, "state": state}, func(w io.Writer) {
275		fmt.Fprintf(w, "%s#%d is now %s\n", repo.Path(), issue.Number, state)
276	})
277}
278
279// editText parses --title/--body/--file -/--format and authorizes: author or
280// write. A nil format means the stored markup format stays as it is.
281func editText(c *Ctx, args []string, kind string) (rest []string, title, body, format *string, code int) {
282	f, err := parseFlags(args, flagSpec{Values: []string{"--title", "--body", "--file", "--format"}, MaxPos: -1,
283		Usage: kind + " edit <owner/name> <n> [--title <t>] [--body <b> | --file -] [--format md|org]"})
284	if err != nil {
285		return nil, nil, nil, nil, c.fail(protocol.ExitUsage, "%v", err)
286	}
287	rest = f.Pos
288	titleV, bodyV, file, formatV := f.Value("--title"), f.Value("--body"), f.Value("--file"), f.Value("--format")
289	haveTitle, haveBody := f.Has("--title"), f.Has("--body")
290	if file != "" {
291		b, err := bodyFrom(c, "", file)
292		if err != nil {
293			return nil, nil, nil, nil, c.failErr(err)
294		}
295		bodyV, haveBody = b, true
296	}
297	fmtName, err := markupFormat(formatV)
298	if err != nil {
299		return nil, nil, nil, nil, c.failErr(err)
300	}
301	if !haveTitle && !haveBody && fmtName == "" {
302		return nil, nil, nil, nil, c.fail(protocol.ExitUsage, "usage: %s edit <owner/name> <n> [--title <t>] [--body <b> | --file -] [--format md|org]", kind)
303	}
304	if haveTitle {
305		if strings.TrimSpace(titleV) == "" {
306			return nil, nil, nil, nil, c.fail(protocol.ExitUsage, "--title must not be empty")
307		}
308		title = &titleV
309	}
310	if haveBody {
311		body = &bodyV
312	}
313	if fmtName != "" {
314		format = &fmtName
315	}
316	return rest, title, body, format, -1
317}
318
319func runIssueEdit(c *Ctx, args []string) int {
320	rest, title, body, format, code := editText(c, args, "issue")
321	if code >= 0 {
322		return code
323	}
324	repo, issue, code := issueRef(c, rest, policy.CanRead)
325	if code >= 0 {
326		return code
327	}
328	if code := refuseArchived(c, repo); code >= 0 {
329		return code
330	}
331	if code := authorOrWrite(c, repo, issue.Author, "edit this issue"); code >= 0 {
332		return code
333	}
334	if err := c.Store.UpdateIssueText(issue.ID, title, body, format); err != nil {
335		return c.fail(protocol.ExitFailure, "%v", err)
336	}
337	return c.emit(map[string]any{"number": issue.Number}, func(w io.Writer) {
338		fmt.Fprintf(w, "edited %s#%d\n", repo.Path(), issue.Number)
339	})
340}
341
342func runIssueClose(c *Ctx, args []string) int  { return setIssueState(c, args, "closed") }
343func runIssueReopen(c *Ctx, args []string) int { return setIssueState(c, args, "open") }
344
345// addRemoveFlags parses repeated --add/--remove flags.
346func addRemoveFlags(args []string) (rest, adds, removes []string, err error) {
347	f, err := parseFlags(args, flagSpec{Multi: []string{"--add", "--remove"}, MaxPos: -1})
348	if err != nil {
349		return nil, nil, nil, err
350	}
351	rest, adds, removes = f.Pos, f.List("--add"), f.List("--remove")
352	return rest, adds, removes, nil
353}
354
355func runIssueLabel(c *Ctx, args []string) int {
356	rest, adds, removes, err := addRemoveFlags(args)
357	if err != nil {
358		return c.failErr(err)
359	}
360	if len(adds)+len(removes) == 0 {
361		return c.fail(protocol.ExitUsage, "usage: issue label <owner/name> <n> [--add <l>]... [--remove <l>]...")
362	}
363	repo, issue, code := issueRef(c, rest, policy.CanWrite)
364	if code >= 0 {
365		return code
366	}
367	if code := refuseArchived(c, repo); code >= 0 {
368		return code
369	}
370	for _, l := range adds {
371		if err := c.Store.SetIssueLabel(repo.ID, issue.ID, l, true); err != nil {
372			return c.fail(protocol.ExitFailure, "%v", err)
373		}
374	}
375	for _, l := range removes {
376		if err := c.Store.SetIssueLabel(repo.ID, issue.ID, l, false); err != nil {
377			if errors.Is(err, store.ErrNotFound) {
378				return c.fail(protocol.ExitNotFound, "%v", err)
379			}
380			return c.fail(protocol.ExitFailure, "%v", err)
381		}
382	}
383	updated, err := c.Store.IssueByNumber(repo.ID, issue.Number)
384	if err != nil {
385		return c.fail(protocol.ExitFailure, "%v", err)
386	}
387	return c.emit(map[string]any{"number": issue.Number, "labels": updated.Labels}, func(w io.Writer) {
388		fmt.Fprintf(w, "labels on %s#%d: %s\n", repo.Path(), issue.Number, strings.Join(updated.Labels, ", "))
389	})
390}
391
392func runIssueAssign(c *Ctx, args []string) int {
393	rest, adds, removes, err := addRemoveFlags(args)
394	if err != nil {
395		return c.failErr(err)
396	}
397	if len(adds)+len(removes) == 0 {
398		return c.fail(protocol.ExitUsage, "usage: issue assign <owner/name> <n> [--add <user>]... [--remove <user>]...")
399	}
400	repo, issue, code := issueRef(c, rest, policy.CanWrite)
401	if code >= 0 {
402		return code
403	}
404	if code := refuseArchived(c, repo); code >= 0 {
405		return code
406	}
407	resolve := func(name string) (store.User, int) {
408		u, err := c.Store.UserByUsername(name)
409		if errors.Is(err, store.ErrNotFound) {
410			return u, c.fail(protocol.ExitNotFound, "no such user %q", name)
411		}
412		if err != nil {
413			return u, c.fail(protocol.ExitFailure, "%v", err)
414		}
415		return u, -1
416	}
417	for _, name := range adds {
418		u, code := resolve(name)
419		if code >= 0 {
420			return code
421		}
422		if err := c.Store.SetIssueAssignee(issue.ID, u.ID, true); err != nil {
423			return c.fail(protocol.ExitFailure, "%v", err)
424		}
425	}
426	for _, name := range removes {
427		u, code := resolve(name)
428		if code >= 0 {
429			return code
430		}
431		if err := c.Store.SetIssueAssignee(issue.ID, u.ID, false); err != nil {
432			if errors.Is(err, store.ErrNotFound) {
433				return c.fail(protocol.ExitNotFound, "%s is not assigned", name)
434			}
435			return c.fail(protocol.ExitFailure, "%v", err)
436		}
437	}
438	updated, err := c.Store.IssueByNumber(repo.ID, issue.Number)
439	if err != nil {
440		return c.fail(protocol.ExitFailure, "%v", err)
441	}
442	return c.emit(map[string]any{"number": issue.Number, "assignees": updated.Assignees}, func(w io.Writer) {
443		fmt.Fprintf(w, "assignees on %s#%d: %s\n", repo.Path(), issue.Number, strings.Join(updated.Assignees, ", "))
444	})
445}