summaryrefslogtreecommitdiffstats
path: root/services/pull/commit_status.go
blob: bdadc329d64073253eef40b2b508935dcd33d1f3 (plain)
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
// Copyright 2019 The Gitea Authors.
// All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package pull

import (
	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/git"

	"github.com/pkg/errors"
)

// IsCommitStatusContextSuccess returns true if all required status check contexts succeed.
func IsCommitStatusContextSuccess(commitStatuses []*models.CommitStatus, requiredContexts []string) bool {
	for _, ctx := range requiredContexts {
		var found bool
		for _, commitStatus := range commitStatuses {
			if commitStatus.Context == ctx {
				if commitStatus.State != models.CommitStatusSuccess {
					return false
				}

				found = true
				break
			}
		}
		if !found {
			return false
		}
	}
	return true
}

// IsPullCommitStatusPass returns if all required status checks PASS
func IsPullCommitStatusPass(pr *models.PullRequest) (bool, error) {
	if err := pr.LoadProtectedBranch(); err != nil {
		return false, errors.Wrap(err, "GetLatestCommitStatus")
	}
	if pr.ProtectedBranch == nil || !pr.ProtectedBranch.EnableStatusCheck {
		return true, nil
	}

	// check if all required status checks are successful
	headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
	if err != nil {
		return false, errors.Wrap(err, "OpenRepository")
	}

	if !headGitRepo.IsBranchExist(pr.HeadBranch) {
		return false, errors.New("Head branch does not exist, can not merge")
	}

	sha, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
	if err != nil {
		return false, errors.Wrap(err, "GetBranchCommitID")
	}

	if err := pr.LoadBaseRepo(); err != nil {
		return false, errors.Wrap(err, "LoadBaseRepo")
	}

	commitStatuses, err := models.GetLatestCommitStatus(pr.BaseRepo, sha, 0)
	if err != nil {
		return false, errors.Wrap(err, "GetLatestCommitStatus")
	}

	return IsCommitStatusContextSuccess(commitStatuses, pr.ProtectedBranch.StatusCheckContexts), nil
}