internal/control/diffcomment.go

dbec077010394f2955c9b20cfd81700ef6b2bdb9
gitbay/internal/control/diffcomment.go history · blame · raw

235 lines · 7749 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"slices"
  8	"strconv"
  9	"strings"
 10
 11	"gitbay.org/gitbay/internal/gitutil"
 12	"gitbay.org/gitbay/internal/policy"
 13	"gitbay.org/gitbay/internal/protocol"
 14	"gitbay.org/gitbay/internal/store"
 15)
 16
 17func init() {
 18	register(Command{Path: []string{"mr", "diff-comment"},
 19		Summary:    "comment on a diff line",
 20		Usage:      "mr diff-comment <owner/name> <n> --path <file> --line <l> [--old] [--reply <id>] [--message <m> | --file -]",
 21		ReadsStdin: true, Run: runDiffComment})
 22	register(Command{Path: []string{"mr", "threads"},
 23		Summary: "review threads on an MR",
 24		Usage:   "mr threads <owner/name> <n>", ReadOnly: true, Run: runMRThreads})
 25	register(Command{Path: []string{"mr", "resolve"},
 26		Summary: "resolve a review thread",
 27		Usage:   "mr resolve <owner/name> <n> <thread-id>", Run: runMRResolve})
 28	register(Command{Path: []string{"mr", "unresolve"},
 29		Summary: "reopen a review thread",
 30		Usage:   "mr unresolve <owner/name> <n> <thread-id>", Run: runMRUnresolve})
 31}
 32
 33func runDiffComment(c *Ctx, args []string) int {
 34	f, err := parseFlags(args, flagSpec{Values: []string{"--path", "--line", "--reply", "--message", "--file"}, Bools: []string{"--old"}, MaxPos: -1,
 35		Usage: "mr diff-comment <owner/name> <n> --path <file> --line <l> [--old] [--reply <id>] [--message <m> | --file -]"})
 36	if err != nil {
 37		return c.fail(protocol.ExitUsage, "%v", err)
 38	}
 39	rest := f.Pos
 40	path, message, file, old := f.Value("--path"), f.Value("--message"), f.Value("--file"), f.Has("--old")
 41	var line, replyTo int64
 42	if f.Has("--line") {
 43		n, err := strconv.ParseInt(f.Value("--line"), 10, 64)
 44		if err != nil || n < 1 {
 45			return c.fail(protocol.ExitUsage, "--line must be a positive number")
 46		}
 47		line = n
 48	}
 49	if f.Has("--reply") {
 50		n, err := strconv.ParseInt(f.Value("--reply"), 10, 64)
 51		if err != nil || n < 1 {
 52			return c.fail(protocol.ExitUsage, "--reply must be a thread id")
 53		}
 54		replyTo = n
 55	}
 56	repo, mr, code := mrRef(c, rest, policy.CanRead)
 57	if code >= 0 {
 58		return code
 59	}
 60	if code := refuseArchived(c, repo); code >= 0 {
 61		return code
 62	}
 63	if replyTo == 0 && (path == "" || line == 0) {
 64		return c.fail(protocol.ExitUsage, "a new thread needs --path and --line (or reply to one with --reply <id>)")
 65	}
 66	body, err := bodyFrom(c, message, file)
 67	if err != nil {
 68		return c.failErr(err)
 69	}
 70	if strings.TrimSpace(body) == "" {
 71		return c.fail(protocol.ExitUsage, "empty comment; use --message or --file -")
 72	}
 73
 74	side := "new"
 75	if old {
 76		side = "old"
 77	}
 78	if replyTo == 0 {
 79		// The path must actually be part of the MR's diff.
 80		dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 81		base := mr.MergedBase
 82		if base == "" {
 83			b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number))
 84			if err != nil {
 85				return c.fail(protocol.ExitFailure, "%v", err)
 86			}
 87			base = b
 88		}
 89		files, err := gitutil.DiffFiles(dir, base, mrHeadRef(mr.Number))
 90		if err != nil {
 91			return c.fail(protocol.ExitFailure, "%v", err)
 92		}
 93		if !slices.Contains(files, path) {
 94			return c.fail(protocol.ExitUsage, "%s is not part of this merge request's diff", path)
 95		}
 96	}
 97
 98	id, err := c.Store.AddDiffComment(mr.ID, c.User.ID, mr.HeadSHA, path, side, line, body, replyTo)
 99	if err != nil {
100		if errors.Is(err, store.ErrNotFound) {
101			return c.fail(protocol.ExitNotFound, "%v", err)
102		}
103		return c.failErr(err)
104	}
105	if parts, err := c.Store.MRParticipants(mr.ID); err == nil {
106		notifyUsers(c, parts, mrSubject(repo, mr.Number, mr.Title),
107			notifyBody(c, fmt.Sprintf("commented on %s:%d in !%d", path, line, mr.Number), body,
108				fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)))
109	}
110	return c.emit(map[string]any{"id": id, "thread": firstNonZero(replyTo, id)}, func(w io.Writer) {
111		if replyTo != 0 {
112			fmt.Fprintf(w, "replied to thread %d on %s!%d\n", replyTo, repo.Path(), mr.Number)
113		} else {
114			fmt.Fprintf(w, "thread %d opened on %s:%d in %s!%d\n", id, path, line, repo.Path(), mr.Number)
115		}
116	})
117}
118
119func firstNonZero(a, b int64) int64 {
120	if a != 0 {
121		return a
122	}
123	return b
124}
125
126func runMRThreads(c *Ctx, args []string) int {
127	repo, mr, code := mrRef(c, args, policy.CanRead)
128	if code >= 0 {
129		return code
130	}
131	if len(args) != 2 {
132		return c.fail(protocol.ExitUsage, "usage: mr threads <owner/name> <n>")
133	}
134	comments, err := c.Store.ListDiffComments(mr.ID)
135	if err != nil {
136		return c.fail(protocol.ExitFailure, "%v", err)
137	}
138	type commentOut struct {
139		ID        int64  `json:"id"`
140		Author    string `json:"author"`
141		Body      string `json:"body"`
142		CreatedAt string `json:"created_at"`
143	}
144	type threadOut struct {
145		ID       int64        `json:"id"`
146		Path     string       `json:"path"`
147		Side     string       `json:"side"`
148		Line     int64        `json:"line"`
149		Stale    bool         `json:"stale"`
150		Resolved string       `json:"resolved_by,omitempty"`
151		Comments []commentOut `json:"comments"`
152	}
153	byRoot := map[int64]*threadOut{}
154	var order []int64
155	for _, cm := range comments {
156		if cm.ReplyTo == 0 {
157			byRoot[cm.ID] = &threadOut{
158				ID: cm.ID, Path: cm.Path, Side: cm.Side, Line: cm.Line,
159				Stale: cm.HeadSHA != mr.HeadSHA, Resolved: cm.ResolvedBy,
160				Comments: []commentOut{{cm.ID, cm.Author, cm.Body, cm.CreatedAt}},
161			}
162			order = append(order, cm.ID)
163		} else if th, ok := byRoot[cm.ReplyTo]; ok {
164			th.Comments = append(th.Comments, commentOut{cm.ID, cm.Author, cm.Body, cm.CreatedAt})
165		}
166	}
167	var ds []threadOut
168	for _, id := range order {
169		ds = append(ds, *byRoot[id])
170	}
171	_ = repo
172	return c.emit(ds, func(w io.Writer) {
173		for _, th := range ds {
174			marks := ""
175			if th.Resolved != "" {
176				marks += " [resolved by " + th.Resolved + "]"
177			}
178			if th.Stale {
179				marks += " [stale]"
180			}
181			fmt.Fprintf(w, "thread %d  %s:%d (%s)%s\n", th.ID, th.Path, th.Line, th.Side, marks)
182			for _, cm := range th.Comments {
183				fmt.Fprintf(w, "  %s: %s\n", cm.Author, cm.Body)
184			}
185		}
186	})
187}
188
189func setThreadResolved(c *Ctx, args []string, resolved bool) int {
190	if len(args) != 3 {
191		return c.fail(protocol.ExitUsage, "usage: mr resolve|unresolve <owner/name> <n> <thread-id>")
192	}
193	repo, mr, code := mrRef(c, args[:2], policy.CanRead)
194	if code >= 0 {
195		return code
196	}
197	if code := refuseArchived(c, repo); code >= 0 {
198		return code
199	}
200	threadID, err := strconv.ParseInt(args[2], 10, 64)
201	if err != nil {
202		return c.fail(protocol.ExitUsage, "bad thread id %q", args[2])
203	}
204	// Thread author, MR author, or anyone with write may resolve.
205	author, err := c.Store.DiffCommentAuthor(mr.ID, threadID)
206	if errors.Is(err, store.ErrNotFound) {
207		return c.fail(protocol.ExitNotFound, "no thread %d on %s!%d", threadID, repo.Path(), mr.Number)
208	}
209	if err != nil {
210		return c.fail(protocol.ExitFailure, "%v", err)
211	}
212	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
213	if err != nil {
214		return c.fail(protocol.ExitFailure, "%v", err)
215	}
216	if author != c.User.ID && mr.Author != c.User.Username && !policy.CanWrite(c.User, repo, grant) {
217		return c.fail(protocol.ExitDenied, "only the thread author, the MR author, or users with write access can resolve threads")
218	}
219	if err := c.Store.SetThreadResolved(mr.ID, threadID, c.User.ID, resolved); err != nil {
220		if errors.Is(err, store.ErrNotFound) {
221			return c.fail(protocol.ExitNotFound, "no thread %d (replies cannot be resolved; use the root id)", threadID)
222		}
223		return c.fail(protocol.ExitFailure, "%v", err)
224	}
225	verb := "resolved"
226	if !resolved {
227		verb = "reopened"
228	}
229	return c.emit(map[string]any{"thread": threadID, "resolved": resolved}, func(w io.Writer) {
230		fmt.Fprintf(w, "%s thread %d on %s!%d\n", verb, threadID, repo.Path(), mr.Number)
231	})
232}
233
234func runMRResolve(c *Ctx, args []string) int   { return setThreadResolved(c, args, true) }
235func runMRUnresolve(c *Ctx, args []string) int { return setThreadResolved(c, args, false) }