Implement state filter for get PR by base head

Add the `isClosed` flag to the function and filter the pull requests accordingly. Filter on the issue state as the indicator if a PR is closed or not. The default behaves like the previous implementation, returning the first one regardless of issue state
This commit is contained in:
Sven Steinbauer 2025-02-19 21:54:32 +00:00
parent b2e7a71159
commit 16955b770e
2 changed files with 23 additions and 2 deletions

View file

@ -20,6 +20,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/optional"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
@ -691,11 +692,15 @@ func GetPullRequestByIssueID(ctx context.Context, issueID int64) (*PullRequest,
}
// GetPullRequestByBaseHeadInfo returns the pull request by given base and head
func GetPullRequestByBaseHeadInfo(ctx context.Context, baseID, headID int64, base, head string) (*PullRequest, error) {
func GetPullRequestByBaseHeadInfo(ctx context.Context, baseID, headID int64, base, head string, isClosed optional.Option[bool]) (*PullRequest, error) {
pr := &PullRequest{}
sess := db.GetEngine(ctx).
Join("INNER", "issue", "issue.id = pull_request.issue_id").
Where("base_repo_id = ? AND base_branch = ? AND head_repo_id = ? AND head_branch = ?", baseID, base, headID, head)
if isClosed.Has() {
sess = sess.And("issue.is_closed = ?", isClosed.Value())
}
has, err := sess.Get(pr)
if err != nil {
return nil, err

View file

@ -25,6 +25,7 @@ import (
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/optional"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/timeutil"
@ -261,6 +262,11 @@ func GetPullRequestByBaseHead(ctx *context.APIContext) {
// description: head of the pull request to get
// type: string
// required: true
// - name: state
// in: query
// description: state of pull request to get
// type: string
// enum: [closed, open, all]
// responses:
// "200":
// "$ref": "#/responses/PullRequest"
@ -297,7 +303,17 @@ func GetPullRequestByBaseHead(ctx *context.APIContext) {
headBranch = head
}
pr, err := issues_model.GetPullRequestByBaseHeadInfo(ctx, ctx.Repo.Repository.ID, headRepoID, ctx.Params(":base"), headBranch)
var isClosed optional.Option[bool]
switch ctx.FormString("state") {
case "closed":
isClosed = optional.Some(true)
case "open":
isClosed = optional.Some(false)
default:
isClosed = optional.None[bool]()
}
pr, err := issues_model.GetPullRequestByBaseHeadInfo(ctx, ctx.Repo.Repository.ID, headRepoID, ctx.Params(":base"), headBranch, isClosed)
if err != nil {
if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound()