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.

79 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. defer headGitRepo.Close()
  52. if !headGitRepo.IsBranchExist(pr.HeadBranch) {
  53. return false, errors.New("Head branch does not exist, can not merge")
  54. }
  55. sha, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  56. if err != nil {
  57. return false, errors.Wrap(err, "GetBranchCommitID")
  58. }
  59. if err := pr.LoadBaseRepo(); err != nil {
  60. return false, errors.Wrap(err, "LoadBaseRepo")
  61. }
  62. commitStatuses, err := models.GetLatestCommitStatus(pr.BaseRepo, sha, 0)
  63. if err != nil {
  64. return false, errors.Wrap(err, "GetLatestCommitStatus")
  65. }
  66. return IsCommitStatusContextSuccess(commitStatuses, pr.ProtectedBranch.StatusCheckContexts), nil
  67. }