Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

commit_status.go 8.3KB

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