-
-
Notifications
You must be signed in to change notification settings - Fork 398
/
gitlab_mr_discussion.go
217 lines (194 loc) 路 6.9 KB
/
gitlab_mr_discussion.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package gitlab
import (
"context"
"fmt"
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/xanzy/go-gitlab"
"golang.org/x/sync/errgroup"
"github.com/reviewdog/reviewdog"
"github.com/reviewdog/reviewdog/proto/rdf"
"github.com/reviewdog/reviewdog/service/commentutil"
"github.com/reviewdog/reviewdog/service/serviceutil"
)
const (
invalidSuggestionPre = "<details><summary>reviewdog suggestion error</summary>"
invalidSuggestionPost = "</details>"
)
// MergeRequestDiscussionCommenter is a comment and diff service for GitLab MergeRequest.
//
// API:
//
// https://docs.gitlab.com/ee/api/discussions.html#create-new-merge-request-discussion
// POST /projects/:id/merge_requests/:merge_request_iid/discussions
type MergeRequestDiscussionCommenter struct {
cli *gitlab.Client
pr int
sha string
projects string
muComments sync.Mutex
postComments []*reviewdog.Comment
// wd is working directory relative to root of repository.
wd string
}
// NewGitLabMergeRequestDiscussionCommenter returns a new MergeRequestDiscussionCommenter service.
// MergeRequestDiscussionCommenter service needs git command in $PATH.
func NewGitLabMergeRequestDiscussionCommenter(cli *gitlab.Client, owner, repo string, pr int, sha string) (*MergeRequestDiscussionCommenter, error) {
workDir, err := serviceutil.GitRelWorkdir()
if err != nil {
return nil, fmt.Errorf("MergeRequestDiscussionCommenter needs 'git' command: %w", err)
}
return &MergeRequestDiscussionCommenter{
cli: cli,
pr: pr,
sha: sha,
projects: owner + "/" + repo,
wd: workDir,
}, nil
}
// Post accepts a comment and holds it. Flush method actually posts comments to
// GitLab in parallel.
func (g *MergeRequestDiscussionCommenter) Post(_ context.Context, c *reviewdog.Comment) error {
c.Result.Diagnostic.GetLocation().Path = filepath.ToSlash(
filepath.Join(g.wd, c.Result.Diagnostic.GetLocation().GetPath()))
g.muComments.Lock()
defer g.muComments.Unlock()
g.postComments = append(g.postComments, c)
return nil
}
// Flush posts comments which has not been posted yet.
func (g *MergeRequestDiscussionCommenter) Flush(ctx context.Context) error {
g.muComments.Lock()
defer g.muComments.Unlock()
postedcs, err := g.createPostedComments()
if err != nil {
return fmt.Errorf("failed to create posted comments: %w", err)
}
return g.postCommentsForEach(ctx, postedcs)
}
func (g *MergeRequestDiscussionCommenter) createPostedComments() (commentutil.PostedComments, error) {
postedcs := make(commentutil.PostedComments)
discussions, err := listAllMergeRequestDiscussion(g.cli, g.projects, g.pr, &gitlab.ListMergeRequestDiscussionsOptions{PerPage: 100})
if err != nil {
return nil, fmt.Errorf("failed to list all merge request discussions: %w", err)
}
for _, d := range discussions {
for _, note := range d.Notes {
pos := note.Position
if pos == nil || pos.NewPath == "" || pos.NewLine == 0 || note.Body == "" {
continue
}
postedcs.AddPostedComment(pos.NewPath, pos.NewLine, note.Body)
}
}
return postedcs, nil
}
func (g *MergeRequestDiscussionCommenter) postCommentsForEach(ctx context.Context, postedcs commentutil.PostedComments) error {
mr, _, err := g.cli.MergeRequests.GetMergeRequest(g.projects, g.pr, nil, gitlab.WithContext(ctx))
if err != nil {
return fmt.Errorf("failed to get merge request: %w", err)
}
targetBranch, _, err := g.cli.Branches.GetBranch(mr.TargetProjectID, mr.TargetBranch, nil)
if err != nil {
return err
}
var eg errgroup.Group
for _, c := range g.postComments {
c := c
loc := c.Result.Diagnostic.GetLocation()
lnum := int(loc.GetRange().GetStart().GetLine())
body := commentutil.MarkdownComment(c)
if suggestion := buildSuggestions(c); suggestion != "" {
body = body + "\n\n" + suggestion
}
if !c.Result.InDiffFile || lnum == 0 || postedcs.IsPosted(c, lnum, body) {
continue
}
eg.Go(func() error {
pos := &gitlab.PositionOptions{
StartSHA: gitlab.Ptr(targetBranch.Commit.ID),
HeadSHA: gitlab.Ptr(g.sha),
BaseSHA: gitlab.Ptr(targetBranch.Commit.ID),
PositionType: gitlab.Ptr("text"),
NewPath: gitlab.Ptr(loc.GetPath()),
NewLine: gitlab.Ptr(lnum),
}
if c.Result.OldPath != "" && c.Result.OldLine != 0 {
pos.OldPath = gitlab.Ptr(c.Result.OldPath)
pos.OldLine = gitlab.Ptr(c.Result.OldLine)
}
discussion := &gitlab.CreateMergeRequestDiscussionOptions{
Body: gitlab.Ptr(body),
Position: pos,
}
_, _, err := g.cli.Discussions.CreateMergeRequestDiscussion(g.projects, g.pr, discussion)
if err != nil {
return fmt.Errorf("failed to create merge request discussion: %w", err)
}
return nil
})
}
return eg.Wait()
}
func listAllMergeRequestDiscussion(cli *gitlab.Client, projectID string, mergeRequest int, opts *gitlab.ListMergeRequestDiscussionsOptions) ([]*gitlab.Discussion, error) {
discussions, resp, err := cli.Discussions.ListMergeRequestDiscussions(projectID, mergeRequest, opts)
if err != nil {
return nil, err
}
if resp.NextPage == 0 {
return discussions, nil
}
newOpts := &gitlab.ListMergeRequestDiscussionsOptions{
Page: resp.NextPage,
PerPage: opts.PerPage,
}
restDiscussions, err := listAllMergeRequestDiscussion(cli, projectID, mergeRequest, newOpts)
if err != nil {
return nil, err
}
return append(discussions, restDiscussions...), nil
}
// creates diff in markdown for suggested changes
// Ref gitlab suggestion: https://docs.gitlab.com/ee/user/project/merge_requests/reviews/suggestions.html
func buildSuggestions(c *reviewdog.Comment) string {
var sb strings.Builder
for _, s := range c.Result.Diagnostic.GetSuggestions() {
if s.Range == nil || s.Range.Start == nil || s.Range.End == nil {
continue
}
txt, err := buildSingleSuggestion(c, s)
if err != nil {
sb.WriteString(invalidSuggestionPre + err.Error() + invalidSuggestionPost + "\n")
continue
}
sb.WriteString(txt)
sb.WriteString("\n")
}
return sb.String()
}
func buildSingleSuggestion(c *reviewdog.Comment, s *rdf.Suggestion) (string, error) {
var sb strings.Builder
// we might need to use 4 or more backticks
//
// https://docs.gitlab.com/ee/user/project/merge_requests/reviews/suggestions.html#code-block-nested-in-suggestions
// > If you need to make a suggestion that involves a fenced code block, wrap your suggestion in four backticks instead of the usual three.
//
// The documentation doesn't explicitly say anything about cases more than 4 backticks,
// however it seems to be handled as intended.
txt := s.GetText()
backticks := commentutil.GetCodeFenceLength(txt)
lines := strconv.Itoa(int(s.Range.End.Line - s.Range.Start.Line))
sb.Grow(backticks + len("suggestion:-0+\n") + len(lines) + len(txt) + len("\n") + backticks)
commentutil.WriteCodeFence(&sb, backticks)
sb.WriteString("suggestion:-0+")
sb.WriteString(lines)
sb.WriteString("\n")
if txt != "" {
sb.WriteString(txt)
sb.WriteString("\n")
}
commentutil.WriteCodeFence(&sb, backticks)
return sb.String(), nil
}