You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

status.go 9.5 kB

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