forked from runatlantis/atlantis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathazuredevops_client.go
321 lines (290 loc) · 11 KB
/
azuredevops_client.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
package vcs
import (
"context"
"fmt"
"net/http"
"net/url"
"path/filepath"
"strings"
"time"
"github.com/mcdafydd/go-azuredevops/azuredevops"
"github.com/pkg/errors"
"github.com/runatlantis/atlantis/server/events/models"
"github.com/runatlantis/atlantis/server/events/vcs/common"
)
// AzureDevopsClient represents an Azure DevOps VCS client
type AzureDevopsClient struct {
Client *azuredevops.Client
ctx context.Context
}
// NewAzureDevopsClient returns a valid Azure DevOps client.
func NewAzureDevopsClient(hostname string, token string) (*AzureDevopsClient, error) {
tp := azuredevops.BasicAuthTransport{
Username: "",
Password: strings.TrimSpace(token),
}
httpClient := tp.Client()
httpClient.Timeout = time.Second * 10
var adClient, err = azuredevops.NewClient(httpClient)
if err != nil {
return nil, err
}
if hostname != "dev.azure.com" {
baseURL := fmt.Sprintf("https://%s/", hostname)
base, err := url.Parse(baseURL)
if err != nil {
return nil, errors.Wrapf(err, "invalid azure devops hostname trying to parse %s", baseURL)
}
adClient.BaseURL = *base
}
client := &AzureDevopsClient{
Client: adClient,
ctx: context.Background(),
}
return client, nil
}
// GetModifiedFiles returns the names of files that were modified in the merge request
// relative to the repo root, e.g. parent/child/file.txt.
func (g *AzureDevopsClient) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) {
var files []string
opts := azuredevops.PullRequestGetOptions{
IncludeWorkItemRefs: true,
}
owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName)
commitIDResponse, _, _ := g.Client.PullRequests.GetWithRepo(g.ctx, owner, project, repoName, pull.Num, &opts)
commitID := commitIDResponse.GetLastMergeSourceCommit().GetCommitID()
r, _, _ := g.Client.Git.GetChanges(g.ctx, owner, project, repoName, commitID)
for _, change := range r.Changes {
item := change.GetItem()
// Convert the path to a relative path from the repo's root.
relativePath := filepath.Clean("./" + item.GetPath())
files = append(files, relativePath)
// If the file was renamed, we'll want to run plan in the directory
// it was moved from as well.
changeType := azuredevops.Rename.String()
if change.ChangeType == &changeType {
// Convert the path to a relative path from the repo's root.
relativePath = filepath.Clean("./" + change.GetSourceServerItem())
files = append(files, relativePath)
}
}
return files, nil
}
// CreateComment creates a comment on a pull request.
//
// If comment length is greater than the max comment length we split into
// multiple comments.
func (g *AzureDevopsClient) CreateComment(repo models.Repo, pullNum int, comment string) error {
sepEnd := "\n```\n</details>" +
"\n<br>\n\n**Warning**: Output length greater than max comment size. Continued in next comment."
sepStart := "Continued from previous comment.\n<details><summary>Show Output</summary>\n\n" +
"```diff\n"
// maxCommentLength is the maximum number of chars allowed in a single comment
// This length was copied from the Github client - haven't found documentation
// or tested limit in Azure DevOps.
const maxCommentLength = 65536
comments := common.SplitComment(comment, maxCommentLength, sepEnd, sepStart)
owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName)
for _, c := range comments {
commentType := "text"
parentCommentID := 0
prComment := azuredevops.Comment{
CommentType: &commentType,
Content: &c,
ParentCommentID: &parentCommentID,
}
prComments := []*azuredevops.Comment{&prComment}
body := azuredevops.GitPullRequestCommentThread{
Comments: prComments,
}
_, _, err := g.Client.PullRequests.CreateComments(g.ctx, owner, project, repoName, pullNum, &body)
if err != nil {
return err
}
}
return nil
}
func (g *AzureDevopsClient) HideOldComments(repo models.Repo, pullNum int) error {
return nil
}
// PullIsApproved returns true if the merge request was approved.
// https://docs.microsoft.com/en-us/azure/devops/repos/git/branch-policies?view=azure-devops#require-a-minimum-number-of-reviewers
func (g *AzureDevopsClient) PullIsApproved(repo models.Repo, pull models.PullRequest) (bool, error) {
opts := azuredevops.PullRequestGetOptions{
IncludeWorkItemRefs: true,
}
owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName)
adPull, _, err := g.Client.PullRequests.GetWithRepo(g.ctx, owner, project, repoName, pull.Num, &opts)
if err != nil {
return false, errors.Wrap(err, "getting pull request")
}
for _, review := range adPull.Reviewers {
if review == nil {
continue
}
if review.GetVote() == azuredevops.VoteApproved {
return true, nil
}
}
return false, nil
}
// PullIsMergeable returns true if the merge request can be merged.
func (g *AzureDevopsClient) PullIsMergeable(repo models.Repo, pull models.PullRequest) (bool, error) {
opts := azuredevops.PullRequestGetOptions{
IncludeWorkItemRefs: true,
}
owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName)
adPull, _, err := g.Client.PullRequests.GetWithRepo(g.ctx, owner, project, repoName, pull.Num, &opts)
if err != nil {
return false, errors.Wrap(err, "getting pull request")
}
if *adPull.MergeStatus != azuredevops.MergeConflicts.String() &&
*adPull.MergeStatus != azuredevops.MergeRejectedByPolicy.String() {
return true, nil
}
return false, nil
}
// GetPullRequest returns the pull request.
func (g *AzureDevopsClient) GetPullRequest(repo models.Repo, num int) (*azuredevops.GitPullRequest, error) {
opts := azuredevops.PullRequestGetOptions{
IncludeWorkItemRefs: true,
}
owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName)
pull, _, err := g.Client.PullRequests.GetWithRepo(g.ctx, owner, project, repoName, num, &opts)
return pull, err
}
// UpdateStatus updates the build status of a commit.
func (g *AzureDevopsClient) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error {
adState := azuredevops.GitError.String()
switch state {
case models.PendingCommitStatus:
adState = azuredevops.GitPending.String()
case models.SuccessCommitStatus:
adState = azuredevops.GitSucceeded.String()
case models.FailedCommitStatus:
adState = azuredevops.GitFailed.String()
}
genreStr := "Atlantis Bot"
status := azuredevops.GitPullRequestStatus{}
status.Context = &azuredevops.GitStatusContext{
Name: &src,
Genre: &genreStr,
}
status.Description = &description
status.State = &adState
if url != "" {
status.TargetURL = &url
}
owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName)
opts := azuredevops.PullRequestListOptions{}
source, resp, err := g.Client.PullRequests.Get(g.ctx, owner, project, pull.Num, &opts)
if err != nil {
return errors.Wrap(err, "getting pull request")
}
if resp.StatusCode != http.StatusOK {
return errors.Wrapf(err, "http response code %d getting pull request", resp.StatusCode)
}
if source.GetSupportsIterations() {
opts := azuredevops.PullRequestIterationsListOptions{}
iterations, resp, err := g.Client.PullRequests.ListIterations(g.ctx, owner, project, repoName, pull.Num, &opts)
if err != nil {
return errors.Wrap(err, "listing pull request iterations")
}
if resp.StatusCode != http.StatusOK {
return errors.Wrapf(err, "http response code %d listing pull request iterations", resp.StatusCode)
}
for _, iteration := range iterations {
if sourceRef := iteration.GetSourceRefCommit(); sourceRef != nil {
if *sourceRef.CommitID == pull.HeadCommit {
status.IterationID = iteration.ID
break
}
}
}
if iterationID := status.IterationID; iterationID != nil {
if !(*iterationID >= 1) {
return errors.New("supportsIterations was true but got invalid iteration ID or no matching iteration commit SHA was found")
}
}
}
_, resp, err = g.Client.PullRequests.CreateStatus(g.ctx, owner, project, repoName, pull.Num, &status)
if err != nil {
return errors.Wrap(err, "creating pull request status")
}
if resp.StatusCode != http.StatusOK {
return errors.Wrapf(err, "http response code %d creating pull request status", resp.StatusCode)
}
return err
}
// MergePull merges the merge request using the default no fast-forward strategy
// If the user has set a branch policy that disallows no fast-forward, the merge will fail
// until we handle branch policies
// https://docs.microsoft.com/en-us/azure/devops/repos/git/branch-policies?view=azure-devops
func (g *AzureDevopsClient) MergePull(pull models.PullRequest) error {
descriptor := "Atlantis Terraform Pull Request Automation"
i := "atlantis"
imageURL := "https://github.com/runatlantis/atlantis/raw/master/runatlantis.io/.vuepress/public/hero.png"
id := azuredevops.IdentityRef{
Descriptor: &descriptor,
ID: &i,
ImageURL: &imageURL,
}
// Set default pull request completion options
mcm := azuredevops.NoFastForward.String()
twi := new(bool)
*twi = true
completionOpts := azuredevops.GitPullRequestCompletionOptions{
BypassPolicy: new(bool),
BypassReason: azuredevops.String(""),
DeleteSourceBranch: new(bool),
MergeCommitMessage: azuredevops.String(common.AutomergeCommitMsg),
MergeStrategy: &mcm,
SquashMerge: new(bool),
TransitionWorkItems: twi,
TriggeredByAutoComplete: new(bool),
}
// Construct request body from supplied parameters
mergePull := new(azuredevops.GitPullRequest)
mergePull.AutoCompleteSetBy = &id
mergePull.CompletionOptions = &completionOpts
owner, project, repoName := SplitAzureDevopsRepoFullName(pull.BaseRepo.FullName)
mergeResult, _, err := g.Client.PullRequests.Merge(
g.ctx,
owner,
project,
repoName,
pull.Num,
mergePull,
completionOpts,
id,
)
if err != nil {
return errors.Wrap(err, "merging pull request")
}
if *mergeResult.MergeStatus != azuredevops.MergeSucceeded.String() {
return fmt.Errorf("could not merge pull request: %s", mergeResult.GetMergeFailureMessage())
}
return nil
}
// SplitAzureDevopsRepoFullName splits a repo full name up into its owner,
// repo and project name segments. If the repoFullName is malformed, may
// return empty strings for owner, repo, or project. Azure DevOps uses
// repoFullName format owner/project/repo.
//
// Ex. runatlantis/atlantis => (runatlantis, atlantis)
// gitlab/subgroup/runatlantis/atlantis => (gitlab/subgroup/runatlantis, atlantis)
// azuredevops/project/atlantis => (azuredevops, project, atlantis)
func SplitAzureDevopsRepoFullName(repoFullName string) (owner string, project string, repo string) {
firstSlashIdx := strings.Index(repoFullName, "/")
lastSlashIdx := strings.LastIndex(repoFullName, "/")
slashCount := strings.Count(repoFullName, "/")
if lastSlashIdx == -1 || lastSlashIdx == len(repoFullName)-1 {
return "", "", ""
}
if firstSlashIdx != lastSlashIdx && slashCount == 2 {
return repoFullName[:firstSlashIdx],
repoFullName[firstSlashIdx+1 : lastSlashIdx],
repoFullName[lastSlashIdx+1:]
}
return repoFullName[:lastSlashIdx], "", repoFullName[lastSlashIdx+1:]
}