Skip to content

Commit 0f05470

Browse files
authored
[API] Pull Requests (#248)
1 parent d7ed78a commit 0f05470

File tree

6 files changed

+592
-0
lines changed

6 files changed

+592
-0
lines changed

models/error.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,28 @@ func (err ErrPullRequestNotExist) Error() string {
584584
err.ID, err.IssueID, err.HeadRepoID, err.BaseRepoID, err.HeadBarcnh, err.BaseBranch)
585585
}
586586

587+
// ErrPullRequestAlreadyExists represents a "PullRequestAlreadyExists"-error
588+
type ErrPullRequestAlreadyExists struct {
589+
ID int64
590+
IssueID int64
591+
HeadRepoID int64
592+
BaseRepoID int64
593+
HeadBranch string
594+
BaseBranch string
595+
}
596+
597+
// IsErrPullRequestAlreadyExists checks if an error is a ErrPullRequestAlreadyExists.
598+
func IsErrPullRequestAlreadyExists(err error) bool {
599+
_, ok := err.(ErrPullRequestAlreadyExists)
600+
return ok
601+
}
602+
603+
// Error does pretty-printing :D
604+
func (err ErrPullRequestAlreadyExists) Error() string {
605+
return fmt.Sprintf("pull request already exists for these targets [id: %d, issue_id: %d, head_repo_id: %d, base_repo_id: %d, head_branch: %s, base_branch: %s]",
606+
err.ID, err.IssueID, err.HeadRepoID, err.BaseRepoID, err.HeadBranch, err.BaseBranch)
607+
}
608+
587609
// _________ __
588610
// \_ ___ \ ____ _____ _____ ____ _____/ |_
589611
// / \ \/ / _ \ / \ / \_/ __ \ / \ __\

models/issue.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,22 @@ func (issue *Issue) HTMLURL() string {
170170
return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
171171
}
172172

173+
// DiffURL returns the absolute URL to this diff
174+
func (issue *Issue) DiffURL() string {
175+
if issue.IsPull {
176+
return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
177+
}
178+
return ""
179+
}
180+
181+
// PatchURL returns the absolute URL to this patch
182+
func (issue *Issue) PatchURL() string {
183+
if issue.IsPull {
184+
return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
185+
}
186+
return ""
187+
}
188+
173189
// State returns string representation of issue status.
174190
func (issue *Issue) State() api.StateType {
175191
if issue.IsClosed {

models/pull.go

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,26 @@ func (pr *PullRequest) LoadIssue() (err error) {
121121
// Required - Issue
122122
// Optional - Merger
123123
func (pr *PullRequest) APIFormat() *api.PullRequest {
124+
124125
apiIssue := pr.Issue.APIFormat()
126+
baseBranch, _ := pr.BaseRepo.GetBranch(pr.BaseBranch)
127+
baseCommit, _ := baseBranch.GetCommit()
128+
headBranch, _ := pr.HeadRepo.GetBranch(pr.HeadBranch)
129+
headCommit, _ := headBranch.GetCommit()
130+
apiBaseBranchInfo := &api.PRBranchInfo{
131+
Name: pr.BaseBranch,
132+
Ref: pr.BaseBranch,
133+
Sha: baseCommit.ID.String(),
134+
RepoID: pr.BaseRepoID,
135+
Repository: pr.BaseRepo.APIFormat(nil),
136+
}
137+
apiHeadBranchInfo := &api.PRBranchInfo{
138+
Name: pr.HeadBranch,
139+
Ref: pr.HeadBranch,
140+
Sha: headCommit.ID.String(),
141+
RepoID: pr.HeadRepoID,
142+
Repository: pr.HeadRepo.APIFormat(nil),
143+
}
125144
apiPullRequest := &api.PullRequest{
126145
ID: pr.ID,
127146
Index: pr.Index,
@@ -134,7 +153,12 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
134153
State: apiIssue.State,
135154
Comments: apiIssue.Comments,
136155
HTMLURL: pr.Issue.HTMLURL(),
156+
DiffURL: pr.Issue.DiffURL(),
157+
PatchURL: pr.Issue.PatchURL(),
137158
HasMerged: pr.HasMerged,
159+
Base: apiBaseBranchInfo,
160+
Head: apiHeadBranchInfo,
161+
MergeBase: pr.MergeBase,
138162
}
139163

140164
if pr.Status != PullRequestStatusChecking {
@@ -472,6 +496,46 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
472496
return nil
473497
}
474498

499+
// PullRequestsOptions holds the options for PRs
500+
type PullRequestsOptions struct {
501+
Page int
502+
State string
503+
SortType string
504+
Labels []string
505+
MilestoneID int64
506+
}
507+
508+
func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) *xorm.Session {
509+
sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
510+
511+
sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
512+
switch opts.State {
513+
case "closed", "open":
514+
sess.And("issue.is_closed=?", opts.State == "closed")
515+
}
516+
517+
return sess
518+
}
519+
520+
// PullRequests returns all pull requests for a base Repo by the given conditions
521+
func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
522+
if opts.Page <= 0 {
523+
opts.Page = 1
524+
}
525+
526+
countSession := listPullRequestStatement(baseRepoID, opts)
527+
maxResults, err := countSession.Count(new(PullRequest))
528+
if err != nil {
529+
log.Error(4, "Count PRs", err)
530+
return nil, maxResults, err
531+
}
532+
533+
prs := make([]*PullRequest, 0, ItemsPerPage)
534+
findSession := listPullRequestStatement(baseRepoID, opts)
535+
findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
536+
return prs, maxResults, findSession.Find(&prs)
537+
}
538+
475539
// GetUnmergedPullRequest returnss a pull request that is open and has not been merged
476540
// by given head/base and repo/branch.
477541
func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
@@ -512,6 +576,26 @@ func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequ
512576
Find(&prs)
513577
}
514578

579+
// GetPullRequestByIndex returns a pull request by the given index
580+
func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
581+
pr := &PullRequest{
582+
BaseRepoID: repoID,
583+
Index: index,
584+
}
585+
586+
has, err := x.Get(pr)
587+
if err != nil {
588+
return nil, err
589+
} else if !has {
590+
return nil, ErrPullRequestNotExist{0, repoID, index, 0, "", ""}
591+
}
592+
593+
pr.LoadAttributes()
594+
pr.LoadIssue()
595+
596+
return pr, nil
597+
}
598+
515599
func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
516600
pr := new(PullRequest)
517601
has, err := e.Id(id).Get(pr)

modules/context/api.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"fmt"
99
"strings"
1010

11+
"code.gitea.io/git"
1112
"code.gitea.io/gitea/models"
1213
"code.gitea.io/gitea/modules/base"
1314
"code.gitea.io/gitea/modules/log"
@@ -103,3 +104,24 @@ func ExtractOwnerAndRepo() macaron.Handler {
103104
ctx.Data["Repository"] = repo
104105
}
105106
}
107+
108+
// ReferencesGitRepo injects the GitRepo into the Context
109+
func ReferencesGitRepo() macaron.Handler {
110+
return func(ctx *APIContext) {
111+
// Empty repository does not have reference information.
112+
if ctx.Repo.Repository.IsBare {
113+
return
114+
}
115+
116+
// For API calls.
117+
if ctx.Repo.GitRepo == nil {
118+
repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
119+
gitRepo, err := git.OpenRepository(repoPath)
120+
if err != nil {
121+
ctx.Error(500, "RepoRef Invalid repo "+repoPath, err)
122+
return
123+
}
124+
ctx.Repo.GitRepo = gitRepo
125+
}
126+
}
127+
}

routers/api/v1/api.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,13 @@ func mustEnableIssues(ctx *context.APIContext) {
167167
}
168168
}
169169

170+
func mustAllowPulls(ctx *context.Context) {
171+
if !ctx.Repo.Repository.AllowsPulls() {
172+
ctx.Status(404)
173+
return
174+
}
175+
}
176+
170177
// RegisterRoutes registers all v1 APIs routes to web application.
171178
// FIXME: custom form error response
172179
func RegisterRoutes(m *macaron.Macaron) {
@@ -305,6 +312,14 @@ func RegisterRoutes(m *macaron.Macaron) {
305312
Delete(reqRepoWriter(), repo.DeleteMilestone)
306313
})
307314
m.Get("/editorconfig/:filename", context.RepoRef(), repo.GetEditorconfig)
315+
m.Group("/pulls", func() {
316+
m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).Post(reqRepoWriter(), bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
317+
m.Group("/:index", func() {
318+
m.Combo("").Get(repo.GetPullRequest).Patch(reqRepoWriter(), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
319+
m.Combo("/merge").Get(repo.IsPullRequestMerged).Post(reqRepoWriter(), repo.MergePullRequest)
320+
})
321+
322+
}, mustAllowPulls, context.ReferencesGitRepo())
308323
}, repoAssignment())
309324
}, reqToken())
310325

0 commit comments

Comments
 (0)