Skip to content

Commit 92328a3

Browse files
sebastian-sauerAndrewBezold6543
authored
Add API to get commits of PR (#16300)
* Add API to get commits of PR fixes #10918 Co-authored-by: Andrew Bezold <andrew.bezold@gmail.com> Co-authored-by: 6543 <6543@obermui.de>
1 parent a3476e5 commit 92328a3

File tree

4 files changed

+215
-0
lines changed

4 files changed

+215
-0
lines changed

integrations/api_pull_commits_test.go

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright 2021 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 integrations
6+
7+
import (
8+
"net/http"
9+
"testing"
10+
11+
"code.gitea.io/gitea/models"
12+
api "code.gitea.io/gitea/modules/structs"
13+
"github.com/stretchr/testify/assert"
14+
)
15+
16+
func TestAPIPullCommits(t *testing.T) {
17+
defer prepareTestEnv(t)()
18+
pullIssue := models.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
19+
assert.NoError(t, pullIssue.LoadIssue())
20+
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.HeadRepoID}).(*models.Repository)
21+
22+
session := loginUser(t, "user2")
23+
req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits", repo.OwnerName, repo.Name, pullIssue.Index)
24+
resp := session.MakeRequest(t, req, http.StatusOK)
25+
26+
var commits []*api.Commit
27+
DecodeJSON(t, resp, &commits)
28+
29+
if !assert.Len(t, commits, 2) {
30+
return
31+
}
32+
33+
assert.Equal(t, "5f22f7d0d95d614d25a5b68592adb345a4b5c7fd", commits[0].SHA)
34+
assert.Equal(t, "4a357436d925b5c974181ff12a994538ddc5a269", commits[1].SHA)
35+
}
36+
37+
// TODO add tests for already merged PR and closed PR

routers/api/v1/api.go

+1
Original file line numberDiff line numberDiff line change
@@ -905,6 +905,7 @@ func Routes() *web.Route {
905905
m.Get(".diff", repo.DownloadPullDiff)
906906
m.Get(".patch", repo.DownloadPullPatch)
907907
m.Post("/update", reqToken(), repo.UpdatePullRequest)
908+
m.Get("/commits", repo.GetPullRequestCommits)
908909
m.Combo("/merge").Get(repo.IsPullRequestMerged).
909910
Post(reqToken(), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest)
910911
m.Group("/reviews", func() {

routers/api/v1/repo/pull.go

+121
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ package repo
66

77
import (
88
"fmt"
9+
"math"
910
"net/http"
11+
"strconv"
1012
"strings"
1113
"time"
1214

@@ -1101,3 +1103,122 @@ func UpdatePullRequest(ctx *context.APIContext) {
11011103

11021104
ctx.Status(http.StatusOK)
11031105
}
1106+
1107+
// GetPullRequestCommits gets all commits associated with a given PR
1108+
func GetPullRequestCommits(ctx *context.APIContext) {
1109+
// swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/commits repository repoGetPullRequestCommits
1110+
// ---
1111+
// summary: Get commits for a pull request
1112+
// produces:
1113+
// - application/json
1114+
// parameters:
1115+
// - name: owner
1116+
// in: path
1117+
// description: owner of the repo
1118+
// type: string
1119+
// required: true
1120+
// - name: repo
1121+
// in: path
1122+
// description: name of the repo
1123+
// type: string
1124+
// required: true
1125+
// - name: index
1126+
// in: path
1127+
// description: index of the pull request to get
1128+
// type: integer
1129+
// format: int64
1130+
// required: true
1131+
// - name: page
1132+
// in: query
1133+
// description: page number of results to return (1-based)
1134+
// type: integer
1135+
// - name: limit
1136+
// in: query
1137+
// description: page size of results
1138+
// type: integer
1139+
// responses:
1140+
// "200":
1141+
// "$ref": "#/responses/CommitList"
1142+
// "404":
1143+
// "$ref": "#/responses/notFound"
1144+
1145+
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
1146+
if err != nil {
1147+
if models.IsErrPullRequestNotExist(err) {
1148+
ctx.NotFound()
1149+
} else {
1150+
ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
1151+
}
1152+
return
1153+
}
1154+
1155+
if err := pr.LoadBaseRepo(); err != nil {
1156+
ctx.InternalServerError(err)
1157+
return
1158+
}
1159+
1160+
var prInfo *git.CompareInfo
1161+
baseGitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
1162+
if err != nil {
1163+
ctx.ServerError("OpenRepository", err)
1164+
return
1165+
}
1166+
defer baseGitRepo.Close()
1167+
if pr.HasMerged {
1168+
prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.MergeBase, pr.GetGitRefName())
1169+
} else {
1170+
prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.BaseBranch, pr.GetGitRefName())
1171+
}
1172+
if err != nil {
1173+
ctx.ServerError("GetCompareInfo", err)
1174+
return
1175+
}
1176+
commits := prInfo.Commits
1177+
1178+
listOptions := utils.GetListOptions(ctx)
1179+
1180+
totalNumberOfCommits := commits.Len()
1181+
totalNumberOfPages := int(math.Ceil(float64(totalNumberOfCommits) / float64(listOptions.PageSize)))
1182+
1183+
userCache := make(map[string]*models.User)
1184+
1185+
start, end := listOptions.GetStartEnd()
1186+
1187+
if end > totalNumberOfCommits {
1188+
end = totalNumberOfCommits
1189+
}
1190+
1191+
apiCommits := make([]*api.Commit, end-start)
1192+
1193+
i := 0
1194+
addedCommitsCount := 0
1195+
for commitPointer := commits.Front(); commitPointer != nil; commitPointer = commitPointer.Next() {
1196+
if i < start {
1197+
i++
1198+
continue
1199+
}
1200+
if i >= end {
1201+
break
1202+
}
1203+
1204+
commit := commitPointer.Value.(*git.Commit)
1205+
1206+
// Create json struct
1207+
apiCommits[addedCommitsCount], err = convert.ToCommit(ctx.Repo.Repository, commit, userCache)
1208+
addedCommitsCount++
1209+
if err != nil {
1210+
ctx.ServerError("toCommit", err)
1211+
return
1212+
}
1213+
i++
1214+
}
1215+
1216+
ctx.SetLinkHeader(int(totalNumberOfCommits), listOptions.PageSize)
1217+
1218+
ctx.Header().Set("X-Page", strconv.Itoa(listOptions.Page))
1219+
ctx.Header().Set("X-PerPage", strconv.Itoa(listOptions.PageSize))
1220+
ctx.Header().Set("X-Total-Count", fmt.Sprintf("%d", totalNumberOfCommits))
1221+
ctx.Header().Set("X-PageCount", strconv.Itoa(totalNumberOfPages))
1222+
ctx.Header().Set("X-HasMore", strconv.FormatBool(listOptions.Page < totalNumberOfPages))
1223+
ctx.JSON(http.StatusOK, &apiCommits)
1224+
}

templates/swagger/v1_json.tmpl

+56
Original file line numberDiff line numberDiff line change
@@ -7333,6 +7333,62 @@
73337333
}
73347334
}
73357335
},
7336+
"/repos/{owner}/{repo}/pulls/{index}/commits": {
7337+
"get": {
7338+
"produces": [
7339+
"application/json"
7340+
],
7341+
"tags": [
7342+
"repository"
7343+
],
7344+
"summary": "Get commits for a pull request",
7345+
"operationId": "repoGetPullRequestCommits",
7346+
"parameters": [
7347+
{
7348+
"type": "string",
7349+
"description": "owner of the repo",
7350+
"name": "owner",
7351+
"in": "path",
7352+
"required": true
7353+
},
7354+
{
7355+
"type": "string",
7356+
"description": "name of the repo",
7357+
"name": "repo",
7358+
"in": "path",
7359+
"required": true
7360+
},
7361+
{
7362+
"type": "integer",
7363+
"format": "int64",
7364+
"description": "index of the pull request to get",
7365+
"name": "index",
7366+
"in": "path",
7367+
"required": true
7368+
},
7369+
{
7370+
"type": "integer",
7371+
"description": "page number of results to return (1-based)",
7372+
"name": "page",
7373+
"in": "query"
7374+
},
7375+
{
7376+
"type": "integer",
7377+
"description": "page size of results",
7378+
"name": "limit",
7379+
"in": "query"
7380+
}
7381+
],
7382+
"responses": {
7383+
"200": {
7384+
"$ref": "#/responses/CommitList"
7385+
},
7386+
"404": {
7387+
"$ref": "#/responses/notFound"
7388+
}
7389+
}
7390+
}
7391+
},
73367392
"/repos/{owner}/{repo}/pulls/{index}/merge": {
73377393
"get": {
73387394
"produces": [

0 commit comments

Comments
 (0)