Skip to content

Commit 5f81701

Browse files
committed
Status-API
1 parent 54f0293 commit 5f81701

File tree

11 files changed

+627
-4
lines changed

11 files changed

+627
-4
lines changed

models/fixtures/commit_status.yml

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
-
2+
id: 1
3+
index: 1
4+
repo_id: 1
5+
state: pending
6+
sha: 1234123412341234123412341234123412341234
7+
target_url: https://example.com/builds/
8+
description: My awesome CI-service
9+
context: ci/awesomeness
10+
creator_id: 2
11+
12+
-
13+
id: 2
14+
index: 2
15+
repo_id: 1
16+
state: warning
17+
sha: 1234123412341234123412341234123412341234
18+
target_url: https://example.com/converage/
19+
description: My awesome Coverage service
20+
context: cov/awesomeness
21+
creator_id: 2
22+
23+
-
24+
id: 3
25+
index: 3
26+
repo_id: 1
27+
state: success
28+
sha: 1234123412341234123412341234123412341234
29+
target_url: https://example.com/converage/
30+
description: My awesome Coverage service
31+
context: cov/awesomeness
32+
creator_id: 2
33+
34+
-
35+
id: 4
36+
index: 4
37+
repo_id: 1
38+
state: failed
39+
sha: 1234123412341234123412341234123412341234
40+
target_url: https://example.com/builds/
41+
description: My awesome CI-service
42+
context: ci/awesomeness
43+
creator_id: 2
44+
45+
-
46+
id: 5
47+
index: 5
48+
repo_id: 1
49+
state: error
50+
sha: 1234123412341234123412341234123412341234
51+
target_url: https://example.com/builds/
52+
description: My awesome deploy service
53+
context: deploy/awesomeness
54+
creator_id: 2

models/migrations/migrations.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ var migrations = []Migration{
104104
NewMigration("generate and migrate repo and wiki Git hooks", generateAndMigrateGitHookChains),
105105
// v27 -> v28
106106
NewMigration("change mirror interval from hours to time.Duration", convertIntervalToDuration),
107+
// v28 -> v29
108+
NewMigration("add commit status table", addCommitStatus),
107109
}
108110

109111
// Migrate database to current version

models/migrations/v28.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package migrations
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/go-xorm/xorm"
7+
)
8+
9+
// CommitStatus see models/status.go
10+
type CommitStatus struct {
11+
ID int64 `xorm:"pk autoincr"`
12+
Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
13+
RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
14+
State string `xorm:"TEXT NOT NULL"`
15+
SHA string `xorm:"VARCHAR(40) NOT NULL INDEX UNIQUE(repo_sha_index)"`
16+
TargetURL string `xorm:"TEXT"`
17+
Description string `xorm:"TEXT"`
18+
Context string `xorm:"TEXT"`
19+
CreatorID int64 `xorm:"INDEX"`
20+
21+
CreatedUnix int64 `xorm:"INDEX"`
22+
UpdatedUnix int64 `xorm:"INDEX"`
23+
}
24+
25+
func addCommitStatus(x *xorm.Engine) error {
26+
if err := x.Sync2(new(CommitStatus)); err != nil {
27+
return fmt.Errorf("Sync2: %v", err)
28+
}
29+
return nil
30+
}

models/models.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ func init() {
118118
new(ProtectedBranch),
119119
new(UserOpenID),
120120
new(IssueWatch),
121+
new(CommitStatus),
121122
)
122123

123124
gonicNames := []string{"SSL", "UID"}

models/status.go

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
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+
5+
package models
6+
7+
import (
8+
"fmt"
9+
"strings"
10+
"time"
11+
12+
"code.gitea.io/git"
13+
"code.gitea.io/gitea/modules/log"
14+
"code.gitea.io/gitea/modules/setting"
15+
api "code.gitea.io/sdk/gitea"
16+
17+
"github.com/go-xorm/xorm"
18+
)
19+
20+
// CommitStatusState holds the state of a Status
21+
// It can be "pending", "success", "error", "failure", and "warning"
22+
type CommitStatusState string
23+
24+
// IsWorseThan returns true if this State is worse than the given State
25+
func (css CommitStatusState) IsWorseThan(css2 CommitStatusState) bool {
26+
switch css {
27+
case CommitStatusError:
28+
return true
29+
case CommitStatusFailure:
30+
return css2 != CommitStatusError
31+
case CommitStatusWarning:
32+
return css2 != CommitStatusError && css2 != CommitStatusFailure
33+
case CommitStatusSuccess:
34+
return css2 != CommitStatusError && css2 != CommitStatusFailure && css2 != CommitStatusWarning
35+
default:
36+
return css2 != CommitStatusError && css2 != CommitStatusFailure && css2 != CommitStatusWarning && css2 != CommitStatusSuccess
37+
}
38+
}
39+
40+
const (
41+
// CommitStatusPending is for when the Status is Pending
42+
CommitStatusPending CommitStatusState = "pending"
43+
// CommitStatusSuccess is for when the Status is Success
44+
CommitStatusSuccess CommitStatusState = "success"
45+
// CommitStatusError is for when the Status is Error
46+
CommitStatusError CommitStatusState = "error"
47+
// CommitStatusFailure is for when the Status is Failure
48+
CommitStatusFailure CommitStatusState = "failure"
49+
// CommitStatusWarning is for when the Status is Warning
50+
CommitStatusWarning CommitStatusState = "warning"
51+
)
52+
53+
// CommitStatus holds a single Status of a single Commit
54+
type CommitStatus struct {
55+
ID int64 `xorm:"pk autoincr"`
56+
Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
57+
RepoID int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
58+
Repo *Repository `xorm:"-"`
59+
State CommitStatusState `xorm:"TEXT NOT NULL"`
60+
SHA string `xorm:"VARCHAR(40) NOT NULL INDEX UNIQUE(repo_sha_index)"`
61+
TargetURL string `xorm:"TEXT"`
62+
Description string `xorm:"TEXT"`
63+
Context string `xorm:"TEXT"`
64+
Creator *User `xorm:"-"`
65+
CreatorID int64
66+
67+
Created time.Time `xorm:"-"`
68+
CreatedUnix int64 `xorm:"INDEX"`
69+
Updated time.Time `xorm:"-"`
70+
UpdatedUnix int64 `xorm:"INDEX"`
71+
}
72+
73+
// BeforeInsert is invoked from XORM before inserting an object of this type.
74+
func (status *CommitStatus) BeforeInsert() {
75+
status.CreatedUnix = time.Now().Unix()
76+
status.UpdatedUnix = status.CreatedUnix
77+
}
78+
79+
// BeforeUpdate is invoked from XORM before updating this object.
80+
func (status *CommitStatus) BeforeUpdate() {
81+
status.UpdatedUnix = time.Now().Unix()
82+
}
83+
84+
// AfterSet is invoked from XORM after setting the value of a field of
85+
// this object.
86+
func (status *CommitStatus) AfterSet(colName string, _ xorm.Cell) {
87+
switch colName {
88+
case "created_unix":
89+
status.Created = time.Unix(status.CreatedUnix, 0).Local()
90+
case "updated_unix":
91+
status.Updated = time.Unix(status.UpdatedUnix, 0).Local()
92+
}
93+
}
94+
95+
func (status *CommitStatus) loadRepo(e Engine) (err error) {
96+
if status.Repo == nil {
97+
status.Repo, err = getRepositoryByID(e, status.RepoID)
98+
if err != nil {
99+
return fmt.Errorf("getRepositoryByID [%d]: %v", status.RepoID, err)
100+
}
101+
}
102+
if status.Creator == nil && status.CreatorID > 0 {
103+
status.Creator, err = getUserByID(e, status.CreatorID)
104+
if err != nil {
105+
return fmt.Errorf("getUserByID [%d]: %v", status.CreatorID, err)
106+
}
107+
}
108+
return nil
109+
}
110+
111+
// APIURL returns the absolute APIURL to this commit-status.
112+
func (status *CommitStatus) APIURL() string {
113+
status.loadRepo(x)
114+
return fmt.Sprintf("%sapi/v1/%s/statuses/%s",
115+
setting.AppURL, status.Repo.FullName(), status.SHA)
116+
}
117+
118+
// APIFormat assumes some fields assigned with values:
119+
// Required - Repo, Creator
120+
func (status *CommitStatus) APIFormat() *api.Status {
121+
status.loadRepo(x)
122+
apiStatus := &api.Status{
123+
Created: status.Created,
124+
Updated: status.Created,
125+
State: api.StatusState(status.State),
126+
TargetURL: status.TargetURL,
127+
Description: status.Description,
128+
ID: status.Index,
129+
URL: status.APIURL(),
130+
Context: status.Context,
131+
}
132+
if status.Creator != nil {
133+
apiStatus.Creator = status.Creator.APIFormat()
134+
}
135+
136+
return apiStatus
137+
}
138+
139+
// GetCommitStatuses returns all statuses for a given commit.
140+
func GetCommitStatuses(repo *Repository, sha string, page int) ([]*CommitStatus, error) {
141+
statuses := make([]*CommitStatus, 0, 10)
142+
sess := x.NewSession()
143+
defer sess.Close()
144+
return statuses, sess.Limit(10, page*10).Where("repo_id = ?", repo.ID).And("sha = ?", sha).Find(&statuses)
145+
}
146+
147+
// GetLatestCommitStatus returns all statuses with a unique context for a given commit.
148+
func GetLatestCommitStatus(repo *Repository, sha string, page int) ([]*CommitStatus, error) {
149+
statuses := make([]*CommitStatus, 0, 10)
150+
sess := x.NewSession()
151+
defer sess.Close()
152+
153+
return statuses, sess.Limit(10, page*10).
154+
Where("repo_id = ?", repo.ID).And("sha = ?", sha).Select("*").
155+
GroupBy("context").Desc("created_unix").Find(&statuses)
156+
}
157+
158+
// GetCommitStatus populates a given status for a given commit.
159+
// NOTE: If ID or Index isn't given, and only Context, TargetURL and/or Description
160+
// is given, the CommitStatus created _last_ will be returned.
161+
func GetCommitStatus(repo *Repository, sha string, status *CommitStatus) (*CommitStatus, error) {
162+
conds := &CommitStatus{
163+
Context: status.Context,
164+
State: status.State,
165+
TargetURL: status.TargetURL,
166+
Description: status.Description,
167+
}
168+
has, err := x.Where("repo_id = ?", repo.ID).And("sha = ?", sha).Desc("created_unix").Get(conds)
169+
if err != nil {
170+
return nil, fmt.Errorf("GetCommitStatus[%s, %s]: %v", repo.RepoPath(), sha, err)
171+
}
172+
if !has {
173+
return nil, fmt.Errorf("GetCommitStatus[%s, %s]: not found", repo.RepoPath(), sha)
174+
}
175+
176+
return conds, nil
177+
}
178+
179+
// NewCommitStatusOptions holds options for creating a CommitStatus
180+
type NewCommitStatusOptions struct {
181+
Repo *Repository
182+
Creator *User
183+
SHA string
184+
CommitStatus *CommitStatus
185+
}
186+
187+
func newCommitStatus(e Engine, opts NewCommitStatusOptions) error {
188+
opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
189+
opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
190+
opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL)
191+
opts.CommitStatus.SHA = opts.SHA
192+
opts.CommitStatus.CreatorID = opts.Creator.ID
193+
194+
if opts.Repo == nil {
195+
return fmt.Errorf("newCommitStatus[nil, %s]: no repository specified", opts.SHA)
196+
}
197+
opts.CommitStatus.RepoID = opts.Repo.ID
198+
199+
if opts.Creator == nil {
200+
return fmt.Errorf("newCommitStatus[%s, %s]: no user specified", opts.Repo.RepoPath(), opts.SHA)
201+
}
202+
203+
gitRepo, err := git.OpenRepository(opts.Repo.RepoPath())
204+
if err != nil {
205+
return fmt.Errorf("OpenRepository[%s]: %v", opts.Repo.RepoPath(), err)
206+
}
207+
if _, err := gitRepo.GetCommit(opts.SHA); err != nil {
208+
return fmt.Errorf("GetCommit[%s]: %v", opts.SHA, err)
209+
}
210+
211+
sess := x.NewSession()
212+
defer sess.Close()
213+
if err = sess.Begin(); err != nil {
214+
return fmt.Errorf("newCommitStatus[%s, %s]: %v", opts.Repo.RepoPath(), opts.SHA, err)
215+
}
216+
217+
// Get the next Status Index
218+
var nextIndex int64
219+
lastCommitStatus := &CommitStatus{
220+
SHA: opts.SHA,
221+
RepoID: opts.Repo.ID,
222+
}
223+
has, err := sess.Desc("index").Limit(1).Get(lastCommitStatus)
224+
if err != nil {
225+
sess.Rollback()
226+
return fmt.Errorf("newCommitStatus[%s, %s]: %v", opts.Repo.RepoPath(), opts.SHA, err)
227+
}
228+
if has {
229+
log.Debug("newCommitStatus[%s, %s]: found", opts.Repo.RepoPath(), opts.SHA)
230+
nextIndex = lastCommitStatus.Index
231+
}
232+
opts.CommitStatus.Index = nextIndex + 1
233+
log.Debug("newCommitStatus[%s, %s]: %d", opts.Repo.RepoPath(), opts.SHA, opts.CommitStatus.Index)
234+
235+
// Insert new CommitStatus
236+
if _, err = sess.Insert(opts.CommitStatus); err != nil {
237+
sess.Rollback()
238+
return fmt.Errorf("newCommitStatus[%s, %s]: %v", opts.Repo.RepoPath(), opts.SHA, err)
239+
}
240+
sess.Commit()
241+
242+
return nil
243+
}
244+
245+
// NewCommitStatus creates a new CommitStatus given a bunch of parameters
246+
// NOTE: All text-values will be trimmed from whitespaces.
247+
// Requires: Repo, Creator, SHA
248+
func NewCommitStatus(repo *Repository, creator *User, sha string, status *CommitStatus) error {
249+
sess := x.NewSession()
250+
defer sess.Close()
251+
252+
if err := sess.Begin(); err != nil {
253+
return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", repo.ID, creator.ID, sha, err)
254+
}
255+
256+
if err := newCommitStatus(sess, NewCommitStatusOptions{
257+
Repo: repo,
258+
Creator: creator,
259+
SHA: sha,
260+
CommitStatus: status,
261+
}); err != nil {
262+
return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", repo.ID, creator.ID, sha, err)
263+
}
264+
265+
return nil
266+
}

0 commit comments

Comments
 (0)