本站源代码
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.

331 lines
10KB

  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. "crypto/sha1"
  8. "fmt"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. api "code.gitea.io/gitea/modules/structs"
  14. "code.gitea.io/gitea/modules/timeutil"
  15. "xorm.io/xorm"
  16. )
  17. // CommitStatusState holds the state of a Status
  18. // It can be "pending", "success", "error", "failure", and "warning"
  19. type CommitStatusState string
  20. // IsWorseThan returns true if this State is worse than the given State
  21. func (css CommitStatusState) IsWorseThan(css2 CommitStatusState) bool {
  22. switch css {
  23. case CommitStatusError:
  24. return true
  25. case CommitStatusFailure:
  26. return css2 != CommitStatusError
  27. case CommitStatusWarning:
  28. return css2 != CommitStatusError && css2 != CommitStatusFailure
  29. case CommitStatusSuccess:
  30. return css2 != CommitStatusError && css2 != CommitStatusFailure && css2 != CommitStatusWarning
  31. default:
  32. return css2 != CommitStatusError && css2 != CommitStatusFailure && css2 != CommitStatusWarning && css2 != CommitStatusSuccess
  33. }
  34. }
  35. const (
  36. // CommitStatusPending is for when the Status is Pending
  37. CommitStatusPending CommitStatusState = "pending"
  38. // CommitStatusSuccess is for when the Status is Success
  39. CommitStatusSuccess CommitStatusState = "success"
  40. // CommitStatusError is for when the Status is Error
  41. CommitStatusError CommitStatusState = "error"
  42. // CommitStatusFailure is for when the Status is Failure
  43. CommitStatusFailure CommitStatusState = "failure"
  44. // CommitStatusWarning is for when the Status is Warning
  45. CommitStatusWarning CommitStatusState = "warning"
  46. )
  47. // CommitStatus holds a single Status of a single Commit
  48. type CommitStatus struct {
  49. ID int64 `xorm:"pk autoincr"`
  50. Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  51. RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
  52. Repo *Repository `xorm:"-"`
  53. State CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
  54. SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
  55. TargetURL string `xorm:"TEXT"`
  56. Description string `xorm:"TEXT"`
  57. ContextHash string `xorm:"char(40) index"`
  58. Context string `xorm:"TEXT"`
  59. Creator *User `xorm:"-"`
  60. CreatorID int64
  61. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  62. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  63. }
  64. func (status *CommitStatus) loadRepo(e Engine) (err error) {
  65. if status.Repo == nil {
  66. status.Repo, err = getRepositoryByID(e, status.RepoID)
  67. if err != nil {
  68. return fmt.Errorf("getRepositoryByID [%d]: %v", status.RepoID, err)
  69. }
  70. }
  71. if status.Creator == nil && status.CreatorID > 0 {
  72. status.Creator, err = getUserByID(e, status.CreatorID)
  73. if err != nil {
  74. return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err)
  75. }
  76. }
  77. return nil
  78. }
  79. // APIURL returns the absolute APIURL to this commit-status.
  80. func (status *CommitStatus) APIURL() string {
  81. _ = status.loadRepo(x)
  82. return fmt.Sprintf("%sapi/v1/repos/%s/statuses/%s",
  83. setting.AppURL, status.Repo.FullName(), status.SHA)
  84. }
  85. // APIFormat assumes some fields assigned with values:
  86. // Required - Repo, Creator
  87. func (status *CommitStatus) APIFormat() *api.Status {
  88. _ = status.loadRepo(x)
  89. apiStatus := &api.Status{
  90. Created: status.CreatedUnix.AsTime(),
  91. Updated: status.CreatedUnix.AsTime(),
  92. State: api.StatusState(status.State),
  93. TargetURL: status.TargetURL,
  94. Description: status.Description,
  95. ID: status.Index,
  96. URL: status.APIURL(),
  97. Context: status.Context,
  98. }
  99. if status.Creator != nil {
  100. apiStatus.Creator = status.Creator.APIFormat()
  101. }
  102. return apiStatus
  103. }
  104. // CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
  105. func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
  106. var lastStatus *CommitStatus
  107. var state CommitStatusState
  108. for _, status := range statuses {
  109. if status.State.IsWorseThan(state) {
  110. state = status.State
  111. lastStatus = status
  112. }
  113. }
  114. if lastStatus == nil {
  115. if len(statuses) > 0 {
  116. lastStatus = statuses[0]
  117. } else {
  118. lastStatus = &CommitStatus{}
  119. }
  120. }
  121. return lastStatus
  122. }
  123. // CommitStatusOptions holds the options for query commit statuses
  124. type CommitStatusOptions struct {
  125. Page int
  126. State string
  127. SortType string
  128. }
  129. // GetCommitStatuses returns all statuses for a given commit.
  130. func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions) ([]*CommitStatus, int64, error) {
  131. if opts.Page <= 0 {
  132. opts.Page = 1
  133. }
  134. countSession := listCommitStatusesStatement(repo, sha, opts)
  135. maxResults, err := countSession.Count(new(CommitStatus))
  136. if err != nil {
  137. log.Error("Count PRs: %v", err)
  138. return nil, maxResults, err
  139. }
  140. statuses := make([]*CommitStatus, 0, ItemsPerPage)
  141. findSession := listCommitStatusesStatement(repo, sha, opts)
  142. sortCommitStatusesSession(findSession, opts.SortType)
  143. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  144. return statuses, maxResults, findSession.Find(&statuses)
  145. }
  146. func listCommitStatusesStatement(repo *Repository, sha string, opts *CommitStatusOptions) *xorm.Session {
  147. sess := x.Where("repo_id = ?", repo.ID).And("sha = ?", sha)
  148. switch opts.State {
  149. case "pending", "success", "error", "failure", "warning":
  150. sess.And("state = ?", opts.State)
  151. }
  152. return sess
  153. }
  154. func sortCommitStatusesSession(sess *xorm.Session, sortType string) {
  155. switch sortType {
  156. case "oldest":
  157. sess.Asc("created_unix")
  158. case "recentupdate":
  159. sess.Desc("updated_unix")
  160. case "leastupdate":
  161. sess.Asc("updated_unix")
  162. case "leastindex":
  163. sess.Desc("index")
  164. case "highestindex":
  165. sess.Asc("index")
  166. default:
  167. sess.Desc("created_unix")
  168. }
  169. }
  170. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
  171. func GetLatestCommitStatus(repo *Repository, sha string, page int) ([]*CommitStatus, error) {
  172. ids := make([]int64, 0, 10)
  173. err := x.Limit(10, page*10).
  174. Table(&CommitStatus{}).
  175. Where("repo_id = ?", repo.ID).And("sha = ?", sha).
  176. Select("max( id ) as id").
  177. GroupBy("context_hash").OrderBy("max( id ) desc").Find(&ids)
  178. if err != nil {
  179. return nil, err
  180. }
  181. statuses := make([]*CommitStatus, 0, len(ids))
  182. if len(ids) == 0 {
  183. return statuses, nil
  184. }
  185. return statuses, x.In("id", ids).Find(&statuses)
  186. }
  187. // FindRepoRecentCommitStatusContexts returns repository's recent commit status contexts
  188. func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]string, error) {
  189. start := timeutil.TimeStampNow().AddDuration(-before)
  190. ids := make([]int64, 0, 10)
  191. if err := x.Table("commit_status").
  192. Where("repo_id = ?", repoID).
  193. And("updated_unix >= ?", start).
  194. Select("max( id ) as id").
  195. GroupBy("context_hash").OrderBy("max( id ) desc").
  196. Find(&ids); err != nil {
  197. return nil, err
  198. }
  199. var contexts = make([]string, 0, len(ids))
  200. if len(ids) == 0 {
  201. return contexts, nil
  202. }
  203. return contexts, x.Select("context").Table("commit_status").In("id", ids).Find(&contexts)
  204. }
  205. // NewCommitStatusOptions holds options for creating a CommitStatus
  206. type NewCommitStatusOptions struct {
  207. Repo *Repository
  208. Creator *User
  209. SHA string
  210. CommitStatus *CommitStatus
  211. }
  212. // NewCommitStatus save commit statuses into database
  213. func NewCommitStatus(opts NewCommitStatusOptions) error {
  214. if opts.Repo == nil {
  215. return fmt.Errorf("NewCommitStatus[nil, %s]: no repository specified", opts.SHA)
  216. }
  217. repoPath := opts.Repo.RepoPath()
  218. if opts.Creator == nil {
  219. return fmt.Errorf("NewCommitStatus[%s, %s]: no user specified", repoPath, opts.SHA)
  220. }
  221. sess := x.NewSession()
  222. defer sess.Close()
  223. if err := sess.Begin(); err != nil {
  224. return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", opts.Repo.ID, opts.Creator.ID, opts.SHA, err)
  225. }
  226. opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
  227. opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
  228. opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL)
  229. opts.CommitStatus.SHA = opts.SHA
  230. opts.CommitStatus.CreatorID = opts.Creator.ID
  231. opts.CommitStatus.RepoID = opts.Repo.ID
  232. // Get the next Status Index
  233. var nextIndex int64
  234. lastCommitStatus := &CommitStatus{
  235. SHA: opts.SHA,
  236. RepoID: opts.Repo.ID,
  237. }
  238. has, err := sess.Desc("index").Limit(1).Get(lastCommitStatus)
  239. if err != nil {
  240. if err := sess.Rollback(); err != nil {
  241. log.Error("NewCommitStatus: sess.Rollback: %v", err)
  242. }
  243. return fmt.Errorf("NewCommitStatus[%s, %s]: %v", repoPath, opts.SHA, err)
  244. }
  245. if has {
  246. log.Debug("NewCommitStatus[%s, %s]: found", repoPath, opts.SHA)
  247. nextIndex = lastCommitStatus.Index
  248. }
  249. opts.CommitStatus.Index = nextIndex + 1
  250. log.Debug("NewCommitStatus[%s, %s]: %d", repoPath, opts.SHA, opts.CommitStatus.Index)
  251. opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context)
  252. // Insert new CommitStatus
  253. if _, err = sess.Insert(opts.CommitStatus); err != nil {
  254. if err := sess.Rollback(); err != nil {
  255. log.Error("Insert CommitStatus: sess.Rollback: %v", err)
  256. }
  257. return fmt.Errorf("Insert CommitStatus[%s, %s]: %v", repoPath, opts.SHA, err)
  258. }
  259. return sess.Commit()
  260. }
  261. // SignCommitWithStatuses represents a commit with validation of signature and status state.
  262. type SignCommitWithStatuses struct {
  263. Status *CommitStatus
  264. *SignCommit
  265. }
  266. // ParseCommitsWithStatus checks commits latest statuses and calculates its worst status state
  267. func ParseCommitsWithStatus(oldCommits *list.List, repo *Repository) *list.List {
  268. var (
  269. newCommits = list.New()
  270. e = oldCommits.Front()
  271. )
  272. for e != nil {
  273. c := e.Value.(SignCommit)
  274. commit := SignCommitWithStatuses{
  275. SignCommit: &c,
  276. }
  277. statuses, err := GetLatestCommitStatus(repo, commit.ID.String(), 0)
  278. if err != nil {
  279. log.Error("GetLatestCommitStatus: %v", err)
  280. } else {
  281. commit.Status = CalcCommitStatus(statuses)
  282. }
  283. newCommits.PushBack(commit)
  284. e = e.Next()
  285. }
  286. return newCommits
  287. }
  288. // hashCommitStatusContext hash context
  289. func hashCommitStatusContext(context string) string {
  290. return fmt.Sprintf("%x", sha1.Sum([]byte(context)))
  291. }
上海开阖软件有限公司 沪ICP备12045867号-1