You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.2 KiB

  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. package pull
  6. import (
  7. "code.gitea.io/gitea/models"
  8. "code.gitea.io/gitea/modules/git"
  9. "github.com/pkg/errors"
  10. )
  11. // IsCommitStatusContextSuccess returns true if all required status check contexts succeed.
  12. func IsCommitStatusContextSuccess(commitStatuses []*models.CommitStatus, requiredContexts []string) bool {
  13. // If no specific context is required, require that last commit status is a success
  14. if len(requiredContexts) == 0 {
  15. status := models.CalcCommitStatus(commitStatuses)
  16. if status == nil || status.State != models.CommitStatusSuccess {
  17. return false
  18. }
  19. return true
  20. }
  21. for _, ctx := range requiredContexts {
  22. var found bool
  23. for _, commitStatus := range commitStatuses {
  24. if commitStatus.Context == ctx {
  25. if commitStatus.State != models.CommitStatusSuccess {
  26. return false
  27. }
  28. found = true
  29. break
  30. }
  31. }
  32. if !found {
  33. return false
  34. }
  35. }
  36. return true
  37. }
  38. // IsPullCommitStatusPass returns if all required status checks PASS
  39. func IsPullCommitStatusPass(pr *models.PullRequest) (bool, error) {
  40. if err := pr.LoadProtectedBranch(); err != nil {
  41. return false, errors.Wrap(err, "GetLatestCommitStatus")
  42. }
  43. if pr.ProtectedBranch == nil || !pr.ProtectedBranch.EnableStatusCheck {
  44. return true, nil
  45. }
  46. // check if all required status checks are successful
  47. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  48. if err != nil {
  49. return false, errors.Wrap(err, "OpenRepository")
  50. }
  51. if !headGitRepo.IsBranchExist(pr.HeadBranch) {
  52. return false, errors.New("Head branch does not exist, can not merge")
  53. }
  54. sha, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  55. if err != nil {
  56. return false, errors.Wrap(err, "GetBranchCommitID")
  57. }
  58. if err := pr.LoadBaseRepo(); err != nil {
  59. return false, errors.Wrap(err, "LoadBaseRepo")
  60. }
  61. commitStatuses, err := models.GetLatestCommitStatus(pr.BaseRepo, sha, 0)
  62. if err != nil {
  63. return false, errors.Wrap(err, "GetLatestCommitStatus")
  64. }
  65. return IsCommitStatusContextSuccess(commitStatuses, pr.ProtectedBranch.StatusCheckContexts), nil
  66. }