fix(gitlab_client): prevent duplicate pipelines in gitlab merge requests (#2745)

* fix(gitlab_client): change CommitStatus update logic to prevent duplicated pipelines in MRs

* chore: refactor refTarget logic

* chore: fix tests

* chore: fix lint

* chore: remove nested if
This commit is contained in:
Michel Z. Santello
2022-12-07 18:14:39 -03:00
committed by GitHub
parent b6e1c61127
commit c800f706e4
2 changed files with 19 additions and 2 deletions

View File

@@ -244,12 +244,26 @@ func (g *GitlabClient) UpdateStatus(repo models.Repo, pull models.PullRequest, s
case models.SuccessCommitStatus:
gitlabState = gitlab.Success
}
_, _, err := g.Client.Commits.SetCommitStatus(repo.FullName, pull.HeadCommit, &gitlab.SetCommitStatusOptions{
mr, err := g.GetMergeRequest(pull.BaseRepo.FullName, pull.Num)
if err != nil {
return err
}
// refTarget is set to current branch if no pipeline is assigned to the commit,
// otherwise it is set to the pipeline created by the merge_request_event rule
refTarget := pull.HeadBranch
if mr.Pipeline != nil {
switch mr.Pipeline.Source {
case "merge_request_event":
refTarget = fmt.Sprintf("refs/merge-requests/%d/head", pull.Num)
}
}
_, _, err = g.Client.Commits.SetCommitStatus(repo.FullName, pull.HeadCommit, &gitlab.SetCommitStatusOptions{
State: gitlabState,
Context: gitlab.String(src),
Description: gitlab.String(description),
TargetURL: &url,
Ref: gitlab.String(pull.HeadBranch),
Ref: gitlab.String(refTarget),
})
return err
}

View File

@@ -216,6 +216,9 @@ func TestGitlabClient_UpdateStatus(t *testing.T) {
Equals(t, exp, string(body))
defer r.Body.Close() // nolint: errcheck
w.Write([]byte("{}")) // nolint: errcheck
case "/api/v4/projects/runatlantis%2Fatlantis/merge_requests/1":
w.WriteHeader(http.StatusOK)
w.Write([]byte(pipelineSuccess)) // nolint: errcheck
case "/api/v4/":
// Rate limiter requests.
w.WriteHeader(http.StatusOK)