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.

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