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.

301 lines
9.5 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. "time"
  10. "code.gitea.io/git"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  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. Created time.Time `xorm:"-"`
  60. CreatedUnix int64 `xorm:"INDEX created"`
  61. Updated time.Time `xorm:"-"`
  62. UpdatedUnix int64 `xorm:"INDEX updated"`
  63. }
  64. // AfterLoad is invoked from XORM after setting the value of a field of
  65. // this object.
  66. func (status *CommitStatus) AfterLoad() {
  67. status.Created = time.Unix(status.CreatedUnix, 0).Local()
  68. status.Updated = time.Unix(status.UpdatedUnix, 0).Local()
  69. }
  70. func (status *CommitStatus) loadRepo(e Engine) (err error) {
  71. if status.Repo == nil {
  72. status.Repo, err = getRepositoryByID(e, status.RepoID)
  73. if err != nil {
  74. return fmt.Errorf("getRepositoryByID [%d]: %v", status.RepoID, err)
  75. }
  76. }
  77. if status.Creator == nil && status.CreatorID > 0 {
  78. status.Creator, err = getUserByID(e, status.CreatorID)
  79. if err != nil {
  80. return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err)
  81. }
  82. }
  83. return nil
  84. }
  85. // APIURL returns the absolute APIURL to this commit-status.
  86. func (status *CommitStatus) APIURL() string {
  87. status.loadRepo(x)
  88. return fmt.Sprintf("%sapi/v1/%s/statuses/%s",
  89. setting.AppURL, status.Repo.FullName(), status.SHA)
  90. }
  91. // APIFormat assumes some fields assigned with values:
  92. // Required - Repo, Creator
  93. func (status *CommitStatus) APIFormat() *api.Status {
  94. status.loadRepo(x)
  95. apiStatus := &api.Status{
  96. Created: status.Created,
  97. Updated: status.Created,
  98. State: api.StatusState(status.State),
  99. TargetURL: status.TargetURL,
  100. Description: status.Description,
  101. ID: status.Index,
  102. URL: status.APIURL(),
  103. Context: status.Context,
  104. }
  105. if status.Creator != nil {
  106. apiStatus.Creator = status.Creator.APIFormat()
  107. }
  108. return apiStatus
  109. }
  110. // CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
  111. func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
  112. var lastStatus *CommitStatus
  113. var state CommitStatusState
  114. for _, status := range statuses {
  115. if status.State.IsWorseThan(state) {
  116. state = status.State
  117. lastStatus = status
  118. }
  119. }
  120. if lastStatus == nil {
  121. if len(statuses) > 0 {
  122. lastStatus = statuses[0]
  123. } else {
  124. lastStatus = &CommitStatus{}
  125. }
  126. }
  127. return lastStatus
  128. }
  129. // GetCommitStatuses returns all statuses for a given commit.
  130. func GetCommitStatuses(repo *Repository, sha string, page int) ([]*CommitStatus, error) {
  131. statuses := make([]*CommitStatus, 0, 10)
  132. return statuses, x.Limit(10, page*10).Where("repo_id = ?", repo.ID).And("sha = ?", sha).Find(&statuses)
  133. }
  134. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
  135. func GetLatestCommitStatus(repo *Repository, sha string, page int) ([]*CommitStatus, error) {
  136. ids := make([]int64, 0, 10)
  137. err := x.Limit(10, page*10).
  138. Table(&CommitStatus{}).
  139. Where("repo_id = ?", repo.ID).And("sha = ?", sha).
  140. Select("max( id ) as id").
  141. GroupBy("context").OrderBy("max( id ) desc").Find(&ids)
  142. if err != nil {
  143. return nil, err
  144. }
  145. statuses := make([]*CommitStatus, 0, len(ids))
  146. if len(ids) == 0 {
  147. return statuses, nil
  148. }
  149. return statuses, x.In("id", ids).Find(&statuses)
  150. }
  151. // GetCommitStatus populates a given status for a given commit.
  152. // NOTE: If ID or Index isn't given, and only Context, TargetURL and/or Description
  153. // is given, the CommitStatus created _last_ will be returned.
  154. func GetCommitStatus(repo *Repository, sha string, status *CommitStatus) (*CommitStatus, error) {
  155. conds := &CommitStatus{
  156. Context: status.Context,
  157. State: status.State,
  158. TargetURL: status.TargetURL,
  159. Description: status.Description,
  160. }
  161. has, err := x.Where("repo_id = ?", repo.ID).And("sha = ?", sha).Desc("created_unix").Get(conds)
  162. if err != nil {
  163. return nil, fmt.Errorf("GetCommitStatus[%s, %s]: %v", repo.RepoPath(), sha, err)
  164. }
  165. if !has {
  166. return nil, fmt.Errorf("GetCommitStatus[%s, %s]: not found", repo.RepoPath(), sha)
  167. }
  168. return conds, nil
  169. }
  170. // NewCommitStatusOptions holds options for creating a CommitStatus
  171. type NewCommitStatusOptions struct {
  172. Repo *Repository
  173. Creator *User
  174. SHA string
  175. CommitStatus *CommitStatus
  176. }
  177. func newCommitStatus(sess *xorm.Session, opts NewCommitStatusOptions) error {
  178. opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
  179. opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
  180. opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL)
  181. opts.CommitStatus.SHA = opts.SHA
  182. opts.CommitStatus.CreatorID = opts.Creator.ID
  183. if opts.Repo == nil {
  184. return fmt.Errorf("newCommitStatus[nil, %s]: no repository specified", opts.SHA)
  185. }
  186. opts.CommitStatus.RepoID = opts.Repo.ID
  187. if opts.Creator == nil {
  188. return fmt.Errorf("newCommitStatus[%s, %s]: no user specified", opts.Repo.RepoPath(), opts.SHA)
  189. }
  190. gitRepo, err := git.OpenRepository(opts.Repo.RepoPath())
  191. if err != nil {
  192. return fmt.Errorf("OpenRepository[%s]: %v", opts.Repo.RepoPath(), err)
  193. }
  194. if _, err := gitRepo.GetCommit(opts.SHA); err != nil {
  195. return fmt.Errorf("GetCommit[%s]: %v", opts.SHA, err)
  196. }
  197. // Get the next Status Index
  198. var nextIndex int64
  199. lastCommitStatus := &CommitStatus{
  200. SHA: opts.SHA,
  201. RepoID: opts.Repo.ID,
  202. }
  203. has, err := sess.Desc("index").Limit(1).Get(lastCommitStatus)
  204. if err != nil {
  205. sess.Rollback()
  206. return fmt.Errorf("newCommitStatus[%s, %s]: %v", opts.Repo.RepoPath(), opts.SHA, err)
  207. }
  208. if has {
  209. log.Debug("newCommitStatus[%s, %s]: found", opts.Repo.RepoPath(), opts.SHA)
  210. nextIndex = lastCommitStatus.Index
  211. }
  212. opts.CommitStatus.Index = nextIndex + 1
  213. log.Debug("newCommitStatus[%s, %s]: %d", opts.Repo.RepoPath(), opts.SHA, opts.CommitStatus.Index)
  214. // Insert new CommitStatus
  215. if _, err = sess.Insert(opts.CommitStatus); err != nil {
  216. sess.Rollback()
  217. return fmt.Errorf("newCommitStatus[%s, %s]: %v", opts.Repo.RepoPath(), opts.SHA, err)
  218. }
  219. return nil
  220. }
  221. // NewCommitStatus creates a new CommitStatus given a bunch of parameters
  222. // NOTE: All text-values will be trimmed from whitespaces.
  223. // Requires: Repo, Creator, SHA
  224. func NewCommitStatus(repo *Repository, creator *User, sha string, status *CommitStatus) error {
  225. sess := x.NewSession()
  226. defer sess.Close()
  227. if err := sess.Begin(); err != nil {
  228. return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", repo.ID, creator.ID, sha, err)
  229. }
  230. if err := newCommitStatus(sess, NewCommitStatusOptions{
  231. Repo: repo,
  232. Creator: creator,
  233. SHA: sha,
  234. CommitStatus: status,
  235. }); err != nil {
  236. return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", repo.ID, creator.ID, sha, err)
  237. }
  238. return sess.Commit()
  239. }
  240. // SignCommitWithStatuses represents a commit with validation of signature and status state.
  241. type SignCommitWithStatuses struct {
  242. Status *CommitStatus
  243. *SignCommit
  244. }
  245. // ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state
  246. func ParseCommitsWithStatus(oldCommits *list.List, repo *Repository) *list.List {
  247. var (
  248. newCommits = list.New()
  249. e = oldCommits.Front()
  250. )
  251. for e != nil {
  252. c := e.Value.(SignCommit)
  253. commit := SignCommitWithStatuses{
  254. SignCommit: &c,
  255. }
  256. statuses, err := GetLatestCommitStatus(repo, commit.ID.String(), 0)
  257. if err != nil {
  258. log.Error(3, "GetLatestCommitStatus: %v", err)
  259. } else {
  260. commit.Status = CalcCommitStatus(statuses)
  261. }
  262. newCommits.PushBack(commit)
  263. e = e.Next()
  264. }
  265. return newCommits
  266. }