Skip to content

Commit

Permalink
Added API endpoint ListAllCommits (/repos/{owner}/{repo}/git/commits)
Browse files Browse the repository at this point in the history
Signed-off-by: Mike Schwörer <mailport@mikescher.de>
  • Loading branch information
Mikescher committed Jun 11, 2019
1 parent 74690f6 commit d4273db
Show file tree
Hide file tree
Showing 4 changed files with 345 additions and 0 deletions.
58 changes: 58 additions & 0 deletions integrations/api_repo_git_commits_test.go
Expand Up @@ -9,6 +9,9 @@ import (
"testing"

"code.gitea.io/gitea/models"
api "code.gitea.io/sdk/gitea"

"github.com/stretchr/testify/assert"
)

func TestAPIReposGitCommits(t *testing.T) {
Expand All @@ -30,3 +33,58 @@ func TestAPIReposGitCommits(t *testing.T) {
req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/unknown?token="+token, user.Name)
session.MakeRequest(t, req, http.StatusNotFound)
}

func TestAPIReposGitCommitList(t *testing.T) {
prepareTestEnv(t)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

// Test getting commits (Page 1)
req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits?token="+token, user.Name)
resp := session.MakeRequest(t, req, http.StatusOK)

var apiData []api.Commit
DecodeJSON(t, resp, &apiData)

assert.Equal(t, 3, len(apiData))
assert.Equal(t, "69554a64c1e6030f051e5c3f94bfbd773cd6a324", apiData[0].CommitMeta.SHA)
assert.Equal(t, "27566bd5738fc8b4e3fef3c5e72cce608537bd95", apiData[1].CommitMeta.SHA)
assert.Equal(t, "5099b81332712fe655e34e8dd63574f503f61811", apiData[2].CommitMeta.SHA)
}

func TestAPIReposGitCommitListPage2Empty(t *testing.T) {
prepareTestEnv(t)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

// Test getting commits (Page=2)
req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits?token="+token+"&page=2", user.Name)
resp := session.MakeRequest(t, req, http.StatusOK)

var apiData []api.Commit
DecodeJSON(t, resp, &apiData)

assert.Equal(t, 0, len(apiData))
}

func TestAPIReposGitCommitListDifferentBranch(t *testing.T) {
prepareTestEnv(t)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

// Test getting commits (Page=1, Branch=good-sign)
req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits?token="+token+"&sha=good-sign", user.Name)
resp := session.MakeRequest(t, req, http.StatusOK)

var apiData []api.Commit
DecodeJSON(t, resp, &apiData)

assert.Equal(t, 1, len(apiData))
assert.Equal(t, "f27c2b2b03dcab38beaf89b0ab4ff61f6de63441", apiData[0].CommitMeta.SHA)
}
1 change: 1 addition & 0 deletions routers/api/v1/api.go
Expand Up @@ -757,6 +757,7 @@ func RegisterRoutes(m *macaron.Macaron) {
}, reqRepoReader(models.UnitTypeCode))
m.Group("/git", func() {
m.Group("/commits", func() {
m.Get("", repo.GetAllCommits)
m.Get("/:sha", repo.GetSingleCommit)
})
m.Get("/refs", repo.GetGitAllRefs)
Expand Down
203 changes: 203 additions & 0 deletions routers/api/v1/repo/commits.go
Expand Up @@ -6,6 +6,8 @@
package repo

import (
"math"
"strconv"
"time"

"code.gitea.io/gitea/models"
Expand Down Expand Up @@ -120,3 +122,204 @@ func GetSingleCommit(ctx *context.APIContext) {
Parents: apiParents,
})
}

// GetAllCommits get all commits via
func GetAllCommits(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/git/commits repository repoGetAllCommits
// ---
// summary: Get a list of all commits from a repository
// produces:
// - application/json
// parameters:
// - name: owner
// in: path
// description: owner of the repo
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repo
// type: string
// required: true
// - name: sha
// in: query
// description: SHA or branch to start listing commits from (usually 'master')
// type: string
// - name: page
// in: query
// description: page number of requested commits
// type: integer
// responses:
// "200":
// "$ref": "#/responses/CommitList"
// "404":
// "$ref": "#/responses/notFound"

gitRepo, err := git.OpenRepository(ctx.Repo.Repository.RepoPath())
if err != nil {
ctx.ServerError("OpenRepository", err)
return
}

page := ctx.QueryInt("page")
if page <= 0 {
page = 1
}

sha := ctx.Query("sha")

var baseCommit *git.Commit
if len(sha) == 0 {
// no sha supplied - use default branch
head, err := gitRepo.GetHEADBranch()
if err != nil {
ctx.ServerError("GetHEADBranch", err)
return
}
baseCommit, err = gitRepo.GetBranchCommit(head.Name)
if err != nil {
ctx.ServerError("GetCommit", err)
return
}
} else {
// get commit specified by sha
baseCommit, err = gitRepo.GetCommit(sha)
if err != nil {
ctx.ServerError("GetCommit", err)
return
}
}

// Total commit count
commitsCountTotal, err := baseCommit.CommitsCount()
if err != nil {
ctx.ServerError("GetCommitsCount", err)
return
}

pageCount := int(math.Ceil(float64(commitsCountTotal) / float64(git.CommitsRangeSize)))

// Query commits
commits, err := baseCommit.CommitsByRange(page)
if err != nil {
ctx.ServerError("CommitsByRange", err)
return
}

userCache := make(map[string]*models.User)

apiCommits := make([]*api.Commit, commits.Len())

i := 0
for commitPointer := commits.Front(); commitPointer != nil; commitPointer = commitPointer.Next() {
commit := commitPointer.Value.(*git.Commit)

var apiAuthor, apiCommitter *api.User

// Retrieve author and committer information
cacheAuthor, ok := userCache[commit.Author.Email]
if ok {
apiAuthor = cacheAuthor.APIFormat()
} else {
author, err := models.GetUserByEmail(commit.Author.Email)
if err != nil && !models.IsErrUserNotExist(err) {
ctx.ServerError("Get user by author email", err)
return
} else if err == nil {
apiAuthor = author.APIFormat()
userCache[commit.Author.Email] = author
}
}
cacheCommitter, ok := userCache[commit.Committer.Email]
if ok {
apiCommitter = cacheCommitter.APIFormat()
} else {
committer, err := models.GetUserByEmail(commit.Committer.Email)
if err != nil && !models.IsErrUserNotExist(err) {
ctx.ServerError("Get user by committer email", err)
return
} else if err == nil {
apiCommitter = committer.APIFormat()
userCache[commit.Committer.Email] = committer
}
}

// Retrieve parent(s) of the commit
apiParents := make([]*api.CommitMeta, commit.ParentCount())
for i := 0; i < commit.ParentCount(); i++ {
sha, _ := commit.ParentID(i)
apiParents[i] = &api.CommitMeta{
URL: ctx.Repo.Repository.APIURL() + "/git/commits/" + sha.String(),
SHA: sha.String(),
}
}

// Create json struct
apiCommits[i] = &api.Commit{
CommitMeta: &api.CommitMeta{
URL: ctx.Repo.Repository.APIURL() + "/git/commits/" + commit.ID.String(),
SHA: commit.ID.String(),
},
HTMLURL: ctx.Repo.Repository.HTMLURL() + "/commits/" + commit.ID.String(),
RepoCommit: &api.RepoCommit{
URL: setting.AppURL + ctx.Link[1:],
Author: &api.CommitUser{
Identity: api.Identity{
Name: commit.Committer.Name,
Email: commit.Committer.Email,
},
Date: commit.Author.When.Format(time.RFC3339),
},
Committer: &api.CommitUser{
Identity: api.Identity{
Name: commit.Committer.Name,
Email: commit.Committer.Email,
},
Date: commit.Committer.When.Format(time.RFC3339),
},
Message: commit.Summary(),
Tree: &api.CommitMeta{
URL: ctx.Repo.Repository.APIURL() + "/trees/" + commit.ID.String(),
SHA: commit.ID.String(),
},
},
Author: apiAuthor,
Committer: apiCommitter,
Parents: apiParents,
}

i++
}

ctx.SetLinkHeader(int(commitsCountTotal), git.CommitsRangeSize)

ctx.Header().Set("X-Page", strconv.Itoa(page))
ctx.Header().Set("X-PerPage", strconv.Itoa(git.CommitsRangeSize))
ctx.Header().Set("X-Total", strconv.FormatInt(commitsCountTotal, 10))
ctx.Header().Set("X-PageCount", strconv.Itoa(pageCount))
ctx.Header().Set("X-HasMore", strconv.FormatBool(page < pageCount))

ctx.JSON(200, &apiCommits)
}

// CommitList
// swagger:response CommitList
type swaggerCommitList struct {
// The current page
Page int `json:"X-Page"`

// Commits per page
PerPage int `json:"X-PerPage"`

// Total commit count
Total int `json:"X-Total"`

// Total number of pages
PageCount int `json:"X-PageCount"`

// True if there is another page
HasMore bool `json:"X-HasMore"`

//in: body
Body []api.Commit `json:"body"`
}
83 changes: 83 additions & 0 deletions templates/swagger/v1_json.tmpl
Expand Up @@ -1914,6 +1914,54 @@
}
}
},
"/repos/{owner}/{repo}/git/commits": {
"get": {
"produces": [
"application/json"
],
"tags": [
"repository"
],
"summary": "Get a list of all commits from a repository",
"operationId": "repoGetAllCommits",
"parameters": [
{
"type": "string",
"description": "owner of the repo",
"name": "owner",
"in": "path",
"required": true
},
{
"type": "string",
"description": "name of the repo",
"name": "repo",
"in": "path",
"required": true
},
{
"type": "string",
"description": "SHA or branch to start listing commits from (usually 'master')",
"name": "sha",
"in": "query"
},
{
"type": "integer",
"description": "page number of requested commits",
"name": "page",
"in": "query"
}
],
"responses": {
"200": {
"$ref": "#/responses/CommitList"
},
"404": {
"$ref": "#/responses/notFound"
}
}
}
},
"/repos/{owner}/{repo}/git/commits/{sha}": {
"get": {
"produces": [
Expand Down Expand Up @@ -9876,6 +9924,41 @@
"$ref": "#/definitions/Commit"
}
},
"CommitList": {
"description": "CommitList",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Commit"
}
},
"headers": {
"X-HasMore": {
"type": "boolean",
"description": "True if there is another page"
},
"X-Page": {
"type": "integer",
"format": "int64",
"description": "The current page"
},
"X-PageCount": {
"type": "integer",
"format": "int64",
"description": "Total number of pages"
},
"X-PerPage": {
"type": "integer",
"format": "int64",
"description": "Commits per page"
},
"X-Total": {
"type": "integer",
"format": "int64",
"description": "Total commit count"
}
}
},
"DeployKey": {
"description": "DeployKey",
"schema": {
Expand Down

0 comments on commit d4273db

Please sign in to comment.