1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package app
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "net/url"
11 "slices"
12 "strconv"
13 "strings"
14
15 "connectrpc.com/connect"
16 "github.com/spf13/cobra"
17
18 "bnema.dev/ermite-api/gen/ermite"
19 "bnema.dev/ermite/internal/adapters/client"
20)
21
22// Names of the states, the sides and the merge modes in the output and in the
23// flags.
24const (
25 stateOpen = "open"
26 stateMerged = "merged"
27 stateClosed = "closed"
28 stateAll = "all"
29
30 sideOld = "old"
31 sideNew = "new"
32
33 modeFastForward = "fast-forward"
34 modeSquash = "squash"
35 modeMerge = "merge"
36)
37
38func stateName(s ermite.MergeRequestState) string {
39 switch s {
40 case ermite.MergeRequestState_MERGE_REQUEST_STATE_OPEN:
41 return stateOpen
42 case ermite.MergeRequestState_MERGE_REQUEST_STATE_MERGED:
43 return stateMerged
44 case ermite.MergeRequestState_MERGE_REQUEST_STATE_CLOSED:
45 return stateClosed
46 }
47 return "unknown"
48}
49
50func parseState(s string) (ermite.MergeRequestState, error) {
51 switch strings.ToLower(strings.TrimSpace(s)) {
52 case stateOpen:
53 return ermite.MergeRequestState_MERGE_REQUEST_STATE_OPEN, nil
54 case stateMerged:
55 return ermite.MergeRequestState_MERGE_REQUEST_STATE_MERGED, nil
56 case stateClosed:
57 return ermite.MergeRequestState_MERGE_REQUEST_STATE_CLOSED, nil
58 case stateAll:
59 return ermite.MergeRequestState_MERGE_REQUEST_STATE_UNSPECIFIED, nil
60 }
61 return 0, fmt.Errorf("invalid state %q: use %s, %s, %s or %s", s, stateOpen, stateMerged, stateClosed, stateAll)
62}
63
64func modeName(m ermite.MergeMode) string {
65 switch m {
66 case ermite.MergeMode_MERGE_MODE_FAST_FORWARD:
67 return modeFastForward
68 case ermite.MergeMode_MERGE_MODE_SQUASH:
69 return modeSquash
70 case ermite.MergeMode_MERGE_MODE_MERGE_COMMIT:
71 return modeMerge
72 }
73 return ""
74}
75
76func parseMode(s string) (ermite.MergeMode, error) {
77 switch strings.ToLower(strings.TrimSpace(s)) {
78 case modeFastForward, "ff":
79 return ermite.MergeMode_MERGE_MODE_FAST_FORWARD, nil
80 case modeSquash:
81 return ermite.MergeMode_MERGE_MODE_SQUASH, nil
82 case modeMerge:
83 return ermite.MergeMode_MERGE_MODE_MERGE_COMMIT, nil
84 }
85 return 0, fmt.Errorf("invalid merge mode %q: use %s, %s or %s", s, modeFastForward, modeSquash, modeMerge)
86}
87
88func sideName(s ermite.DiffSide) string {
89 switch s {
90 case ermite.DiffSide_DIFF_SIDE_OLD:
91 return sideOld
92 case ermite.DiffSide_DIFF_SIDE_NEW:
93 return sideNew
94 }
95 return ""
96}
97
98func parseSide(s string) (ermite.DiffSide, error) {
99 switch strings.ToLower(strings.TrimSpace(s)) {
100 case sideOld:
101 return ermite.DiffSide_DIFF_SIDE_OLD, nil
102 case sideNew:
103 return ermite.DiffSide_DIFF_SIDE_NEW, nil
104 }
105 return 0, fmt.Errorf("invalid side %q: use %s or %s", s, sideOld, sideNew)
106}
107
108// jsonMergeRequest is the stable JSON shape of a merge request.
109type jsonMergeRequest struct {
110 Repo string `json:"repo"`
111 URL string `json:"url"`
112 Number int64 `json:"number"`
113 Title string `json:"title"`
114 Description string `json:"description"`
115 SourceBranch string `json:"source_branch"`
116 TargetBranch string `json:"target_branch"`
117 State string `json:"state"`
118 Author string `json:"author"`
119 CreatedAt *string `json:"created_at"`
120 UpdatedAt *string `json:"updated_at"`
121 HeadID string `json:"head_id"`
122 MergedCommitID string `json:"merged_commit_id"`
123 MergeMode string `json:"merge_mode"`
124 // AutoMerge is the pending auto-merge, null when there is none.
125 AutoMerge *jsonAutoMerge `json:"auto_merge"`
126 // AutoMerged is true when the server merged the request by auto-merge.
127 AutoMerged bool `json:"auto_merged"`
128}
129
130// jsonAutoMerge is the stable JSON shape of a pending auto-merge.
131type jsonAutoMerge struct {
132 Mode string `json:"mode"`
133 HeadID string `json:"head_id"`
134 EnabledBy string `json:"enabled_by"`
135 EnabledAt *string `json:"enabled_at"`
136}
137
138// toJSONAutoMerge maps an auto-merge; nil when there is none.
139func toJSONAutoMerge(a *ermite.AutoMerge) *jsonAutoMerge {
140 if a == nil {
141 return nil
142 }
143 return &jsonAutoMerge{Mode: modeName(a.GetMode()), HeadID: a.GetHeadId(), EnabledBy: a.GetEnabledBy(), EnabledAt: jsonTime(a.GetEnabledAt())}
144}
145
146// jsonMergeability is the stable JSON shape of the mergeability of an open
147// merge request.
148type jsonMergeability struct {
149 // State is "checking", "up_to_date", "behind" or "conflict".
150 State string `json:"state"`
151 // Behind counts the commits of the target the head lacks (behind only);
152 // BehindCapped says it is a lower bound.
153 Behind int32 `json:"behind"`
154 BehindCapped bool `json:"behind_capped"`
155 ConflictPaths []string `json:"conflict_paths"`
156 // ConflictPathsTruncated says that more paths conflict than listed.
157 ConflictPathsTruncated bool `json:"conflict_paths_truncated"`
158 TargetID string `json:"target_id"`
159 HeadID string `json:"head_id"`
160}
161
162func mergeabilityName(s ermite.MergeabilityState) string {
163 switch s {
164 case ermite.MergeabilityState_MERGEABILITY_STATE_CHECKING:
165 return "checking"
166 case ermite.MergeabilityState_MERGEABILITY_STATE_UP_TO_DATE:
167 return "up_to_date"
168 case ermite.MergeabilityState_MERGEABILITY_STATE_BEHIND:
169 return "behind"
170 case ermite.MergeabilityState_MERGEABILITY_STATE_CONFLICT:
171 return "conflict"
172 }
173 return ""
174}
175
176// toJSONMergeability maps a mergeability; nil when the server sent none.
177func toJSONMergeability(m *ermite.Mergeability) *jsonMergeability {
178 if m == nil {
179 return nil
180 }
181 return &jsonMergeability{
182 State: mergeabilityName(m.GetState()), Behind: m.GetBehind(), BehindCapped: m.GetBehindCapped(),
183 ConflictPaths: append([]string{}, m.GetConflictPaths()...), ConflictPathsTruncated: m.GetConflictPathsTruncated(),
184 TargetID: m.GetTargetId(), HeadID: m.GetHeadId(),
185 }
186}
187
188// mergeabilityText is the human form of a mergeability: "up to date",
189// "behind by 2", "conflict (a, b, ...)", "checking".
190func mergeabilityText(m *jsonMergeability) string {
191 switch m.State {
192 case "up_to_date":
193 return "up to date with the target, can be fast-forwarded"
194 case "behind":
195 return fmt.Sprintf("behind by %d%s, merges without conflicts (squash or merge commit; fast-forward needs a rebase)", m.Behind, plus(m.BehindCapped))
196 case "conflict":
197 if len(m.ConflictPaths) == 0 {
198 return "conflict (no common history with the target), rebase needed"
199 }
200 more := ""
201 if m.ConflictPathsTruncated {
202 more = ", ..."
203 }
204 return "conflict (" + strings.Join(m.ConflictPaths, ", ") + more + "), rebase needed"
205 case "checking":
206 return "checking"
207 }
208 return m.State
209}
210
211// jsonMerged is the output of `mr merge --json`.
212type jsonMerged struct {
213 jsonMergeRequest
214 SourceBranchDeleted bool `json:"source_branch_deleted"`
215}
216
217func toJSONMergeRequest(m *ermite.MergeRequest, baseURL string) jsonMergeRequest {
218 return jsonMergeRequest{
219 URL: mrWebURL(baseURL, m.GetRepo(), m.GetNumber()),
220 Repo: m.GetRepo(), Number: m.GetNumber(), Title: m.GetTitle(), Description: m.GetDescription(),
221 SourceBranch: m.GetSourceBranch(), TargetBranch: m.GetTargetBranch(), State: stateName(m.GetState()),
222 Author: m.GetAuthor(), CreatedAt: jsonTime(m.GetCreatedAt()), UpdatedAt: jsonTime(m.GetUpdatedAt()),
223 HeadID: m.GetHeadId(), MergedCommitID: m.GetMergedCommitId(), MergeMode: modeName(m.GetMergeMode()),
224 AutoMerge: toJSONAutoMerge(m.GetAutoMerge()), AutoMerged: m.GetAutoMerged(),
225 }
226}
227
228// jsonComment is the stable JSON shape of a comment.
229type jsonComment struct {
230 ID string `json:"id"`
231 Author string `json:"author"`
232 Path string `json:"path"`
233 Line int32 `json:"line"`
234 Side string `json:"side"`
235 CommitID string `json:"commit_id"`
236 Text string `json:"text"`
237 Resolved bool `json:"resolved"`
238 CreatedAt *string `json:"created_at"`
239 ReplyTo string `json:"reply_to"`
240 StartLine int32 `json:"start_line"`
241 Verdict string `json:"verdict"`
242 EditedAt *string `json:"edited_at"`
243 Deleted bool `json:"deleted"`
244}
245
246func verdictName(v ermite.Verdict) string {
247 switch v {
248 case ermite.Verdict_VERDICT_APPROVE:
249 return "approve"
250 case ermite.Verdict_VERDICT_CHANGES_REQUESTED:
251 return "changes_requested"
252 }
253 return ""
254}
255
256func toJSONComment(c *ermite.Comment) jsonComment {
257 return jsonComment{
258 ID: c.GetId(), Author: c.GetAuthor(), Path: c.GetPath(), Line: c.GetLine(), Side: sideName(c.GetSide()),
259 CommitID: c.GetCommitId(), Text: c.GetText(), Resolved: c.GetResolved(), CreatedAt: jsonTime(c.GetCreatedAt()),
260 ReplyTo: c.GetReplyTo(), StartLine: c.GetStartLine(), Verdict: verdictName(c.GetVerdict()), EditedAt: jsonTime(c.GetEditedAt()), Deleted: c.GetDeleted(),
261 }
262}
263
264const jsonMRHelp = `
265JSON fields of a merge request (--json): repo, url (full web URL), number, title, description, source_branch,
266target_branch, state ("open", "merged" or "closed"), author (token label), created_at and
267updated_at (RFC 3339 UTC), head_id (the commit the source branch points to; empty when the
268branch is gone), merged_commit_id and merge_mode ("fast-forward", "squash" or "merge"; both empty
269unless merged), auto_merge (null unless auto-merge is pending: mode, head_id, enabled_by,
270enabled_at) and auto_merged (true when the server merged the request by auto-merge).`
271
272const jsonMergeabilityHelp = `
273mr show --json adds mergeability, null unless the request is open: state ("checking", "up_to_date",
274"behind" or "conflict"), behind and behind_capped (commits of the target the head lacks; behind
275only), conflict_paths and conflict_paths_truncated (conflict only), target_id and head_id (the
276commits the result is for).`
277
278const jsonCommentHelp = `
279JSON fields of a comment: id, author, path, line and side ("old" or "new"; empty path, line 0
280and empty side for a general comment), commit_id (the head when it was written), text,
281resolved, created_at, reply_to (empty for roots), start_line (0 for a single line),
282verdict ("", "approve", "changes_requested"), edited_at (nullable RFC 3339), deleted.`
283
284func newMRCmd(env *cliEnv) *cobra.Command {
285 mr := &cobra.Command{
286 Use: "mr",
287 Short: "Review and merge branches on a remote server",
288 Long: "Merge requests ask to merge one branch of a repository into another. They are about a branch,\n" +
289 "not about who wrote it. Needs a server with the merge_requests feature (see `ermite version`).\n" +
290 "A merge request is named by its repository and its number: `ermite mr show proj 3`.",
291 }
292 mr.AddCommand(
293 newMRCreateCmd(env), newMRListCmd(env), newMRShowCmd(env), newMRCommentCmd(env),
294 newMRResolveCmd(env), newMREditCommentCmd(env), newMRDeleteCommentCmd(env), newMRMergeCmd(env), newMRCloseCmd(env),
295 )
296 return mr
297}
298
299// parseNumber reads the number of a merge request, written 3 or !3.
300func parseNumber(s string) (int64, error) {
301 n, err := strconv.ParseInt(strings.TrimPrefix(strings.TrimSpace(s), "!"), 10, 64)
302 if err != nil || n < 1 {
303 return 0, fmt.Errorf("invalid merge request number %q: use a positive number such as 3 or !3", s)
304 }
305 return n, nil
306}
307
308// readText returns value, or all of standard input when value is "-".
309func readText(cmd *cobra.Command, value string) (string, error) {
310 if value != "-" {
311 return value, nil
312 }
313 b, err := io.ReadAll(io.LimitReader(cmd.InOrStdin(), 1<<20))
314 if err != nil {
315 return "", fmt.Errorf("read standard input: %w", err)
316 }
317 return strings.TrimRight(string(b), "\r\n"), nil
318}
319
320func completeMRRepoThenNumber(env *cliEnv) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
321 return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
322 switch len(args) {
323 case 0:
324 return repoNames(env, cmd, toComplete), cobra.ShellCompDirectiveNoFileComp
325 case 1:
326 c, err := env.completionClient(cmd)
327 if err != nil {
328 return nil, cobra.ShellCompDirectiveNoFileComp
329 }
330 mrs, err := listMergeRequests(env.ctx(cmd), c, args[0], ermite.MergeRequestState_MERGE_REQUEST_STATE_UNSPECIFIED)
331 if err != nil {
332 return nil, cobra.ShellCompDirectiveNoFileComp
333 }
334 var out []string
335 for _, m := range mrs {
336 if n := strconv.FormatInt(m.GetNumber(), 10); strings.HasPrefix(n, toComplete) {
337 out = append(out, n+"\t"+stateName(m.GetState())+", "+clean(m.GetTitle()))
338 }
339 }
340 return out, cobra.ShellCompDirectiveNoFileComp
341 }
342 return nil, cobra.ShellCompDirectiveNoFileComp
343 }
344}
345
346func listMergeRequests(ctx context.Context, c *client.Client, repo string, state ermite.MergeRequestState) ([]*ermite.MergeRequest, error) {
347 return collect(ctx, func(token string) ([]*ermite.MergeRequest, string, error) {
348 res, err := c.MergeRequests().ListMergeRequests(ctx, connect.NewRequest(&ermite.ListMergeRequestsRequest{
349 Repo: repo, State: state, PageToken: token,
350 }))
351 if err != nil {
352 return nil, "", c.Describe(err)
353 }
354 return res.Msg.GetMergeRequests(), res.Msg.GetNextPageToken(), nil
355 })
356}
357
358func newMRCreateCmd(env *cliEnv) *cobra.Command {
359 var title, description, source, target string
360 cmd := &cobra.Command{
361 Use: "create <repo>",
362 Short: "Open a merge request",
363 Long: "Open a merge request for a branch of the repository. --target defaults to the default branch.\n" +
364 "The title is one line of at most 120 characters, the description plain text of at most 8000;\n" +
365 "neither may hold control characters (a description may hold line breaks) or bidirectional\n" +
366 "override characters. --description - reads it from standard input. Fails if an open merge request\n" +
367 "already has the same source and target. Prints a confirmation, then the full web URL on its own line.\n" +
368 "Needs the mr:write scope." + jsonMRHelp,
369 Args: cobra.ExactArgs(1),
370 ValidArgsFunction: completeRepoNames(env),
371 }
372 cmd.Flags().StringVar(&title, "title", "", "title of the merge request (required)")
373 cmd.Flags().StringVar(&description, "description", "", "description, or - to read standard input")
374 cmd.Flags().StringVar(&source, "source", "", "branch to merge (required)")
375 cmd.Flags().StringVar(&target, "target", "", "branch to merge into (default: the default branch)")
376 _ = cmd.MarkFlagRequired("title")
377 _ = cmd.MarkFlagRequired("source")
378 asJSON := addJSONFlag(cmd)
379 cmd.RunE = func(cmd *cobra.Command, args []string) error {
380 desc, err := readText(cmd, description)
381 if err != nil {
382 return err
383 }
384 req := &ermite.CreateMergeRequestRequest{
385 Repo: args[0], Title: title, Description: desc,
386 SourceBranch: trimBranch(source), TargetBranch: trimBranch(target),
387 }
388 c, err := env.client(cmd)
389 if err != nil {
390 return err
391 }
392 res, err := c.MergeRequests().CreateMergeRequest(env.ctx(cmd), connect.NewRequest(req))
393 if err != nil {
394 return c.Describe(err)
395 }
396 return outputMR(cmd, res.Msg.GetMergeRequest(), *asJSON, "opened", c.URL())
397 }
398 return cmd
399}
400
401func trimBranch(s string) string { return strings.TrimPrefix(strings.TrimSpace(s), "refs/heads/") }
402
403// mrWebURL builds the web route with the repository as a single path segment.
404// Repository names currently forbid slashes, but escape all path delimiters defensively.
405func mrWebURL(baseURL, repo string, number int64) string {
406 return strings.TrimRight(baseURL, "/") + "/" + url.PathEscape(repo) + "/merge-requests/" + strconv.FormatInt(number, 10)
407}
408
409// outputMR prints a merge request as JSON, or a confirmation followed by its URL.
410func outputMR(cmd *cobra.Command, m *ermite.MergeRequest, asJSON bool, verb, baseURL string) error {
411 if asJSON {
412 return writeJSON(cmd.OutOrStdout(), toJSONMergeRequest(m, baseURL))
413 }
414 _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s %s!%d (%s into %s)\n%s\n", verb, clean(m.GetRepo()), m.GetNumber(),
415 clean(m.GetSourceBranch()), clean(m.GetTargetBranch()), mrWebURL(baseURL, m.GetRepo(), m.GetNumber()))
416 return err
417}
418
419func newMRListCmd(env *cliEnv) *cobra.Command {
420 var state string
421 cmd := &cobra.Command{
422 Use: "list <repo>",
423 Short: "List the merge requests of a repository",
424 Long: "List the merge requests of a repository, newest first. --state restricts them to open, merged or\n" +
425 "closed ones (default: open; all shows every state)." + jsonMRHelp + "\n--json prints an array of merge requests.",
426 Args: cobra.ExactArgs(1),
427 ValidArgsFunction: completeRepoNames(env),
428 }
429 cmd.Flags().StringVar(&state, "state", stateOpen, "state: open, merged, closed or all")
430 _ = cmd.RegisterFlagCompletionFunc("state", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
431 return []string{stateOpen, stateMerged, stateClosed, stateAll}, cobra.ShellCompDirectiveNoFileComp
432 })
433 asJSON := addJSONFlag(cmd)
434 cmd.RunE = func(cmd *cobra.Command, args []string) error {
435 st, err := parseState(state)
436 if err != nil {
437 return err
438 }
439 c, err := env.client(cmd)
440 if err != nil {
441 return err
442 }
443 mrs, err := listMergeRequests(env.ctx(cmd), c, args[0], st)
444 if err != nil {
445 return err
446 }
447 if *asJSON {
448 out := make([]jsonMergeRequest, 0, len(mrs))
449 for _, m := range mrs {
450 out = append(out, toJSONMergeRequest(m, c.URL()))
451 }
452 return writeJSON(cmd.OutOrStdout(), out)
453 }
454 if len(mrs) == 0 {
455 noticef(cmd, "no merge requests")
456 return nil
457 }
458 rows := make([][]string, 0, len(mrs))
459 for _, m := range mrs {
460 rows = append(rows, []string{
461 "!" + strconv.FormatInt(m.GetNumber(), 10), stateName(m.GetState()),
462 m.GetSourceBranch() + " -> " + m.GetTargetBranch(), m.GetAuthor(),
463 shortTime(m.GetUpdatedAt(), "-"), m.GetTitle(),
464 })
465 }
466 return table(cmd.OutOrStdout(), []string{"NUMBER", "STATE", "BRANCHES", "AUTHOR", "UPDATED", "TITLE"}, rows)
467 }
468 return cmd
469}
470
471// jsonStats are the totals of a diff.
472type jsonStats struct {
473 FilesChanged int32 `json:"files_changed"`
474 Additions int32 `json:"additions"`
475 Deletions int32 `json:"deletions"`
476}
477
478type jsonLine struct {
479 Kind string `json:"kind"`
480 OldNumber int32 `json:"old_number"`
481 NewNumber int32 `json:"new_number"`
482 Text string `json:"text"`
483}
484
485type jsonHunk struct {
486 Header string `json:"header"`
487 OldStart int32 `json:"old_start"`
488 OldLines int32 `json:"old_lines"`
489 NewStart int32 `json:"new_start"`
490 NewLines int32 `json:"new_lines"`
491 Lines []jsonLine `json:"lines"`
492}
493
494type jsonFile struct {
495 OldPath string `json:"old_path"`
496 NewPath string `json:"new_path"`
497 Status string `json:"status"`
498 Additions int32 `json:"additions"`
499 Deletions int32 `json:"deletions"`
500 Binary bool `json:"binary"`
501 Truncated bool `json:"truncated"`
502 // Omitted is generated, large, budget or unavailable; absent when the hunks are not omitted.
503 Omitted string `json:"omitted,omitempty"`
504 Hunks []jsonHunk `json:"hunks,omitempty"`
505}
506
507type jsonCommit struct {
508 ID string `json:"id"`
509 Author string `json:"author"`
510 Summary string `json:"summary"`
511}
512
513// jsonMRDetail is the stable JSON shape of `mr show --json`.
514type jsonMRDetail struct {
515 jsonMergeRequest
516 // Mergeability is null unless the request is open and the server computes it.
517 Mergeability *jsonMergeability `json:"mergeability"`
518 Commits []jsonCommit `json:"commits"`
519 CommitsTruncated bool `json:"commits_truncated"`
520 DiffBaseID string `json:"diff_base_id"`
521 Stats jsonStats `json:"stats"`
522 DiffTruncated bool `json:"diff_truncated"`
523 Files []jsonFile `json:"files"`
524 Comments []jsonComment `json:"comments"`
525 Verdicts []jsonAuthorVerdict `json:"verdicts"`
526 LastReadID string `json:"last_read_id"`
527 LastReadLost bool `json:"last_read_lost"`
528}
529
530type jsonAuthorVerdict struct {
531 Author string `json:"author"`
532 Verdict string `json:"verdict"`
533 CommentID string `json:"comment_id"`
534 CommitID string `json:"commit_id"`
535 CreatedAt *string `json:"created_at"`
536 Stale bool `json:"stale"`
537}
538
539func fileStatusName(s ermite.FileStatus) string {
540 return strings.ToLower(strings.TrimPrefix(s.String(), "FILE_STATUS_"))
541}
542
543// fileOmissionName is the lowercase reason of an omitted file, "" for none.
544func fileOmissionName(o ermite.FileOmission) string {
545 if o == ermite.FileOmission_FILE_OMISSION_UNSPECIFIED {
546 return ""
547 }
548 return strings.ToLower(strings.TrimPrefix(o.String(), "FILE_OMISSION_"))
549}
550
551func lineKindName(k ermite.LineKind) string {
552 return strings.ToLower(strings.TrimPrefix(k.String(), "LINE_KIND_"))
553}
554
555func toJSONDetail(d *ermite.GetMergeRequestResponse, withDiff bool, baseURL string) jsonMRDetail {
556 out := jsonMRDetail{
557 jsonMergeRequest: toJSONMergeRequest(d.GetMergeRequest(), baseURL),
558 Mergeability: toJSONMergeability(d.GetMergeRequest().GetMergeability()),
559 Commits: []jsonCommit{}, CommitsTruncated: d.GetCommitsTruncated(),
560 DiffBaseID: d.GetDiffBaseId(),
561 Stats: jsonStats{
562 FilesChanged: d.GetStats().GetFilesChanged(), Additions: d.GetStats().GetAdditions(), Deletions: d.GetStats().GetDeletions(),
563 },
564 DiffTruncated: d.GetDiff().GetTruncated(),
565 Files: []jsonFile{}, Comments: []jsonComment{}, Verdicts: []jsonAuthorVerdict{},
566 LastReadID: d.GetLastReadId(), LastReadLost: d.GetLastReadLost(),
567 }
568 for _, c := range d.GetCommits() {
569 out.Commits = append(out.Commits, jsonCommit{ID: c.GetId(), Author: c.GetAuthor().GetName(), Summary: c.GetSummary()})
570 }
571 for _, f := range d.GetDiff().GetFiles() {
572 jf := jsonFile{
573 OldPath: f.GetOldPath(), NewPath: f.GetNewPath(), Status: fileStatusName(f.GetStatus()),
574 Additions: f.GetAdditions(), Deletions: f.GetDeletions(), Binary: f.GetBinary(), Truncated: f.GetTruncated(),
575 Omitted: fileOmissionName(f.GetOmitted()),
576 }
577 if withDiff {
578 for _, h := range f.GetHunks() {
579 jh := jsonHunk{
580 Header: h.GetHeader(), OldStart: h.GetOldStart(), OldLines: h.GetOldLines(),
581 NewStart: h.GetNewStart(), NewLines: h.GetNewLines(), Lines: []jsonLine{},
582 }
583 for _, l := range h.GetLines() {
584 jh.Lines = append(jh.Lines, jsonLine{
585 Kind: lineKindName(l.GetKind()), OldNumber: l.GetOldNumber(), NewNumber: l.GetNewNumber(), Text: l.GetText(),
586 })
587 }
588 jf.Hunks = append(jf.Hunks, jh)
589 }
590 }
591 out.Files = append(out.Files, jf)
592 }
593 for _, c := range d.GetComments() {
594 out.Comments = append(out.Comments, toJSONComment(c))
595 }
596 for _, v := range d.GetVerdicts() {
597 out.Verdicts = append(out.Verdicts, jsonAuthorVerdict{Author: v.GetAuthor(), Verdict: verdictName(v.GetVerdict()), CommentID: v.GetCommentId(), CommitID: v.GetCommitId(), CreatedAt: jsonTime(v.GetCreatedAt()), Stale: v.GetStale()})
598 }
599 return out
600}
601
602func newMRShowCmd(env *cliEnv) *cobra.Command {
603 var sinceLastRead, withDiff, markRead bool
604 cmd := &cobra.Command{
605 Use: "show <repo> <number>",
606 Short: "Show a merge request with its commits, comments and diff",
607 Long: "Show a merge request: its fields, the commits of the branch that the target lacks, the changed\n" +
608 "files and the comments. --diff adds the diff, with the line numbers to use in `mr comment`.\n" +
609 "--since-last-read shows the diff since the head recorded by --mark-read (or by the web) instead of\n" +
610 "the whole change; after a force-push it still works when the recorded commit exists, else the\n" +
611 "whole change is shown and the output says so. --mark-read records the head shown as read; it needs\n" +
612 "the mr:write scope. The mergeability line says whether the branch merges with its target now: up to\n" +
613 "date (can be fast-forwarded), behind by N commits (merges without conflicts, squash or merge commit),\n" +
614 "or in conflict with the paths that conflict (rebase needed)." + jsonMRHelp + jsonMergeabilityHelp + jsonCommentHelp + "\n" +
615 "--json adds to the merge request fields: commits (id, author, summary), commits_truncated,\n" +
616 "diff_base_id (the commit the diff starts from), stats (files_changed, additions, deletions),\n" +
617 "diff_truncated, files (old_path, new_path, status, additions, deletions, binary, truncated, omitted (generated, large, budget or unavailable; absent when the hunks are\n" +
618 "not omitted) and, with --diff, hunks of lines with kind, old_number, new_number and text), comments, last_read_id\n" +
619 "and last_read_lost; verdicts (author, verdict, comment_id, commit_id, created_at, stale).",
620 Args: cobra.ExactArgs(2),
621 ValidArgsFunction: completeMRRepoThenNumber(env),
622 }
623 cmd.Flags().BoolVar(&withDiff, "diff", false, "include the diff")
624 cmd.Flags().BoolVar(&sinceLastRead, "since-last-read", false, "diff since the head last marked read")
625 cmd.Flags().BoolVar(&markRead, "mark-read", false, "record the head shown as read (needs mr:write)")
626 asJSON := addJSONFlag(cmd)
627 cmd.RunE = func(cmd *cobra.Command, args []string) error {
628 n, err := parseNumber(args[1])
629 if err != nil {
630 return err
631 }
632 c, err := env.client(cmd)
633 if err != nil {
634 return err
635 }
636 ctx := env.ctx(cmd)
637 res, err := c.MergeRequests().GetMergeRequest(ctx, connect.NewRequest(&ermite.GetMergeRequestRequest{
638 Repo: args[0], Number: n, SinceLastRead: sinceLastRead,
639 }))
640 if err != nil {
641 return c.Describe(err)
642 }
643 d := res.Msg
644 if *asJSON {
645 err = writeJSON(cmd.OutOrStdout(), toJSONDetail(d, withDiff, c.URL()))
646 } else {
647 err = printMRDetail(cmd.OutOrStdout(), d, withDiff, sinceLastRead)
648 }
649 if err != nil {
650 return err
651 }
652 if markRead && d.GetMergeRequest().GetHeadId() != "" {
653 _, err = c.MergeRequests().MarkRead(ctx, connect.NewRequest(&ermite.MarkReadRequest{
654 Repo: args[0], Number: n, HeadId: d.GetMergeRequest().GetHeadId(),
655 }))
656 if err != nil {
657 return c.Describe(err)
658 }
659 }
660 if d.GetLastReadLost() {
661 noticef(cmd, "the head you last read is gone (force-push?): showing the whole change")
662 }
663 return nil
664 }
665 return cmd
666}
667
668func printMRDetail(w io.Writer, d *ermite.GetMergeRequestResponse, withDiff, since bool) error {
669 m := d.GetMergeRequest()
670 desc := m.GetDescription()
671 if desc == "" {
672 desc = "-"
673 }
674 pairs := [][2]string{
675 {"merge request", fmt.Sprintf("%s!%d", m.GetRepo(), m.GetNumber())},
676 {"title", m.GetTitle()},
677 {"state", stateName(m.GetState())},
678 {"branches", m.GetSourceBranch() + " -> " + m.GetTargetBranch()},
679 {"author", m.GetAuthor()},
680 {"created", shortTime(m.GetCreatedAt(), "-")},
681 {"updated", shortTime(m.GetUpdatedAt(), "-")},
682 {"head", orDash(m.GetHeadId())},
683 }
684 if m.GetState() == ermite.MergeRequestState_MERGE_REQUEST_STATE_MERGED {
685 merged := orDash(m.GetMergedCommitId()) + " (" + modeName(m.GetMergeMode()) + ")"
686 pairs = append(pairs, [2]string{"merged", merged})
687 if m.GetAutoMerged() {
688 pairs = append(pairs, [2]string{"auto-merged", "yes, by the server once the checks passed"})
689 }
690 }
691 if am := m.GetAutoMerge(); am != nil && m.GetState() == ermite.MergeRequestState_MERGE_REQUEST_STATE_OPEN {
692 pairs = append(pairs, [2]string{"auto-merge", modeName(am.GetMode()) + " when ready (enabled by " + am.GetEnabledBy() + ")"})
693 }
694 if mg := toJSONMergeability(m.GetMergeability()); mg != nil && m.GetState() == ermite.MergeRequestState_MERGE_REQUEST_STATE_OPEN {
695 pairs = append(pairs, [2]string{"mergeability", mergeabilityText(mg)})
696 }
697 if len(d.GetVerdicts()) > 0 {
698 var verdicts []string
699 for _, v := range d.GetVerdicts() {
700 var label string
701 switch v.GetVerdict() {
702 case ermite.Verdict_VERDICT_APPROVE:
703 label = "approved"
704 case ermite.Verdict_VERDICT_CHANGES_REQUESTED:
705 label = "changes requested"
706 default:
707 label = fmt.Sprintf("verdict %d", v.GetVerdict())
708 }
709 if v.GetStale() {
710 label += " (stale)"
711 }
712 verdicts = append(verdicts, v.GetAuthor()+" "+label)
713 }
714 pairs = append(pairs, [2]string{"verdicts", strings.Join(verdicts, ", ")})
715 }
716 if err := fields(w, pairs); err != nil {
717 return err
718 }
719 _, _ = fmt.Fprintf(w, "\n%s\n", indentText(desc))
720
721 _, _ = fmt.Fprintf(w, "\ncommits (%d%s)\n", len(d.GetCommits()), plus(d.GetCommitsTruncated()))
722 for _, c := range d.GetCommits() {
723 _, _ = fmt.Fprintf(w, " %s %s %s\n", shortID(c.GetId()), clean(c.GetAuthor().GetName()), clean(c.GetSummary()))
724 }
725
726 st := d.GetStats()
727 what := "changes"
728 if since && !d.GetLastReadLost() && d.GetLastReadId() != "" {
729 what = "changes since " + shortID(d.GetLastReadId())
730 }
731 _, _ = fmt.Fprintf(w, "\n%s: %d file(s), +%d -%d, from %s\n", what, st.GetFilesChanged(), st.GetAdditions(), st.GetDeletions(), orDash(shortID(d.GetDiffBaseId())))
732 for _, f := range d.GetDiff().GetFiles() {
733 path := f.GetNewPath()
734 if path == "" {
735 path = f.GetOldPath()
736 }
737 note := ""
738 if f.GetTruncated() {
739 note = " (too large, not shown)"
740 }
741 _, _ = fmt.Fprintf(w, " %-8s +%d -%d %s%s\n", fileStatusName(f.GetStatus()), f.GetAdditions(), f.GetDeletions(), clean(path), note)
742 }
743 if d.GetDiff().GetTruncated() {
744 _, _ = fmt.Fprintln(w, " (the diff is truncated)")
745 }
746
747 _, _ = fmt.Fprintf(w, "\ncomments (%d)\n", len(d.GetComments()))
748 var ordered []*ermite.Comment
749 for _, root := range d.GetComments() {
750 if root.GetReplyTo() != "" {
751 continue
752 }
753 ordered = append(ordered, root)
754 for _, reply := range d.GetComments() {
755 if reply.GetReplyTo() == root.GetId() {
756 ordered = append(ordered, reply)
757 }
758 }
759 }
760 for _, c := range ordered {
761 where := "general"
762 if c.GetPath() != "" {
763 where = fmt.Sprintf("%s:%d (%s)", clean(c.GetPath()), c.GetLine(), sideName(c.GetSide()))
764 }
765 if c.GetStartLine() > 0 {
766 where = fmt.Sprintf("%s:lines %d-%d (%s)", clean(c.GetPath()), c.GetStartLine(), c.GetLine(), sideName(c.GetSide()))
767 }
768 mark := ""
769 if c.GetEditedAt() != nil {
770 mark += " (edited)"
771 }
772 if c.GetDeleted() {
773 mark += " [deleted]"
774 }
775 if c.GetVerdict() != ermite.Verdict_VERDICT_UNSPECIFIED {
776 mark += " [" + verdictName(c.GetVerdict()) + "]"
777 }
778 if c.GetResolved() {
779 mark += " [resolved]"
780 }
781 prefix := " "
782 body := indentText(c.GetText())
783 if c.GetReplyTo() != "" {
784 prefix += " "
785 body = " " + strings.ReplaceAll(body, "\n", "\n ")
786 }
787 _, _ = fmt.Fprintf(w, "%s#%s %s, %s, %s%s\n%s\n", prefix, c.GetId(), clean(c.GetAuthor()), shortTime(c.GetCreatedAt(), "-"), where, mark, body)
788 }
789 if withDiff {
790 printDiff(w, d.GetDiff())
791 }
792 return nil
793}
794
795func orDash(s string) string {
796 if s == "" {
797 return "-"
798 }
799 return s
800}
801
802func plus(truncated bool) string {
803 if truncated {
804 return "+"
805 }
806 return ""
807}
808
809func shortID(id string) string {
810 if len(id) > 10 {
811 return id[:10]
812 }
813 return id
814}
815
816// indentText indents a multi-line text by four spaces, making each line safe
817// for a terminal.
818func indentText(s string) string {
819 lines := strings.Split(s, "\n")
820 for i, l := range lines {
821 lines[i] = " " + client.Clean(l)
822 }
823 return strings.Join(lines, "\n")
824}
825
826// printDiff prints the diff with a gutter of the old and new line numbers,
827// which are the numbers `mr comment --line` takes with --side old or new.
828func printDiff(w io.Writer, d *ermite.Diff) {
829 _, _ = fmt.Fprintln(w, "\ndiff (old and new line numbers on the left)")
830 num := func(n int32) string {
831 if n == 0 {
832 return ""
833 }
834 return strconv.Itoa(int(n))
835 }
836 for _, f := range d.GetFiles() {
837 _, _ = fmt.Fprintf(w, "\n--- %s\n+++ %s\n", clean(orDash(f.GetOldPath())), clean(orDash(f.GetNewPath())))
838 if f.GetBinary() {
839 _, _ = fmt.Fprintln(w, "(binary file)")
840 }
841 if f.GetTruncated() {
842 _, _ = fmt.Fprintln(w, "(too large, not shown)")
843 }
844 for _, h := range f.GetHunks() {
845 _, _ = fmt.Fprintf(w, "@@ -%d,%d +%d,%d @@ %s\n", h.GetOldStart(), h.GetOldLines(), h.GetNewStart(), h.GetNewLines(), clean(h.GetHeader()))
846 for _, l := range h.GetLines() {
847 sign := map[ermite.LineKind]string{
848 ermite.LineKind_LINE_KIND_ADDITION: "+", ermite.LineKind_LINE_KIND_DELETION: "-",
849 }[l.GetKind()]
850 if sign == "" {
851 sign = " "
852 }
853 _, _ = fmt.Fprintf(w, "%5s %5s %s%s\n", num(l.GetOldNumber()), num(l.GetNewNumber()), sign, clean(l.GetText()))
854 }
855 }
856 }
857}
858
859func newMRCommentCmd(env *cliEnv) *cobra.Command {
860 var message, path, side, line, reply string
861 var approve, requestChanges bool
862 cmd := &cobra.Command{
863 Use: "comment <repo> <number>",
864 Short: "Comment on a merge request",
865 Long: "Add a Markdown note (at most 8000 characters); ^N refers to a note in this merge request.\n" +
866 "--reply replies to a root note. --line accepts N or A-B. --approve and --request-changes\n" +
867 "set a verdict (needs mr:review) and allow an empty message.\n" +
868 "-m - reads it from standard input. Without --path it is a general comment. With --path, --line and\n" +
869 "--side (default new) it is attached to a line of the current diff: the path as in `mr show --diff`\n" +
870 "(the new path, the old one for a deleted file), the line number on the old or new side; a line\n" +
871 "that is not in the diff is refused. Needs the mr:write scope." + jsonCommentHelp,
872 Args: cobra.ExactArgs(2),
873 ValidArgsFunction: completeMRRepoThenNumber(env),
874 }
875 cmd.Flags().StringVarP(&message, "message", "m", "", "Markdown text, or - to read standard input (required unless setting a verdict)")
876 cmd.Flags().StringVar(&path, "path", "", "file the comment is attached to")
877 cmd.Flags().StringVar(&line, "line", "", "1-based line N or range A-B on --side")
878 cmd.Flags().StringVar(&reply, "reply", "", "reply to root note (^12, #12 or 12)")
879 cmd.Flags().BoolVar(&approve, "approve", false, "approve (needs mr:review)")
880 cmd.Flags().BoolVar(&requestChanges, "request-changes", false, "request changes (needs mr:review)")
881 cmd.Flags().StringVar(&side, "side", sideNew, "side the line counts on: old or new")
882 cmd.MarkFlagsMutuallyExclusive("approve", "request-changes")
883 for _, flag := range []string{"path", "line", "side", "approve", "request-changes"} {
884 cmd.MarkFlagsMutuallyExclusive("reply", flag)
885 }
886 // A verdict note may omit its message.
887 _ = cmd.RegisterFlagCompletionFunc("side", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
888 return []string{sideOld, sideNew}, cobra.ShellCompDirectiveNoFileComp
889 })
890 asJSON := addJSONFlag(cmd)
891 cmd.RunE = func(cmd *cobra.Command, args []string) error {
892 n, err := parseNumber(args[1])
893 if err != nil {
894 return err
895 }
896 text, err := readText(cmd, message)
897 if err != nil {
898 return err
899 }
900 if !cmd.Flags().Changed("message") && !approve && !requestChanges {
901 return errors.New("--message is required unless --approve or --request-changes is set")
902 }
903 req := &ermite.AddCommentRequest{Repo: args[0], Number: n, Text: text}
904 if approve {
905 req.Verdict = ermite.Verdict_VERDICT_APPROVE
906 }
907 if requestChanges {
908 req.Verdict = ermite.Verdict_VERDICT_CHANGES_REQUESTED
909 }
910 if cmd.Flags().Changed("reply") {
911 req.ReplyTo, err = parseNoteID(reply)
912 if err != nil {
913 return err
914 }
915 }
916 switch {
917 case path != "":
918 if line == "" {
919 return errors.New("--line is required with --path: give the line number")
920 }
921 req.StartLine, req.Line, err = parseLineRange(line)
922 if err != nil {
923 return err
924 }
925 if req.Side, err = parseSide(side); err != nil {
926 return err
927 }
928 req.Path = path
929 case cmd.Flags().Changed("line") || cmd.Flags().Changed("side"):
930 return errors.New("--line and --side need --path")
931 }
932 c, err := env.client(cmd)
933 if err != nil {
934 return err
935 }
936 res, err := c.MergeRequests().AddComment(env.ctx(cmd), connect.NewRequest(req))
937 if err != nil {
938 return c.Describe(err)
939 }
940 if *asJSON {
941 return writeJSON(cmd.OutOrStdout(), toJSONComment(res.Msg.GetComment()))
942 }
943 _, err = fmt.Fprintf(cmd.OutOrStdout(), "comment %s added to %s!%d\n", res.Msg.GetComment().GetId(), clean(args[0]), n)
944 return err
945 }
946 return cmd
947}
948
949func parseNoteID(s string) (string, error) {
950 id := strings.TrimLeft(strings.TrimSpace(s), "^#")
951 n, err := strconv.ParseInt(id, 10, 64)
952 if err != nil || n < 1 {
953 return "", fmt.Errorf("invalid note id %q: use ^12, #12 or 12", s)
954 }
955 return strconv.FormatInt(n, 10), nil
956}
957
958func parseLineRange(s string) (start, end int32, err error) {
959 parts := strings.Split(s, "-")
960 invalid := fmt.Errorf("invalid --line %q: use N or A-B with 1 <= A < B", s)
961 if len(parts) < 1 || len(parts) > 2 {
962 return 0, 0, invalid
963 }
964 parse := func(v string) (int32, error) {
965 n, e := strconv.ParseInt(v, 10, 32)
966 if e != nil || n < 1 {
967 return 0, invalid
968 }
969 return int32(n), nil
970 }
971 end, err = parse(parts[len(parts)-1])
972 if err != nil {
973 return 0, 0, err
974 }
975 if len(parts) == 2 {
976 start, err = parse(parts[0])
977 if err != nil || start >= end {
978 return 0, 0, invalid
979 }
980 }
981 return start, end, nil
982}
983
984func newMREditCommentCmd(env *cliEnv) *cobra.Command { return newMRNoteMutationCmd(env, true) }
985func newMRDeleteCommentCmd(env *cliEnv) *cobra.Command { return newMRNoteMutationCmd(env, false) }
986
987func newMRNoteMutationCmd(env *cliEnv, edit bool) *cobra.Command {
988 verb := "delete"
989 if edit {
990 verb = "edit"
991 }
992 var message string
993 cmd := &cobra.Command{Use: verb + "-comment <repo> <number> <comment-id>", Short: verb + " your own merge request note", Long: "Edit or delete your own note on an open merge request. Needs mr:write. Verdicts are unchanged." + jsonCommentHelp, Args: cobra.ExactArgs(3), ValidArgsFunction: completeMRRepoThenNumber(env)}
994 if edit {
995 cmd.Flags().StringVarP(&message, "message", "m", "", "Markdown text, or - to read standard input (required)")
996 _ = cmd.MarkFlagRequired("message")
997 }
998 asJSON := addJSONFlag(cmd)
999 cmd.RunE = func(cmd *cobra.Command, args []string) error {
1000 n, err := parseNumber(args[1])
1001 if err != nil {
1002 return err
1003 }
1004 id, err := parseNoteID(args[2])
1005 if err != nil {
1006 return err
1007 }
1008 text, err := readText(cmd, message)
1009 if err != nil {
1010 return err
1011 }
1012 c, err := env.client(cmd)
1013 if err != nil {
1014 return err
1015 }
1016 var note *ermite.Comment
1017 if edit {
1018 res, e := c.MergeRequests().EditComment(env.ctx(cmd), connect.NewRequest(&ermite.EditCommentRequest{Repo: args[0], Number: n, CommentId: id, Text: text}))
1019 if e != nil {
1020 return c.Describe(e)
1021 }
1022 note = res.Msg.GetComment()
1023 } else {
1024 res, e := c.MergeRequests().DeleteComment(env.ctx(cmd), connect.NewRequest(&ermite.DeleteCommentRequest{Repo: args[0], Number: n, CommentId: id}))
1025 if e != nil {
1026 return c.Describe(e)
1027 }
1028 note = res.Msg.GetComment()
1029 }
1030 if *asJSON {
1031 return writeJSON(cmd.OutOrStdout(), toJSONComment(note))
1032 }
1033 past := "deleted"
1034 if edit {
1035 past = "edited"
1036 }
1037 _, err = fmt.Fprintf(cmd.OutOrStdout(), "comment %s of %s!%d %s\n", clean(id), clean(args[0]), n, past)
1038 return err
1039 }
1040 return cmd
1041}
1042
1043func newMRResolveCmd(env *cliEnv) *cobra.Command {
1044 var undo bool
1045 cmd := &cobra.Command{
1046 Use: "resolve <repo> <number> <comment-id>",
1047 Short: "Mark a comment resolved",
1048 Long: "Mark a comment of a merge request resolved, or unresolved with --undo. Doing it twice is not an\n" +
1049 "error. Needs the mr:write scope." + jsonCommentHelp,
1050 Args: cobra.ExactArgs(3),
1051 ValidArgsFunction: completeMRRepoThenNumber(env),
1052 }
1053 cmd.Flags().BoolVar(&undo, "undo", false, "mark the comment unresolved instead")
1054 asJSON := addJSONFlag(cmd)
1055 cmd.RunE = func(cmd *cobra.Command, args []string) error {
1056 n, err := parseNumber(args[1])
1057 if err != nil {
1058 return err
1059 }
1060 id := strings.TrimPrefix(strings.TrimSpace(args[2]), "#")
1061 c, err := env.client(cmd)
1062 if err != nil {
1063 return err
1064 }
1065 res, err := c.MergeRequests().ResolveComment(env.ctx(cmd), connect.NewRequest(&ermite.ResolveCommentRequest{
1066 Repo: args[0], Number: n, CommentId: id, Resolved: !undo,
1067 }))
1068 if err != nil {
1069 return c.Describe(err)
1070 }
1071 if *asJSON {
1072 return writeJSON(cmd.OutOrStdout(), toJSONComment(res.Msg.GetComment()))
1073 }
1074 verb := "resolved"
1075 if undo {
1076 verb = "reopened"
1077 }
1078 _, err = fmt.Fprintf(cmd.OutOrStdout(), "comment %s of %s!%d %s\n", clean(id), clean(args[0]), n, verb)
1079 return err
1080 }
1081 return cmd
1082}
1083
1084func newMRMergeCmd(env *cliEnv) *cobra.Command {
1085 var mode string
1086 var deleteBranch bool
1087 var head string
1088 var auto, cancelAuto bool
1089 cmd := &cobra.Command{
1090 Use: "merge <repo> <number>",
1091 Short: "Merge a merge request",
1092 Long: "Merge an open merge request with --mode (default fast-forward; the repository settings may allow\n" +
1093 "only some modes, see `ermite repo edit --merge-modes`):\n" +
1094 " fast-forward the target branch moves to the head and no commit is created. The target must be\n" +
1095 " an ancestor of the head, else rebase the branch and push it again, or use another mode.\n" +
1096 " squash one new commit with the tree of the merge of the head and the target, the target tip\n" +
1097 " as only parent. The branch must merge without conflicts.\n" +
1098 " merge a merge commit with two parents, the target tip and the head. The branch must merge\n" +
1099 " without conflicts.\n" +
1100 "A squash and a merge commit are signed with the server's own key, generated automatically when the\n" +
1101 "server first starts; `ermite signing-key show` prints it. The server never rebases. `ermite mr show`\n" +
1102 "prints the mergeability (up to date, behind, conflict); the server checks again when merging and\n" +
1103 "refuses a merge that is not possible, saying why.\n\n" +
1104 "The server merges only if the source branch still points to the head you reviewed, so --head is\n" +
1105 "required: give the full id of the head that `ermite mr show <repo> <number>` printed when you\n" +
1106 "reviewed the change. If the branch moved since, the merge is refused: review again. Needs the\n" +
1107 "mr:merge scope.\n\n" +
1108 "The merge answers as soon as the target branch has moved. --delete-branch asks the server to delete\n" +
1109 "the source branch right after, in the background. The merge is refused when the branch is the\n" +
1110 "default branch or used by another open merge request. If the deletion later fails (the branch\n" +
1111 "moved, say), the merge stands and the branch is kept.\n\n" +
1112 "--auto does not merge now: it asks the server to merge by itself, with --mode, once CI has settled\n" +
1113 "with at least one successful check on the head and every check allows it. Needs the mr:merge scope,\n" +
1114 "a server with CI, and `ermite repo edit --allow-auto-merge` on the repository. A new push to the\n" +
1115 "source branch, a change of the settings or of your permissions cancels it. --auto takes --head\n" +
1116 "like a plain merge: it is enabled only if the source branch still points to it. --cancel-auto cancels a pending auto-merge." + jsonMRHelp +
1117 "\n--json adds source_branch_deleted (true when the deletion was requested: the server deletes the branch right after the merge).",
1118 Args: cobra.ExactArgs(2),
1119 ValidArgsFunction: completeMRRepoThenNumber(env),
1120 }
1121 cmd.Flags().StringVar(&mode, "mode", modeFastForward, "merge mode: fast-forward, squash or merge (a merge commit)")
1122 cmd.Flags().StringVar(&head, "head", "", "full id of the head you reviewed, from `ermite mr show` (required)")
1123 cmd.Flags().BoolVar(&deleteBranch, "delete-branch", false, "delete the source branch after the merge")
1124 cmd.Flags().BoolVar(&auto, "auto", false, "merge by itself once the checks passed (needs `repo edit --allow-auto-merge`)")
1125 cmd.Flags().BoolVar(&cancelAuto, "cancel-auto", false, "cancel the pending auto-merge")
1126 cmd.MarkFlagsMutuallyExclusive("auto", "cancel-auto")
1127 cmd.MarkFlagsMutuallyExclusive("cancel-auto", "delete-branch")
1128 cmd.MarkFlagsMutuallyExclusive("cancel-auto", "head")
1129 cmd.MarkFlagsMutuallyExclusive("auto", "delete-branch")
1130 _ = cmd.RegisterFlagCompletionFunc("mode", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
1131 return []string{modeFastForward, modeSquash, modeMerge}, cobra.ShellCompDirectiveNoFileComp
1132 })
1133 asJSON := addJSONFlag(cmd)
1134 cmd.RunE = func(cmd *cobra.Command, args []string) error {
1135 n, err := parseNumber(args[1])
1136 if err != nil {
1137 return err
1138 }
1139 if cancelAuto {
1140 return runMRCancelAuto(env, cmd, args[0], n, *asJSON)
1141 }
1142 pbMode, err := parseMode(mode)
1143 if err != nil {
1144 return err
1145 }
1146 head = strings.TrimSpace(head)
1147 if head == "" {
1148 return fmt.Errorf("--head is required: run `ermite mr show %s %d` and give the head id it prints, "+
1149 "so that only the commit you reviewed is merged", args[0], n)
1150 }
1151 if auto {
1152 return runMREnableAuto(env, cmd, args[0], n, pbMode, head, *asJSON)
1153 }
1154 c, err := env.client(cmd)
1155 if err != nil {
1156 return err
1157 }
1158 ctx := env.ctx(cmd)
1159 if pbMode == ermite.MergeMode_MERGE_MODE_MERGE_COMMIT {
1160 if err := requireFeature(ctx, c, client.FeatureMergeability, "has no merge commit mode (--mode merge)"); err != nil {
1161 return err
1162 }
1163 }
1164 res, err := c.MergeRequests().MergeMergeRequest(ctx, connect.NewRequest(&ermite.MergeMergeRequestRequest{
1165 Repo: args[0], Number: n, Mode: pbMode, HeadId: head, DeleteSourceBranch: deleteBranch,
1166 }))
1167 if err != nil {
1168 return c.Describe(err)
1169 }
1170 m := res.Msg.GetMergeRequest()
1171 deleted := res.Msg.GetSourceBranchDeleted()
1172 if *asJSON {
1173 return writeJSON(cmd.OutOrStdout(), jsonMerged{jsonMergeRequest: toJSONMergeRequest(m, c.URL()), SourceBranchDeleted: deleted})
1174 }
1175 out := cmd.OutOrStdout()
1176 _, err = fmt.Fprintf(out, "merged %s!%d into %s (%s) at %s\n", clean(m.GetRepo()), m.GetNumber(),
1177 clean(m.GetTargetBranch()), modeName(m.GetMergeMode()), shortID(m.GetMergedCommitId()))
1178 if err == nil && pbMode != ermite.MergeMode_MERGE_MODE_FAST_FORWARD {
1179 _, err = fmt.Fprintln(out, signedNote(ctx, c))
1180 }
1181 if err == nil && deleted {
1182 _, err = fmt.Fprintf(out, "deleting branch %s (done by the server after the merge)\n", clean(m.GetSourceBranch()))
1183 }
1184 return err
1185 }
1186 return cmd
1187}
1188
1189// runMREnableAuto is `mr merge --auto`: it asks the server to merge once ready.
1190func runMREnableAuto(env *cliEnv, cmd *cobra.Command, repo string, n int64, mode ermite.MergeMode, head string, asJSON bool) error {
1191 c, err := env.client(cmd)
1192 if err != nil {
1193 return err
1194 }
1195 ctx := env.ctx(cmd)
1196 if err := requireFeature(ctx, c, client.FeatureAutoMerge, "cannot merge by itself (--auto)"); err != nil {
1197 return err
1198 }
1199 res, err := c.MergeRequests().EnableAutoMerge(ctx, connect.NewRequest(&ermite.EnableAutoMergeRequest{Repo: repo, Number: n, Mode: mode, HeadId: head}))
1200 if err != nil {
1201 return c.Describe(err)
1202 }
1203 m := res.Msg.GetMergeRequest()
1204 if asJSON {
1205 return writeJSON(cmd.OutOrStdout(), toJSONMergeRequest(m, c.URL()))
1206 }
1207 _, err = fmt.Fprintf(cmd.OutOrStdout(), "auto-merge enabled on %s!%d: %s into %s when ready (enabled by %s)\n", clean(m.GetRepo()), m.GetNumber(),
1208 modeName(m.GetAutoMerge().GetMode()), clean(m.GetTargetBranch()), clean(m.GetAutoMerge().GetEnabledBy()))
1209 return err
1210}
1211
1212// runMRCancelAuto is `mr merge --cancel-auto`.
1213func runMRCancelAuto(env *cliEnv, cmd *cobra.Command, repo string, n int64, asJSON bool) error {
1214 c, err := env.client(cmd)
1215 if err != nil {
1216 return err
1217 }
1218 ctx := env.ctx(cmd)
1219 if err := requireFeature(ctx, c, client.FeatureAutoMerge, "has no auto-merge to cancel (--cancel-auto)"); err != nil {
1220 return err
1221 }
1222 res, err := c.MergeRequests().CancelAutoMerge(ctx, connect.NewRequest(&ermite.CancelAutoMergeRequest{Repo: repo, Number: n}))
1223 if err != nil {
1224 return c.Describe(err)
1225 }
1226 m := res.Msg.GetMergeRequest()
1227 if asJSON {
1228 return writeJSON(cmd.OutOrStdout(), toJSONMergeRequest(m, c.URL()))
1229 }
1230 _, err = fmt.Fprintf(cmd.OutOrStdout(), "auto-merge cancelled on %s!%d\n", clean(m.GetRepo()), m.GetNumber())
1231 return err
1232}
1233
1234// signedNote says that a squash or merge commit is signed by the server's
1235// key, with its fingerprint when the server tells it.
1236func signedNote(ctx context.Context, c *client.Client) string {
1237 const how = "; `ermite signing-key show` prints the key to verify it"
1238 res, err := c.Server().GetSigningKey(ctx, connect.NewRequest(&ermite.GetSigningKeyRequest{}))
1239 if err != nil || res.Msg.GetFingerprint() == "" {
1240 return "the commit is signed by the server's key" + how
1241 }
1242 return "the commit is signed by the server's key " + clean(res.Msg.GetFingerprint()) + how
1243}
1244
1245// requireFeature refuses to go on with a server that does not list the
1246// feature. A server whose features cannot be read is refused too.
1247func requireFeature(ctx context.Context, c *client.Client, feature, what string) error {
1248 res, err := c.Server().GetVersion(ctx, connect.NewRequest(&ermite.GetVersionRequest{}))
1249 if err != nil {
1250 return c.Describe(err)
1251 }
1252 if !slices.Contains(res.Msg.GetFeatures(), feature) {
1253 return fmt.Errorf("the server does not support %s, so it %s (upgrade the server, see `ermite version`)", feature, what)
1254 }
1255 return nil
1256}
1257
1258func newMRCloseCmd(env *cliEnv) *cobra.Command {
1259 cmd := &cobra.Command{
1260 Use: "close <repo> <number>",
1261 Short: "Close a merge request without merging it",
1262 Long: "Close an open merge request without merging it. A closed merge request cannot be reopened: open a\n" +
1263 "new one. Prints a confirmation, then the full web URL on its own line. Needs the mr:write scope." + jsonMRHelp,
1264 Args: cobra.ExactArgs(2),
1265 ValidArgsFunction: completeMRRepoThenNumber(env),
1266 }
1267 asJSON := addJSONFlag(cmd)
1268 cmd.RunE = func(cmd *cobra.Command, args []string) error {
1269 n, err := parseNumber(args[1])
1270 if err != nil {
1271 return err
1272 }
1273 c, err := env.client(cmd)
1274 if err != nil {
1275 return err
1276 }
1277 res, err := c.MergeRequests().CloseMergeRequest(env.ctx(cmd), connect.NewRequest(&ermite.CloseMergeRequestRequest{Repo: args[0], Number: n}))
1278 if err != nil {
1279 return c.Describe(err)
1280 }
1281 return outputMR(cmd, res.Msg.GetMergeRequest(), *asJSON, "closed", c.URL())
1282 }
1283 return cmd
1284}