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.

292 lines
9.2 KiB

  1. // Copyright 2017 Gitea. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "container/list"
  7. "fmt"
  8. "strings"
  9. "code.gitea.io/git"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/util"
  13. api "code.gitea.io/sdk/gitea"
  14. "github.com/go-xorm/xorm"
  15. )
  16. // CommitStatusState holds the state of a Status
  17. // It can be "pending", "success", "error", "failure", and "warning"
  18. type CommitStatusState string
  19. // IsWorseThan returns true if this State is worse than the given State
  20. func (css CommitStatusState) IsWorseThan(css2 CommitStatusState) bool {
  21. switch css {
  22. case CommitStatusError:
  23. return true
  24. case CommitStatusFailure:
  25. return css2 != CommitStatusError
  26. case CommitStatusWarning:
  27. return css2 != CommitStatusError && css2 != CommitStatusFailure
  28. case CommitStatusSuccess:
  29. return css2 != CommitStatusError && css2 != CommitStatusFailure && css2 != CommitStatusWarning
  30. default:
  31. return css2 != CommitStatusError && css2 != CommitStatusFailure && css2 != CommitStatusWarning && css2 != CommitStatusSuccess
  32. }
  33. }
  34. const (
  35. // CommitStatusPending is for when the Status is Pending
  36. CommitStatusPending CommitStatusState = "pending"
  37. // CommitStatusSuccess is for when the Status is Success
  38. CommitStatusSuccess CommitStatusState = "success"
  39. // CommitStatusError is for when the Status is Error
  40. CommitStatusError CommitStatusState = "error"
  41. // CommitStatusFailure is for when the Status is Failure
  42. CommitStatusFailure CommitStatusState = "failure"
  43. // CommitStatusWarning is for when the Status is Warning
  44. CommitStatusWarning CommitStatusState = "warning"
  45. )
  46. // CommitStatus holds a single Status of a single Commit
  47. type CommitStatus struct {
  48. ID int64 `xorm:"pk autoincr"`
  49. Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  50. RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  51. Repo *Repository `xorm:"-"`
  52. State CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
  53. SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
  54. TargetURL string `xorm:"TEXT"`
  55. Description string `xorm:"TEXT"`
  56. Context string `xorm:"TEXT"`
  57. Creator *User `xorm:"-"`
  58. CreatorID int64
  59. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  60. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  61. }
  62. func (status *CommitStatus) loadRepo(e Engine) (err error) {
  63. if status.Repo == nil {
  64. status.Repo, err = getRepositoryByID(e, status.RepoID)
  65. if err != nil {
  66. return fmt.Errorf("getRepositoryByID [%d]: %v", status.RepoID, err)
  67. }
  68. }
  69. if status.Creator == nil && status.CreatorID > 0 {
  70. status.Creator, err = getUserByID(e, status.CreatorID)
  71. if err != nil {
  72. return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err)
  73. }
  74. }
  75. return nil
  76. }
  77. // APIURL returns the absolute APIURL to this commit-status.
  78. func (status *CommitStatus) APIURL() string {
  79. status.loadRepo(x)
  80. return fmt.Sprintf("%sapi/v1/%s/statuses/%s",
  81. setting.AppURL, status.Repo.FullName(), status.SHA)
  82. }
  83. // APIFormat assumes some fields assigned with values:
  84. // Required - Repo, Creator
  85. func (status *CommitStatus) APIFormat() *api.Status {
  86. status.loadRepo(x)
  87. apiStatus := &api.Status{
  88. Created: status.CreatedUnix.AsTime(),
  89. Updated: status.CreatedUnix.AsTime(),
  90. State: api.StatusState(status.State),
  91. TargetURL: status.TargetURL,
  92. Description: status.Description,
  93. ID: status.Index,
  94. URL: status.APIURL(),
  95. Context: status.Context,
  96. }
  97. if status.Creator != nil {
  98. apiStatus.Creator = status.Creator.APIFormat()
  99. }
  100. return apiStatus
  101. }
  102. // CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
  103. func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
  104. var lastStatus *CommitStatus
  105. var state CommitStatusState
  106. for _, status := range statuses {
  107. if status.State.IsWorseThan(state) {
  108. state = status.State
  109. lastStatus = status
  110. }
  111. }
  112. if lastStatus == nil {
  113. if len(statuses) > 0 {
  114. lastStatus = statuses[0]
  115. } else {
  116. lastStatus = &CommitStatus{}
  117. }
  118. }
  119. return lastStatus
  120. }
  121. // GetCommitStatuses returns all statuses for a given commit.
  122. func GetCommitStatuses(repo *Repository, sha string, page int) ([]*CommitStatus, error) {
  123. statuses := make([]*CommitStatus, 0, 10)
  124. return statuses, x.Limit(10, page*10).Where("repo_id = ?", repo.ID).And("sha = ?", sha).Find(&statuses)
  125. }
  126. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
  127. func GetLatestCommitStatus(repo *Repository, sha string, page int) ([]*CommitStatus, error) {
  128. ids := make([]int64, 0, 10)
  129. err := x.Limit(10, page*10).
  130. Table(&CommitStatus{}).
  131. Where("repo_id = ?", repo.ID).And("sha = ?", sha).
  132. Select("max( id ) as id").
  133. GroupBy("context").OrderBy("max( id ) desc").Find(&ids)
  134. if err != nil {
  135. return nil, err
  136. }
  137. statuses := make([]*CommitStatus, 0, len(ids))
  138. if len(ids) == 0 {
  139. return statuses, nil
  140. }
  141. return statuses, x.In("id", ids).Find(&statuses)
  142. }
  143. // GetCommitStatus populates a given status for a given commit.
  144. // NOTE: If ID or Index isn't given, and only Context, TargetURL and/or Description
  145. // is given, the CommitStatus created _last_ will be returned.
  146. func GetCommitStatus(repo *Repository, sha string, status *CommitStatus) (*CommitStatus, error) {
  147. conds := &CommitStatus{
  148. Context: status.Context,
  149. State: status.State,
  150. TargetURL: status.TargetURL,
  151. Description: status.Description,
  152. }
  153. has, err := x.Where("repo_id = ?", repo.ID).And("sha = ?", sha).Desc("created_unix").Get(conds)
  154. if err != nil {
  155. return nil, fmt.Errorf("GetCommitStatus[%s, %s]: %v", repo.RepoPath(), sha, err)
  156. }
  157. if !has {
  158. return nil, fmt.Errorf("GetCommitStatus[%s, %s]: not found", repo.RepoPath(), sha)
  159. }
  160. return conds, nil
  161. }
  162. // NewCommitStatusOptions holds options for creating a CommitStatus
  163. type NewCommitStatusOptions struct {
  164. Repo *Repository
  165. Creator *User
  166. SHA string
  167. CommitStatus *CommitStatus
  168. }
  169. func newCommitStatus(sess *xorm.Session, opts NewCommitStatusOptions) error {
  170. opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
  171. opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
  172. opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL)
  173. opts.CommitStatus.SHA = opts.SHA
  174. opts.CommitStatus.CreatorID = opts.Creator.ID
  175. if opts.Repo == nil {
  176. return fmt.Errorf("newCommitStatus[nil, %s]: no repository specified", opts.SHA)
  177. }
  178. opts.CommitStatus.RepoID = opts.Repo.ID
  179. if opts.Creator == nil {
  180. return fmt.Errorf("newCommitStatus[%s, %s]: no user specified", opts.Repo.RepoPath(), opts.SHA)
  181. }
  182. gitRepo, err := git.OpenRepository(opts.Repo.RepoPath())
  183. if err != nil {
  184. return fmt.Errorf("OpenRepository[%s]: %v", opts.Repo.RepoPath(), err)
  185. }
  186. if _, err := gitRepo.GetCommit(opts.SHA); err != nil {
  187. return fmt.Errorf("GetCommit[%s]: %v", opts.SHA, err)
  188. }
  189. // Get the next Status Index
  190. var nextIndex int64
  191. lastCommitStatus := &CommitStatus{
  192. SHA: opts.SHA,
  193. RepoID: opts.Repo.ID,
  194. }
  195. has, err := sess.Desc("index").Limit(1).Get(lastCommitStatus)
  196. if err != nil {
  197. sess.Rollback()
  198. return fmt.Errorf("newCommitStatus[%s, %s]: %v", opts.Repo.RepoPath(), opts.SHA, err)
  199. }
  200. if has {
  201. log.Debug("newCommitStatus[%s, %s]: found", opts.Repo.RepoPath(), opts.SHA)
  202. nextIndex = lastCommitStatus.Index
  203. }
  204. opts.CommitStatus.Index = nextIndex + 1
  205. log.Debug("newCommitStatus[%s, %s]: %d", opts.Repo.RepoPath(), opts.SHA, opts.CommitStatus.Index)
  206. // Insert new CommitStatus
  207. if _, err = sess.Insert(opts.CommitStatus); err != nil {
  208. sess.Rollback()
  209. return fmt.Errorf("newCommitStatus[%s, %s]: %v", opts.Repo.RepoPath(), opts.SHA, err)
  210. }
  211. return nil
  212. }
  213. // NewCommitStatus creates a new CommitStatus given a bunch of parameters
  214. // NOTE: All text-values will be trimmed from whitespaces.
  215. // Requires: Repo, Creator, SHA
  216. func NewCommitStatus(repo *Repository, creator *User, sha string, status *CommitStatus) error {
  217. sess := x.NewSession()
  218. defer sess.Close()
  219. if err := sess.Begin(); err != nil {
  220. return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", repo.ID, creator.ID, sha, err)
  221. }
  222. if err := newCommitStatus(sess, NewCommitStatusOptions{
  223. Repo: repo,
  224. Creator: creator,
  225. SHA: sha,
  226. CommitStatus: status,
  227. }); err != nil {
  228. return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", repo.ID, creator.ID, sha, err)
  229. }
  230. return sess.Commit()
  231. }
  232. // SignCommitWithStatuses represents a commit with validation of signature and status state.
  233. type SignCommitWithStatuses struct {
  234. Status *CommitStatus
  235. *SignCommit
  236. }
  237. // ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state
  238. func ParseCommitsWithStatus(oldCommits *list.List, repo *Repository) *list.List {
  239. var (
  240. newCommits = list.New()
  241. e = oldCommits.Front()
  242. )
  243. for e != nil {
  244. c := e.Value.(SignCommit)
  245. commit := SignCommitWithStatuses{
  246. SignCommit: &c,
  247. }
  248. statuses, err := GetLatestCommitStatus(repo, commit.ID.String(), 0)
  249. if err != nil {
  250. log.Error(3, "GetLatestCommitStatus: %v", err)
  251. } else {
  252. commit.Status = CalcCommitStatus(statuses)
  253. }
  254. newCommits.PushBack(commit)
  255. e = e.Next()
  256. }
  257. return newCommits
  258. }