internal/control/diffcomment.go

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

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