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.

commit_status.go 8.8KB

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