Skip to content

Commit e483220

Browse files
authored
[Refactor] CombinedStatus and CommitStatus related functions & structs (#14026)
* RM unused struct * rename (*CommitStatus) loadRepo() -> loadAttributes() * move ToCommitStatus into its own file * use CommitStatusState instead of StatusState * move CombinedStatus convertion into convert package * let models.GetLatestCommitStatus use repoID direct and accept ListOptions * update swagger docs * fix tests * Fix swagger docs * rm page * fix swagger docs!!! * return json null * always return json * rename api.Status to api.CommitStatus * fix swagger docs * sec swagger fix
1 parent 27edc1a commit e483220

File tree

17 files changed

+341
-206
lines changed

17 files changed

+341
-206
lines changed

integrations/pull_status_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ func TestPullCreate_CommitStatus(t *testing.T) {
7070
token := getTokenForLoggedInUser(t, session)
7171
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/user1/repo1/statuses/%s?token=%s", commitID, token),
7272
api.CreateStatusOption{
73-
State: api.StatusState(status),
73+
State: status,
7474
TargetURL: "http://test.ci/",
7575
Description: "",
7676
Context: "testci",

integrations/repo_commits_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) {
5151
// Call API to add status for commit
5252
req = NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/statuses/"+path.Base(commitURL)+"?token="+token,
5353
api.CreateStatusOption{
54-
State: api.StatusState(state),
54+
State: api.CommitStatusState(state),
5555
TargetURL: "http://test.ci/",
5656
Description: "",
5757
Context: "testci",
@@ -83,11 +83,11 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) {
8383

8484
func testRepoCommitsWithStatus(t *testing.T, resp *httptest.ResponseRecorder, state string) {
8585
decoder := json.NewDecoder(resp.Body)
86-
statuses := []*api.Status{}
86+
statuses := []*api.CommitStatus{}
8787
assert.NoError(t, decoder.Decode(&statuses))
8888
assert.Len(t, statuses, 1)
8989
for _, s := range statuses {
90-
assert.Equal(t, api.StatusState(state), s.State)
90+
assert.Equal(t, api.CommitStatusState(state), s.State)
9191
assert.Equal(t, setting.AppURL+"api/v1/repos/user2/repo1/statuses/65f1bf27bc3bf70f64657658635e66094edbcb4d", s.URL)
9292
assert.Equal(t, "http://test.ci/", s.TargetURL)
9393
assert.Equal(t, "", s.Description)

models/commit_status.go

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ type CommitStatus struct {
3838
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
3939
}
4040

41-
func (status *CommitStatus) loadRepo(e Engine) (err error) {
41+
func (status *CommitStatus) loadAttributes(e Engine) (err error) {
4242
if status.Repo == nil {
4343
status.Repo, err = getRepositoryByID(e, status.RepoID)
4444
if err != nil {
@@ -56,7 +56,7 @@ func (status *CommitStatus) loadRepo(e Engine) (err error) {
5656

5757
// APIURL returns the absolute APIURL to this commit-status.
5858
func (status *CommitStatus) APIURL() string {
59-
_ = status.loadRepo(x)
59+
_ = status.loadAttributes(x)
6060
return fmt.Sprintf("%sapi/v1/repos/%s/statuses/%s",
6161
setting.AppURL, status.Repo.FullName(), status.SHA)
6262
}
@@ -139,13 +139,20 @@ func sortCommitStatusesSession(sess *xorm.Session, sortType string) {
139139
}
140140

141141
// GetLatestCommitStatus returns all statuses with a unique context for a given commit.
142-
func GetLatestCommitStatus(repo *Repository, sha string, page int) ([]*CommitStatus, error) {
142+
func GetLatestCommitStatus(repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) {
143+
return getLatestCommitStatus(x, repoID, sha, listOptions)
144+
}
145+
146+
func getLatestCommitStatus(e Engine, repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) {
143147
ids := make([]int64, 0, 10)
144-
err := x.Limit(10, page*10).
145-
Table(&CommitStatus{}).
146-
Where("repo_id = ?", repo.ID).And("sha = ?", sha).
148+
sess := e.Table(&CommitStatus{}).
149+
Where("repo_id = ?", repoID).And("sha = ?", sha).
147150
Select("max( id ) as id").
148-
GroupBy("context_hash").OrderBy("max( id ) desc").Find(&ids)
151+
GroupBy("context_hash").OrderBy("max( id ) desc")
152+
153+
sess = listOptions.setSessionPagination(sess)
154+
155+
err := sess.Find(&ids)
149156
if err != nil {
150157
return nil, err
151158
}
@@ -261,7 +268,7 @@ func ParseCommitsWithStatus(oldCommits *list.List, repo *Repository) *list.List
261268
commit := SignCommitWithStatuses{
262269
SignCommit: &c,
263270
}
264-
statuses, err := GetLatestCommitStatus(repo, commit.ID.String(), 0)
271+
statuses, err := GetLatestCommitStatus(repo.ID, commit.ID.String(), ListOptions{})
265272
if err != nil {
266273
log.Error("GetLatestCommitStatus: %v", err)
267274
} else {

modules/convert/convert.go

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -347,27 +347,6 @@ func ToOAuth2Application(app *models.OAuth2Application) *api.OAuth2Application {
347347
}
348348
}
349349

350-
// ToCommitStatus converts models.CommitStatus to api.Status
351-
func ToCommitStatus(status *models.CommitStatus) *api.Status {
352-
apiStatus := &api.Status{
353-
Created: status.CreatedUnix.AsTime(),
354-
Updated: status.CreatedUnix.AsTime(),
355-
State: api.StatusState(status.State),
356-
TargetURL: status.TargetURL,
357-
Description: status.Description,
358-
ID: status.Index,
359-
URL: status.APIURL(),
360-
Context: status.Context,
361-
}
362-
363-
if status.CreatorID != 0 {
364-
creator, _ := models.GetUserByID(status.CreatorID)
365-
apiStatus.Creator = ToUser(creator, false, false)
366-
}
367-
368-
return apiStatus
369-
}
370-
371350
// ToLFSLock convert a LFSLock to api.LFSLock
372351
func ToLFSLock(l *models.LFSLock) *api.LFSLock {
373352
return &api.LFSLock{

modules/convert/status.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright 2020 The Gitea Authors. 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 convert
6+
7+
import (
8+
"code.gitea.io/gitea/models"
9+
api "code.gitea.io/gitea/modules/structs"
10+
)
11+
12+
// ToCommitStatus converts models.CommitStatus to api.CommitStatus
13+
func ToCommitStatus(status *models.CommitStatus) *api.CommitStatus {
14+
apiStatus := &api.CommitStatus{
15+
Created: status.CreatedUnix.AsTime(),
16+
Updated: status.CreatedUnix.AsTime(),
17+
State: status.State,
18+
TargetURL: status.TargetURL,
19+
Description: status.Description,
20+
ID: status.Index,
21+
URL: status.APIURL(),
22+
Context: status.Context,
23+
}
24+
25+
if status.CreatorID != 0 {
26+
creator, _ := models.GetUserByID(status.CreatorID)
27+
apiStatus.Creator = ToUser(creator, false, false)
28+
}
29+
30+
return apiStatus
31+
}
32+
33+
// ToCombinedStatus converts List of CommitStatus to a CombinedStatus
34+
func ToCombinedStatus(statuses []*models.CommitStatus, repo *api.Repository) *api.CombinedStatus {
35+
36+
if len(statuses) == 0 {
37+
return nil
38+
}
39+
40+
retStatus := &api.CombinedStatus{
41+
SHA: statuses[0].SHA,
42+
TotalCount: len(statuses),
43+
Repository: repo,
44+
URL: "",
45+
}
46+
47+
retStatus.Statuses = make([]*api.CommitStatus, 0, len(statuses))
48+
for _, status := range statuses {
49+
retStatus.Statuses = append(retStatus.Statuses, ToCommitStatus(status))
50+
if status.State.NoBetterThan(retStatus.State) {
51+
retStatus.State = status.State
52+
}
53+
}
54+
55+
return retStatus
56+
}

modules/gitgraph/graph_models.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ func (graph *Graph) LoadAndProcessCommits(repository *models.Repository, gitRepo
113113

114114
_ = models.CalculateTrustStatus(c.Verification, repository, &keyMap)
115115

116-
statuses, err := models.GetLatestCommitStatus(repository, c.Commit.ID.String(), 0)
116+
statuses, err := models.GetLatestCommitStatus(repository.ID, c.Commit.ID.String(), models.ListOptions{})
117117
if err != nil {
118118
log.Error("GetLatestCommitStatus: %v", err)
119119
} else {

modules/structs/commit_status.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,20 @@
44

55
package structs
66

7-
// CommitStatusState holds the state of a Status
7+
// CommitStatusState holds the state of a CommitStatus
88
// It can be "pending", "success", "error", "failure", and "warning"
99
type CommitStatusState string
1010

1111
const (
12-
// CommitStatusPending is for when the Status is Pending
12+
// CommitStatusPending is for when the CommitStatus is Pending
1313
CommitStatusPending CommitStatusState = "pending"
14-
// CommitStatusSuccess is for when the Status is Success
14+
// CommitStatusSuccess is for when the CommitStatus is Success
1515
CommitStatusSuccess CommitStatusState = "success"
16-
// CommitStatusError is for when the Status is Error
16+
// CommitStatusError is for when the CommitStatus is Error
1717
CommitStatusError CommitStatusState = "error"
18-
// CommitStatusFailure is for when the Status is Failure
18+
// CommitStatusFailure is for when the CommitStatus is Failure
1919
CommitStatusFailure CommitStatusState = "failure"
20-
// CommitStatusWarning is for when the Status is Warning
20+
// CommitStatusWarning is for when the CommitStatus is Warning
2121
CommitStatusWarning CommitStatusState = "warning"
2222
)
2323

modules/structs/status.go

Lines changed: 21 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -8,32 +8,15 @@ import (
88
"time"
99
)
1010

11-
// StatusState holds the state of a Status
12-
// It can be "pending", "success", "error", "failure", and "warning"
13-
type StatusState string
14-
15-
const (
16-
// StatusPending is for when the Status is Pending
17-
StatusPending StatusState = "pending"
18-
// StatusSuccess is for when the Status is Success
19-
StatusSuccess StatusState = "success"
20-
// StatusError is for when the Status is Error
21-
StatusError StatusState = "error"
22-
// StatusFailure is for when the Status is Failure
23-
StatusFailure StatusState = "failure"
24-
// StatusWarning is for when the Status is Warning
25-
StatusWarning StatusState = "warning"
26-
)
27-
28-
// Status holds a single Status of a single Commit
29-
type Status struct {
30-
ID int64 `json:"id"`
31-
State StatusState `json:"status"`
32-
TargetURL string `json:"target_url"`
33-
Description string `json:"description"`
34-
URL string `json:"url"`
35-
Context string `json:"context"`
36-
Creator *User `json:"creator"`
11+
// CommitStatus holds a single status of a single Commit
12+
type CommitStatus struct {
13+
ID int64 `json:"id"`
14+
State CommitStatusState `json:"status"`
15+
TargetURL string `json:"target_url"`
16+
Description string `json:"description"`
17+
URL string `json:"url"`
18+
Context string `json:"context"`
19+
Creator *User `json:"creator"`
3720
// swagger:strfmt date-time
3821
Created time.Time `json:"created_at"`
3922
// swagger:strfmt date-time
@@ -42,24 +25,19 @@ type Status struct {
4225

4326
// CombinedStatus holds the combined state of several statuses for a single commit
4427
type CombinedStatus struct {
45-
State StatusState `json:"state"`
46-
SHA string `json:"sha"`
47-
TotalCount int `json:"total_count"`
48-
Statuses []*Status `json:"statuses"`
49-
Repository *Repository `json:"repository"`
50-
CommitURL string `json:"commit_url"`
51-
URL string `json:"url"`
28+
State CommitStatusState `json:"state"`
29+
SHA string `json:"sha"`
30+
TotalCount int `json:"total_count"`
31+
Statuses []*CommitStatus `json:"statuses"`
32+
Repository *Repository `json:"repository"`
33+
CommitURL string `json:"commit_url"`
34+
URL string `json:"url"`
5235
}
5336

54-
// CreateStatusOption holds the information needed to create a new Status for a Commit
37+
// CreateStatusOption holds the information needed to create a new CommitStatus for a Commit
5538
type CreateStatusOption struct {
56-
State StatusState `json:"state"`
57-
TargetURL string `json:"target_url"`
58-
Description string `json:"description"`
59-
Context string `json:"context"`
60-
}
61-
62-
// ListStatusesOption holds pagination information
63-
type ListStatusesOption struct {
64-
Page int
39+
State CommitStatusState `json:"state"`
40+
TargetURL string `json:"target_url"`
41+
Description string `json:"description"`
42+
Context string `json:"context"`
6543
}

routers/api/v1/repo/status.go

Lines changed: 16 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func NewCommitStatus(ctx *context.APIContext, form api.CreateStatusOption) {
4545
// "$ref": "#/definitions/CreateStatusOption"
4646
// responses:
4747
// "201":
48-
// "$ref": "#/responses/Status"
48+
// "$ref": "#/responses/CommitStatus"
4949
// "400":
5050
// "$ref": "#/responses/error"
5151

@@ -113,7 +113,7 @@ func GetCommitStatuses(ctx *context.APIContext) {
113113
// type: integer
114114
// responses:
115115
// "200":
116-
// "$ref": "#/responses/StatusList"
116+
// "$ref": "#/responses/CommitStatusList"
117117
// "400":
118118
// "$ref": "#/responses/error"
119119

@@ -165,7 +165,7 @@ func GetCommitStatusesByRef(ctx *context.APIContext) {
165165
// type: integer
166166
// responses:
167167
// "200":
168-
// "$ref": "#/responses/StatusList"
168+
// "$ref": "#/responses/CommitStatusList"
169169
// "400":
170170
// "$ref": "#/responses/error"
171171

@@ -221,7 +221,7 @@ func getCommitStatuses(ctx *context.APIContext, sha string) {
221221
return
222222
}
223223

224-
apiStatuses := make([]*api.Status, 0, len(statuses))
224+
apiStatuses := make([]*api.CommitStatus, 0, len(statuses))
225225
for _, status := range statuses {
226226
apiStatuses = append(apiStatuses, convert.ToCommitStatus(status))
227227
}
@@ -233,19 +233,9 @@ func getCommitStatuses(ctx *context.APIContext, sha string) {
233233
ctx.JSON(http.StatusOK, apiStatuses)
234234
}
235235

236-
type combinedCommitStatus struct {
237-
State api.CommitStatusState `json:"state"`
238-
SHA string `json:"sha"`
239-
TotalCount int `json:"total_count"`
240-
Statuses []*api.Status `json:"statuses"`
241-
Repo *api.Repository `json:"repository"`
242-
CommitURL string `json:"commit_url"`
243-
URL string `json:"url"`
244-
}
245-
246236
// GetCombinedCommitStatusByRef returns the combined status for any given commit hash
247237
func GetCombinedCommitStatusByRef(ctx *context.APIContext) {
248-
// swagger:operation GET /repos/{owner}/{repo}/commits/{ref}/statuses repository repoGetCombinedStatusByRef
238+
// swagger:operation GET /repos/{owner}/{repo}/commits/{ref}/status repository repoGetCombinedStatusByRef
249239
// ---
250240
// summary: Get a commit's combined status, by branch/tag/commit reference
251241
// produces:
@@ -268,12 +258,15 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) {
268258
// required: true
269259
// - name: page
270260
// in: query
271-
// description: page number of results
261+
// description: page number of results to return (1-based)
262+
// type: integer
263+
// - name: limit
264+
// in: query
265+
// description: page size of results
272266
// type: integer
273-
// required: false
274267
// responses:
275268
// "200":
276-
// "$ref": "#/responses/Status"
269+
// "$ref": "#/responses/CombinedStatus"
277270
// "400":
278271
// "$ref": "#/responses/error"
279272

@@ -284,33 +277,18 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) {
284277
}
285278
repo := ctx.Repo.Repository
286279

287-
page := ctx.QueryInt("page")
288-
289-
statuses, err := models.GetLatestCommitStatus(repo, sha, page)
280+
statuses, err := models.GetLatestCommitStatus(repo.ID, sha, utils.GetListOptions(ctx))
290281
if err != nil {
291-
ctx.Error(http.StatusInternalServerError, "GetLatestCommitStatus", fmt.Errorf("GetLatestCommitStatus[%s, %s, %d]: %v", repo.FullName(), sha, page, err))
282+
ctx.Error(http.StatusInternalServerError, "GetLatestCommitStatus", fmt.Errorf("GetLatestCommitStatus[%s, %s]: %v", repo.FullName(), sha, err))
292283
return
293284
}
294285

295286
if len(statuses) == 0 {
296-
ctx.Status(http.StatusOK)
287+
ctx.JSON(http.StatusOK, &api.CombinedStatus{})
297288
return
298289
}
299290

300-
retStatus := &combinedCommitStatus{
301-
SHA: sha,
302-
TotalCount: len(statuses),
303-
Repo: convert.ToRepo(repo, ctx.Repo.AccessMode),
304-
URL: "",
305-
}
306-
307-
retStatus.Statuses = make([]*api.Status, 0, len(statuses))
308-
for _, status := range statuses {
309-
retStatus.Statuses = append(retStatus.Statuses, convert.ToCommitStatus(status))
310-
if status.State.NoBetterThan(retStatus.State) {
311-
retStatus.State = status.State
312-
}
313-
}
291+
combiStatus := convert.ToCombinedStatus(statuses, convert.ToRepo(repo, ctx.Repo.AccessMode))
314292

315-
ctx.JSON(http.StatusOK, retStatus)
293+
ctx.JSON(http.StatusOK, combiStatus)
316294
}

0 commit comments

Comments
 (0)