Skip to content

Commit b47ae9a

Browse files
committed
check that all commit statuses have the same pipeline Id
Signed-off-by: Ricky Hariady <[email protected]>
1 parent cb4f07d commit b47ae9a

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

server/events/vcs/gitlab_client.go

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"net"
2020
"net/http"
2121
"net/url"
22+
"slices"
2223
"strings"
2324
"time"
2425

@@ -427,7 +428,6 @@ func (g *GitlabClient) UpdateStatus(logger logging.SimpleLogging, repo models.Re
427428
getCommitStatusesOptions := &gitlab.GetCommitStatusesOptions{
428429
ListOptions: gitlab.ListOptions{
429430
Sort: "desc",
430-
PerPage: 1,
431431
},
432432
Ref: gitlab.Ptr(pull.HeadBranch),
433433
}
@@ -437,15 +437,34 @@ func (g *GitlabClient) UpdateStatus(logger logging.SimpleLogging, repo models.Re
437437
commitStatuses, resp, err = g.Client.Commits.GetCommitStatuses(repo.FullName, pull.HeadCommit, getCommitStatusesOptions)
438438

439439
if resp != nil {
440-
logger.Debug("GET /projects/%s/repository/commits/%d: %d", pull.BaseRepo.ID(), pull.HeadCommit, resp.StatusCode)
440+
logger.Debug("GET /projects/%s/repository/commits/%d/statuses: %d", pull.BaseRepo.ID(), pull.HeadCommit, resp.StatusCode)
441441
}
442442
if err != nil {
443443
return err
444444
}
445445
if len(commitStatuses) > 0 {
446-
logger.Info("Pipeline found for commit %s and ref %s, setting pipeline ID to %d", pull.HeadCommit, pull.HeadBranch, commitStatuses[0].PipelineId)
447-
// Set the pipeline ID to the last pipeline that ran for the commit
448-
setCommitStatusOptions.PipelineID = gitlab.Ptr(commitStatuses[0].PipelineId)
446+
var pipelineIds []int
447+
448+
// Loop through the commitStatuses and collect unique pipelineId
449+
for _, commitStatus := range commitStatuses {
450+
if !(slices.Contains(pipelineIds, commitStatus.PipelineId)) {
451+
pipelineIds = append(pipelineIds, commitStatus.PipelineId)
452+
}
453+
}
454+
455+
// Check that all commit statuses has identical pipeline ID reflected by only one item in pipelineIds
456+
if len(pipelineIds) == 1 {
457+
logger.Info("Exactly one PipelineID found for commit %s and ref %s, setting new status PipelineID to %d", pull.HeadCommit, pull.HeadBranch, pipelineIds[0])
458+
459+
// Set the pipeline ID to the only item in pipelineIds
460+
setCommitStatusOptions.PipelineID = gitlab.Ptr(pipelineIds[0])
461+
} else {
462+
logger.Warn("Commit %s has statuses from more than one PipelineID (ids=%v) for ref %s. Set PipelineID from the last commit status: %s", pull.HeadCommit, pipelineIds, pull.HeadBranch, commitStatuses[0].PipelineId)
463+
464+
// Set the pipeline ID from the latest commit status
465+
setCommitStatusOptions.PipelineID = gitlab.Ptr(commitStatuses[0].PipelineId)
466+
}
467+
449468
break
450469
}
451470
if i != retries {

0 commit comments

Comments
 (0)