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.

status.go 9.4KB

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