|
| 1 | +// Copyright 2019 The Gitea Authors. |
| 2 | +// All rights reserved. |
| 3 | +// Use of this source code is governed by a MIT-style |
| 4 | +// license that can be found in the LICENSE file. |
| 5 | + |
| 6 | +package pull |
| 7 | + |
| 8 | +import ( |
| 9 | + "code.gitea.io/gitea/models" |
| 10 | + "code.gitea.io/gitea/modules/git" |
| 11 | + |
| 12 | + "github.com/pkg/errors" |
| 13 | +) |
| 14 | + |
| 15 | +// IsCommitStatusContextSuccess returns true if all required status check contexts succeed. |
| 16 | +func IsCommitStatusContextSuccess(commitStatuses []*models.CommitStatus, requiredContexts []string) bool { |
| 17 | + for _, ctx := range requiredContexts { |
| 18 | + var found bool |
| 19 | + for _, commitStatus := range commitStatuses { |
| 20 | + if commitStatus.Context == ctx { |
| 21 | + if commitStatus.State != models.CommitStatusSuccess { |
| 22 | + return false |
| 23 | + } |
| 24 | + |
| 25 | + found = true |
| 26 | + break |
| 27 | + } |
| 28 | + } |
| 29 | + if !found { |
| 30 | + return false |
| 31 | + } |
| 32 | + } |
| 33 | + return true |
| 34 | +} |
| 35 | + |
| 36 | +// IsPullCommitStatusPass returns if all required status checks PASS |
| 37 | +func IsPullCommitStatusPass(pr *models.PullRequest) (bool, error) { |
| 38 | + if err := pr.LoadProtectedBranch(); err != nil { |
| 39 | + return false, errors.Wrap(err, "GetLatestCommitStatus") |
| 40 | + } |
| 41 | + if pr.ProtectedBranch == nil || !pr.ProtectedBranch.EnableStatusCheck { |
| 42 | + return true, nil |
| 43 | + } |
| 44 | + |
| 45 | + // check if all required status checks are successful |
| 46 | + headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath()) |
| 47 | + if err != nil { |
| 48 | + return false, errors.Wrap(err, "OpenRepository") |
| 49 | + } |
| 50 | + |
| 51 | + if !headGitRepo.IsBranchExist(pr.HeadBranch) { |
| 52 | + return false, errors.New("Head branch does not exist, can not merge") |
| 53 | + } |
| 54 | + |
| 55 | + sha, err := headGitRepo.GetBranchCommitID(pr.HeadBranch) |
| 56 | + if err != nil { |
| 57 | + return false, errors.Wrap(err, "GetBranchCommitID") |
| 58 | + } |
| 59 | + |
| 60 | + if err := pr.LoadBaseRepo(); err != nil { |
| 61 | + return false, errors.Wrap(err, "LoadBaseRepo") |
| 62 | + } |
| 63 | + |
| 64 | + commitStatuses, err := models.GetLatestCommitStatus(pr.BaseRepo, sha, 0) |
| 65 | + if err != nil { |
| 66 | + return false, errors.Wrap(err, "GetLatestCommitStatus") |
| 67 | + } |
| 68 | + |
| 69 | + return IsCommitStatusContextSuccess(commitStatuses, pr.ProtectedBranch.StatusCheckContexts), nil |
| 70 | +} |
0 commit comments