-
Notifications
You must be signed in to change notification settings - Fork 523
/
azure_repos.go
357 lines (291 loc) 路 9.56 KB
/
azure_repos.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package comment
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)
// azureReposComment represents a comment on an Azure Repos pull request. It
// implements the Comment interface.
type azureReposComment struct {
id int64
content string
publishedDate string
href string
}
// Body returns the body of the comment
func (c *azureReposComment) Body() string {
return c.content
}
// Ref returns the reference to the comment. For Azure Repos this is an API URL
// of the comment.
func (c *azureReposComment) Ref() string {
return c.href
}
// ValidAt returns the time the comment was tagged as being valid at
func (c *azureReposComment) ValidAt() *time.Time {
return extractValidAt(c.Body())
}
// Less compares the comment to another comment and returns true if this
// comment should be sorted before the other comment.
func (c *azureReposComment) Less(other Comment) bool {
j := other.(*azureReposComment)
if c.publishedDate != j.publishedDate {
return c.publishedDate < j.publishedDate
}
return c.id < j.id
}
// IsHidden always returns false for Azure Repos since Azure Repos doesn't have a
// feature for hiding comments.
func (c *azureReposComment) IsHidden() bool {
return false
}
// AzureReposExtra contains any extra inputs that can be passed to the Azure Repos
// comment handlers.
type AzureReposExtra struct {
// Token is the Azure DevOps access token.
Token string
// Tag is used to identify the Infracost comment.
Tag string
}
// azureAPIComment represents API response structure of Azure Repos comment.
type azureAPIComment struct {
ID int64 `json:"id"`
Content string `json:"content"`
PublishedDate string `json:"publishedDate"`
IsDeleted bool `json:"isDeleted"`
Links struct {
Self struct {
Href string `json:"href"`
} `json:"self"`
} `json:"_links"`
}
// azurePATLength helps to determine if token is an Azure DevOps Personal Access Token.
const azurePATLength = 52
// newAzureReposAPIClient creates a HTTP client.
func newAzureReposAPIClient(ctx context.Context, token string) (*http.Client, error) {
accessToken, tokenType := token, "Bearer"
if len(token) == azurePATLength {
accessToken = base64.StdEncoding.EncodeToString(
[]byte(fmt.Sprintf(":%s", accessToken)),
)
tokenType = "Basic"
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{
AccessToken: accessToken,
TokenType: tokenType,
},
)
httpClient := oauth2.NewClient(ctx, ts)
return httpClient, nil
}
// buildAzureAPIURL converts repo URL to repo's API URL.
func buildAzureAPIURL(repoURL string) (string, error) {
apiURL, err := url.Parse(repoURL)
if err != nil {
return "", fmt.Errorf("error parsing repo URL %w", err)
}
urlParts := strings.Split(apiURL.Path, "_git/")
if len(urlParts) != 2 {
return "", fmt.Errorf("Invalid repo URL format %s. Expected https://dev.azure.com/org/project/_git/repo/", repoURL)
}
// The URL can contain `org@` username part. If it's present in the API URL,
// requests may result with 401 status even with the provided token.
apiURL.User = nil
apiURL.Path = fmt.Sprintf("%s_apis/git/repositories/%s", urlParts[0], urlParts[1])
if !strings.HasSuffix(apiURL.Path, "/") {
apiURL.Path += "/"
}
return apiURL.String(), nil
}
// azureReposPRHandler is a PlatformHandler for Azure Repos pull requests. It
// implements the PlatformHandler interface and contains the functions
// for finding, creating, updating, deleting comments on Azure Repos pull requests.
type azureReposPRHandler struct {
httpClient *http.Client
repoAPIURL string
prNumber int
}
// NewAzureReposPRHandler creates a new PlatformHandler for Azure Repos pull requests.
func NewAzureReposPRHandler(ctx context.Context, repoURL string, targetRef string, extra AzureReposExtra) (*CommentHandler, error) {
prNumber, err := strconv.Atoi(targetRef)
if err != nil {
return nil, errors.Wrap(err, "Error parsing targetRef as pull request number")
}
httpClient, err := newAzureReposAPIClient(ctx, extra.Token)
if err != nil {
return nil, err
}
apiURL, err := buildAzureAPIURL(repoURL)
if err != nil {
return nil, err
}
h := &azureReposPRHandler{
httpClient: httpClient,
repoAPIURL: apiURL,
prNumber: prNumber,
}
return NewCommentHandler(ctx, h, extra.Tag), nil
}
// CallFindMatchingComments calls the Azure Repos API to find the pull request
// comments that match the given tag, which has been embedded at the beginning
// of the comment.
func (h *azureReposPRHandler) CallFindMatchingComments(ctx context.Context, tag string) ([]Comment, error) {
url := fmt.Sprintf("%spullRequests/%d/threads?api-version=6.0", h.repoAPIURL, h.prNumber)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return []Comment{}, errors.Wrap(err, "Error getting comments")
}
res, err := h.httpClient.Do(req)
if err != nil {
return []Comment{}, errors.Wrap(err, "Error getting comments")
}
if res.StatusCode != http.StatusOK {
return []Comment{}, errors.Errorf("Error getting comments: %s", res.Status)
}
if res.Body != nil {
defer res.Body.Close()
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
return []Comment{}, errors.Wrap(err, "Error reading response body")
}
var resData = struct {
Value []struct {
IsDeleted bool `json:"isDeleted"`
Comments []azureAPIComment `json:"comments"`
} `json:"value"`
}{}
err = json.Unmarshal(resBody, &resData)
if err != nil {
return nil, errors.Wrap(err, "Error unmarshaling response body")
}
// This API request creates comments only at the top-level of threads,
// so we can always just pull the first comment in the thread.
var topLevelComments []Comment
for _, thread := range resData.Value {
if thread.IsDeleted {
continue
}
for _, comment := range thread.Comments {
if comment.IsDeleted || !hasTagKey(comment.Content, tag) {
continue
}
topLevelComments = append(topLevelComments, &azureReposComment{
id: comment.ID,
content: comment.Content,
href: comment.Links.Self.Href,
publishedDate: comment.PublishedDate,
})
break
}
}
return topLevelComments, nil
}
// CallCreateComment calls the Azure Repos API to create a new comment on the pull request.
func (h *azureReposPRHandler) CallCreateComment(ctx context.Context, body string) (Comment, error) {
reqData, err := json.Marshal(map[string]interface{}{
"comments": []map[string]interface{}{
{
"content": body,
"parentCommentId": 0,
"commentType": 1,
},
},
"status": 4,
})
if err != nil {
return nil, errors.Wrap(err, "Error marshaling comment body")
}
url := fmt.Sprintf("%spullRequests/%d/threads?api-version=6.0", h.repoAPIURL, h.prNumber)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqData))
if err != nil {
return nil, errors.Wrap(err, "Error creating request")
}
req.Header.Set("Content-Type", "application/json")
res, err := h.httpClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "Error creating comment")
}
if res.StatusCode != http.StatusOK {
return nil, errors.Errorf("Error creating comment: %s", res.Status)
}
if res.Body != nil {
defer res.Body.Close()
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrap(err, "Error reading response body")
}
var resData = struct {
Comments []azureAPIComment `json:"comments"`
}{}
err = json.Unmarshal(resBody, &resData)
if err != nil {
return nil, errors.Wrap(err, "Error unmarshaling response body")
}
if len(resData.Comments) == 0 {
// This error should never happen because we are creating the thread with a comment
return nil, errors.Wrap(err, "Failed to create new thread: empty comment list")
}
firstComment := resData.Comments[0]
return &azureReposComment{
id: firstComment.ID,
content: firstComment.Content,
href: firstComment.Links.Self.Href,
publishedDate: firstComment.PublishedDate,
}, nil
}
// CallUpdateComment calls the Azure Repos API to update the body of a comment on the pull request.
func (h *azureReposPRHandler) CallUpdateComment(ctx context.Context, comment Comment, body string) error {
reqData, err := json.Marshal(map[string]interface{}{
"content": body,
"parentCommentId": 0,
"commentType": 1,
})
if err != nil {
return errors.Wrap(err, "Error marshaling comment body")
}
url := fmt.Sprintf("%s?api-version=6.0", comment.Ref())
req, err := http.NewRequest("PATCH", url, bytes.NewBuffer(reqData))
if err != nil {
return errors.Wrap(err, "Error creating request")
}
req.Header.Set("Content-Type", "application/json")
res, err := h.httpClient.Do(req)
if res.Body != nil {
defer res.Body.Close()
}
return err
}
// CallDeleteComment calls the Azure Repos API to delete the pull request comment.
func (h *azureReposPRHandler) CallDeleteComment(ctx context.Context, comment Comment) error {
url := fmt.Sprintf("%s?api-version=6.0", comment.Ref())
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return errors.Wrap(err, "Error creating request")
}
res, err := h.httpClient.Do(req)
if res.Body != nil {
defer res.Body.Close()
}
return err
}
// CallHideComment calls the Azure Repos API to minimize the pull request comment.
func (h *azureReposPRHandler) CallHideComment(ctx context.Context, comment Comment) error {
return errors.New("Not implemented")
}
// AddMarkdownTags prepends tags as a markdown comment to the given string.
func (h *azureReposPRHandler) AddMarkdownTags(s string, tags []CommentTag) (string, error) {
return addMarkdownTags(s, tags)
}