forgejo/routers/api/v1/repo/pull_review.go
fxgsell b5ffd266b1
Some checks failed
/ build (push) Has been skipped
/ e2e (push) Has been skipped
/ release (push) Has been skipped
testing-integration / test-unit (push) Has been skipped
testing-integration / test-sqlite (push) Has been skipped
testing-integration / test-mariadb (v10.6) (push) Has been skipped
testing-integration / test-mariadb (v11.8) (push) Has been skipped
testing / backend-checks (push) Has been cancelled
testing / frontend-checks (push) Has been cancelled
testing / test-unit (push) Has been cancelled
testing / test-e2e (push) Has been cancelled
testing / test-remote-cacher (redis) (push) Has been cancelled
testing / test-remote-cacher (valkey) (push) Has been cancelled
testing / test-remote-cacher (garnet) (push) Has been cancelled
testing / test-mysql (push) Has been cancelled
testing / test-pgsql (push) Has been cancelled
testing / test-sqlite (push) Has been cancelled
testing / coverage (push) Has been cancelled
testing / security-check (push) Has been cancelled
testing / semgrep/ci (push) Has been cancelled
feat(api): resolve and unresolve pull request review conversations (#14873)
Closes #12237.

The problem: CLI tools can leave a comment on a PR via the API, but they can't mark a thread as resolved. This adds it.

**Resolve / unresolve a thread**

POST /repos/{owner}/{repo}/pulls/comments/{id}/resolve
POST /repos/{owner}/{repo}/pulls/comments/{id}/unresolve

`{id}` can be any comment in the thread, root or reply. Behavior:

- 403 if you don't have `CanMarkConversation` permission or you're on a read-only token
- 404 for an unknown comment, or one from another repo
- 422 if the comment isn't a code review comment

**Small fix along the way**

`GET .../reviews/{id}/comments/{comment}` always returned `resolver: null` because that path never loaded the resolver. Fixed to load it like the list endpoint does.

**Testing**

Added `TestAPIPullReviewResolveConversation` in `tests/integration/api_pull_review_test.go`. `make pr-go` passes.

## Checklist

The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. All work and communication must conform to Forgejo's [AI Agreement](https://codeberg.org/forgejo/governance/src/branch/main/AIAgreement.md). There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org).

### Compliance

- [x] I confirm that I make this contribution in accordance with [Forgejo's AI Agreement](9084720dc6/AIAgreement.md).

### Tests for Go changes

(can be removed for JavaScript changes)

- I added test coverage for Go changes...
  - [ ] in their respective `*_test.go` for unit tests.
  - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server.
- I ran...
  - [X] `make pr-go` before pushing

### Documentation

- [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
- [X] I did not document these changes and I do not expect someone else to do it.

### Release notes

- [X] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change.
- [ ] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.

*The decision if the pull request will be shown in the release notes is up to the mergers / release team.*

The content of the `release-notes/<pull request number>.md` file will serve as the basis for the release notes. If the file does not exist, the title of the pull request will be used instead.

<!--start release-notes-assistant-->

## Release notes
<!--URL:https://codeberg.org/forgejo/forgejo-->
- Features
  - [PR](#14873): <!--number 14873 --><!--line 0 --><!--description ZmVhdChhcGkpOiByZXNvbHZlIGFuZCB1bnJlc29sdmUgcHVsbCByZXF1ZXN0IHJldmlldyBjb252ZXJzYXRpb25z-->feat(api): resolve and unresolve pull request review conversations<!--description-->
<!--end release-notes-assistant-->

Co-authored-by: François-Xavier Gsell <[email protected]>
Reviewed-on: #14873
Reviewed-by: Andreas Ahlenstorf <[email protected]>
2026-10-31 10:30:41 +01:00

1380 lines
37 KiB
Go

// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package repo
import (
"errors"
"fmt"
"net/http"
"strings"
issues_model "forgejo.org/models/issues"
"forgejo.org/models/organization"
"forgejo.org/models/perm"
user_model "forgejo.org/models/user"
"forgejo.org/modules/gitrepo"
api "forgejo.org/modules/structs"
"forgejo.org/modules/util"
"forgejo.org/modules/web"
"forgejo.org/routers/api/v1/utils"
"forgejo.org/services/context"
"forgejo.org/services/convert"
issue_service "forgejo.org/services/issue"
pull_service "forgejo.org/services/pull"
)
// ListPullReviews lists all reviews of a pull request
func ListPullReviews(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/reviews repository repoListPullReviews
// ---
// summary: List all reviews for a pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: page
// in: query
// description: page number of results to return (1-based)
// type: integer
// - name: limit
// in: query
// description: page size of results
// type: integer
// responses:
// "200":
// "$ref": "#/responses/PullReviewList"
// "404":
// "$ref": "#/responses/notFound"
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo().Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
} else {
ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
}
return
}
if err = pr.LoadIssue(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
return
}
if err = pr.Issue.LoadRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadRepo", err)
return
}
opts := issues_model.FindReviewOptions{
ListOptions: utils.GetListOptions(ctx),
IssueID: pr.IssueID,
}
allReviews, err := issues_model.FindReviews(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return
}
count, err := issues_model.CountReviews(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return
}
apiReviews, err := convert.ToPullReviewList(ctx, allReviews, ctx.Doer())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convertToPullReviewList", err)
return
}
ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, &apiReviews)
}
// GetPullReview gets a specific review of a pull request
func GetPullReview(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/reviews/{id} repository repoGetPullReview
// ---
// summary: Get a specific review for a pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// responses:
// "200":
// "$ref": "#/responses/PullReview"
// "404":
// "$ref": "#/responses/notFound"
review, _, statusSet := prepareSingleReview(ctx)
if statusSet {
return
}
apiReview, err := convert.ToPullReview(ctx, review, ctx.Doer())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convertToPullReview", err)
return
}
ctx.JSON(http.StatusOK, apiReview)
}
// GetPullReviewComments lists all comments of a pull request review
func GetPullReviewComments(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/reviews/{id}/comments repository repoGetPullReviewComments
// ---
// summary: Get a specific review for a pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// responses:
// "200":
// "$ref": "#/responses/PullReviewCommentList"
// "404":
// "$ref": "#/responses/notFound"
review, _, statusSet := prepareSingleReview(ctx)
if statusSet {
return
}
apiComments, err := convert.ToPullReviewCommentList(ctx, review, ctx.Doer())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convertToPullReviewCommentList", err)
return
}
ctx.JSON(http.StatusOK, apiComments)
}
// GetPullReviewComment get a pull review comment
func GetPullReviewComment(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/reviews/{id}/comments/{comment} repository repoGetPullReviewComment
// ---
// summary: Get a pull review comment
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// - name: comment
// in: path
// description: id of the comment
// type: integer
// format: int64
// required: true
// responses:
// "200":
// "$ref": "#/responses/PullReviewComment"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
review, _, statusSet := prepareSingleReview(ctx)
if statusSet {
return
}
comment := ctx.LoadComment("comment")
if ctx.Written() {
return
}
if err := comment.LoadPoster(ctx); err != nil {
ctx.InternalServerError(err)
return
}
if err := (issues_model.CommentList{comment}).LoadResolveDoers(ctx); err != nil {
ctx.InternalServerError(err)
return
}
apiComment, err := convert.ToPullReviewComment(ctx, review, comment, ctx.Doer())
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusOK, apiComment)
}
// CreatePullReviewComments add a new comment to a pull request review
func CreatePullReviewComment(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/reviews/{id}/comments repository repoCreatePullReviewComment
// ---
// summary: Add a new comment to a pull request review
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/CreatePullReviewCommentOptions"
// responses:
// "200":
// "$ref": "#/responses/PullReviewComment"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/validationError"
opts := web.GetForm(ctx).(*api.CreatePullReviewCommentOptions)
review, pr, statusSet := prepareSingleReview(ctx)
if statusSet {
return
}
if err := pr.Issue.LoadRepo(ctx); err != nil {
ctx.InternalServerError(err)
return
}
line := opts.NewLineNum
if opts.OldLineNum > 0 {
line = opts.OldLineNum * -1
}
if err := pull_service.ValidateCodeCommentLineRange(opts.ExtraLinesCount); err != nil {
ctx.Error(http.StatusUnprocessableEntity, "invalid extra_lines_count", err)
return
}
if err := pull_service.ValidateCodeCommentSuggestions(opts.Body); err != nil {
ctx.Error(http.StatusUnprocessableEntity, "invalid suggestion", err)
return
}
comment, err := pull_service.CreateCodeCommentKnownReviewID(ctx,
ctx.Doer(),
pr.Issue.Repo,
pr.Issue,
opts.Body,
opts.Path,
pr.MergeBase,
review.CommitID,
line,
opts.ExtraLinesCount,
review.ID,
nil,
)
if err != nil {
ctx.InternalServerError(err)
return
}
apiComment, err := convert.ToPullReviewComment(ctx, review, comment, ctx.Doer())
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusOK, apiComment)
}
// CreatePullReviewCommentReply adds a reply to a pull request review comment
func CreatePullReviewCommentReply(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/comments/{id}/replies repository repoCreatePullReviewCommentReply
// ---
// summary: Reply to a pull review comment
// produces:
// - application/json
// parameters:
// - name: owner
// in: path
// description: owner of the repository
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repository
// type: string
// required: true
// - name: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: ID of the review comment
// type: integer
// format: int64
// required: true
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/CreatePullReviewCommentReplyOptions"
// responses:
// "201":
// "$ref": "#/responses/PullReviewComment"
// "400":
// "$ref": "#/responses/error"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/validationError"
opts := web.GetForm(ctx).(*api.CreatePullReviewCommentReplyOptions)
parent := ctx.LoadComment("id")
if ctx.Written() {
return
}
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo().Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
} else {
ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
}
return
}
if parent.IssueID != pr.IssueID {
ctx.NotFound("CommentNotInPR")
return
}
if parent.Type != issues_model.CommentTypeCode || parent.ReviewID == 0 {
ctx.Error(http.StatusBadRequest, "CreatePullReviewCommentReply", errors.New("comment is not a pull review comment"))
return
}
review, err := issues_model.GetReviewByID(ctx, parent.ReviewID)
if err != nil {
if issues_model.IsErrReviewNotExist(err) {
ctx.NotFound("GetReviewByID", err)
} else {
ctx.Error(http.StatusInternalServerError, "GetReviewByID", err)
}
return
}
if !review.AcceptsCommentsFrom(ctx.Doer()) {
ctx.NotFound("GetReviewByID")
return
}
review.Issue = parent.Issue
comment, err := pull_service.CreateCodeComment(ctx,
ctx.Doer(),
ctx.Repo().GitRepo,
parent.Issue,
parent.Line,
parent.ExtraLinesCount,
opts.Body,
parent.TreePath,
false,
parent.ReviewID,
pr.MergeBase,
review.CommitID,
nil,
)
if err != nil {
ctx.InternalServerError(err)
return
}
if err := comment.LoadPoster(ctx); err != nil {
ctx.InternalServerError(err)
return
}
apiComment, err := convert.ToPullReviewComment(ctx, review, comment, ctx.Doer())
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusCreated, apiComment)
}
// DeletePullReview delete a specific review from a pull request
func DeletePullReview(ctx *context.APIContext) {
// swagger:operation DELETE /repos/{owner}/{repo}/pulls/{index}/reviews/{id} repository repoDeletePullReview
// ---
// summary: Delete a specific review from a pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// responses:
// "204":
// "$ref": "#/responses/empty"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
review, _, statusSet := prepareSingleReview(ctx)
if statusSet {
return
}
if ctx.Doer() == nil {
ctx.NotFound()
return
}
if !ctx.IsUserSiteAdmin() && ctx.Doer().ID != review.ReviewerID {
ctx.Error(http.StatusForbidden, "only admin and user itself can delete a review", nil)
return
}
if err := issues_model.DeleteReview(ctx, review); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteReview", fmt.Errorf("can not delete ReviewID: %d", review.ID))
return
}
ctx.Status(http.StatusNoContent)
}
// CreatePullReview create a review to a pull request
func CreatePullReview(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/reviews repository repoCreatePullReview
// ---
// summary: Create a review to an pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/CreatePullReviewOptions"
// responses:
// "200":
// "$ref": "#/responses/PullReview"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/validationError"
opts := web.GetForm(ctx).(*api.CreatePullReviewOptions)
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo().Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
} else {
ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
}
return
}
// determine review type
reviewType, isWrong := preparePullReviewType(ctx, pr, opts.Event, opts.Body, len(opts.Comments) > 0)
if isWrong {
return
}
if err := pr.Issue.LoadRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "pr.Issue.LoadRepo", err)
return
}
// if CommitID is empty, set it as lastCommitID
if opts.CommitID == "" {
gitRepo, closer, err := gitrepo.RepositoryFromContextOrOpen(ctx, pr.Issue.Repo)
if err != nil {
ctx.Error(http.StatusInternalServerError, "git.OpenRepository", err)
return
}
defer closer.Close()
headCommitID, err := gitRepo.GetRefCommitID(pr.GetGitRefName())
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetRefCommitID", err)
return
}
opts.CommitID = headCommitID
}
// create review comments
for _, c := range opts.Comments {
if err := pull_service.ValidateCodeCommentLineRange(c.ExtraLinesCount); err != nil {
ctx.Error(http.StatusUnprocessableEntity, "invalid extra_lines_count", err)
return
}
if err := pull_service.ValidateCodeCommentSuggestions(c.Body); err != nil {
ctx.Error(http.StatusUnprocessableEntity, "invalid suggestion", err)
return
}
line := c.NewLineNum
if c.OldLineNum > 0 {
line = c.OldLineNum * -1
}
if _, err := pull_service.CreateCodeComment(ctx,
ctx.Doer(),
ctx.Repo().GitRepo,
pr.Issue,
line,
c.ExtraLinesCount,
c.Body,
c.Path,
true, // pending review
0, // no reply
pr.MergeBase,
opts.CommitID,
nil,
); err != nil {
ctx.Error(http.StatusInternalServerError, "CreateCodeComment", err)
return
}
}
// create review and associate all pending review comments
review, _, err := pull_service.SubmitReview(ctx, ctx.Doer(), ctx.Repo().GitRepo, pr.Issue, reviewType, opts.Body, opts.CommitID, nil)
if err != nil {
ctx.Error(http.StatusInternalServerError, "SubmitReview", err)
return
}
// convert response
apiReview, err := convert.ToPullReview(ctx, review, ctx.Doer())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convertToPullReview", err)
return
}
ctx.JSON(http.StatusOK, apiReview)
}
// SubmitPullReview submit a pending review to an pull request
func SubmitPullReview(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/reviews/{id} repository repoSubmitPullReview
// ---
// summary: Submit a pending review to an pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/SubmitPullReviewOptions"
// responses:
// "200":
// "$ref": "#/responses/PullReview"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/validationError"
opts := web.GetForm(ctx).(*api.SubmitPullReviewOptions)
review, pr, isWrong := prepareSingleReview(ctx)
if isWrong {
return
}
if review.Type != issues_model.ReviewTypePending {
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("only a pending review can be submitted"))
return
}
// determine review type
reviewType, isWrong := preparePullReviewType(ctx, pr, opts.Event, opts.Body, len(review.Comments) > 0)
if isWrong {
return
}
// if review stay pending return
if reviewType == issues_model.ReviewTypePending {
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("review stay pending"))
return
}
headCommitID, err := ctx.Repo().GitRepo.GetRefCommitID(pr.GetGitRefName())
if err != nil {
ctx.Error(http.StatusInternalServerError, "GitRepo: GetRefCommitID", err)
return
}
// create review and associate all pending review comments
review, _, err = pull_service.SubmitReview(ctx, ctx.Doer(), ctx.Repo().GitRepo, pr.Issue, reviewType, opts.Body, headCommitID, nil)
if err != nil {
ctx.Error(http.StatusInternalServerError, "SubmitReview", err)
return
}
// convert response
apiReview, err := convert.ToPullReview(ctx, review, ctx.Doer())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convertToPullReview", err)
return
}
ctx.JSON(http.StatusOK, apiReview)
}
// preparePullReviewType return ReviewType and false or nil and true if an error happen
func preparePullReviewType(ctx *context.APIContext, pr *issues_model.PullRequest, event api.ReviewStateType, body string, hasComments bool) (issues_model.ReviewType, bool) {
if err := pr.LoadIssue(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
return -1, true
}
needsBody := true
hasBody := len(strings.TrimSpace(body)) > 0
var reviewType issues_model.ReviewType
switch event {
case api.ReviewStateApproved:
// can not approve your own PR
if pr.Issue.IsPoster(ctx.Doer().ID) {
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("approve your own pull is not allowed"))
return -1, true
}
reviewType = issues_model.ReviewTypeApprove
needsBody = false
case api.ReviewStateRequestChanges:
// can not reject your own PR
if pr.Issue.IsPoster(ctx.Doer().ID) {
ctx.Error(http.StatusUnprocessableEntity, "", errors.New("reject your own pull is not allowed"))
return -1, true
}
reviewType = issues_model.ReviewTypeReject
case api.ReviewStateComment:
reviewType = issues_model.ReviewTypeComment
needsBody = false
// if there is no body we need to ensure that there are comments
if !hasBody && !hasComments {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("review event %s requires a body or a comment", event))
return -1, true
}
default:
reviewType = issues_model.ReviewTypePending
}
// reject reviews with empty body if a body is required for this call
if needsBody && !hasBody {
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("review event %s requires a body", event))
return -1, true
}
return reviewType, false
}
// prepareSingleReview return review, related pull and false or nil, nil and true if an error happen
func prepareSingleReview(ctx *context.APIContext) (*issues_model.Review, *issues_model.PullRequest, bool) {
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo().Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
} else {
ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
}
return nil, nil, true
}
review, err := issues_model.GetReviewByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if issues_model.IsErrReviewNotExist(err) {
ctx.NotFound("GetReviewByID", err)
} else {
ctx.Error(http.StatusInternalServerError, "GetReviewByID", err)
}
return nil, nil, true
}
// validate the review is for the given PR
if review.IssueID != pr.IssueID {
ctx.NotFound("ReviewNotInPR")
return nil, nil, true
}
// make sure that the user has access to this review if it is pending
if review.Type == issues_model.ReviewTypePending && review.ReviewerID != ctx.Doer().ID && !ctx.IsUserSiteAdmin() {
ctx.NotFound("GetReviewByID")
return nil, nil, true
}
if err := review.LoadAttributes(ctx); err != nil && !user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusInternalServerError, "ReviewLoadAttributes", err)
return nil, nil, true
}
return review, pr, false
}
// CreateReviewRequests create review requests to an pull request
func CreateReviewRequests(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/requested_reviewers repository repoCreatePullReviewRequests
// ---
// summary: Create review requests for a pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/PullReviewRequestOptions"
// responses:
// "201":
// "$ref": "#/responses/PullReviewListWithoutPagination"
// "422":
// "$ref": "#/responses/validationError"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
opts := web.GetForm(ctx).(*api.PullReviewRequestOptions)
apiReviewRequest(ctx, *opts, true)
}
// DeleteReviewRequests delete review requests to an pull request
func DeleteReviewRequests(ctx *context.APIContext) {
// swagger:operation DELETE /repos/{owner}/{repo}/pulls/{index}/requested_reviewers repository repoDeletePullReviewRequests
// ---
// summary: Cancel review requests for a pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/PullReviewRequestOptions"
// responses:
// "204":
// "$ref": "#/responses/empty"
// "422":
// "$ref": "#/responses/validationError"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
opts := web.GetForm(ctx).(*api.PullReviewRequestOptions)
apiReviewRequest(ctx, *opts, false)
}
func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions, isAdd bool) {
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo().Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
} else {
ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
}
return
}
if err := pr.Issue.LoadRepo(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "pr.Issue.LoadRepo", err)
return
}
reviewers := make([]*user_model.User, 0, len(opts.Reviewers))
// Ability to add review requests is relatively complex logic that will be in `CanDoerChangeReviewRequests`. But on
// the API side, it's possible that an auth reducer may want to interfere with this logic -- so we'll run a write
// AccessMode through the reducer and if we don't get write back, then the reducer is preventing us from adding this
// review request. (eg. a repo-scoped access token, when accessing a public repo, can't write review requests)
reducerAccessMode, err := ctx.Reducer().ReduceRepoAccess(ctx, ctx.Repo().Repository, perm.AccessModeWrite)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ReduceRepoAccess", err)
return
} else if reducerAccessMode != perm.AccessModeWrite {
// Forbidden (rather than NotFound) is used for this perm check because the middleware on the APIs already
// guarantees we have read access to this repo, so this doesn't leak any existence information.
ctx.Error(http.StatusForbidden, "apiReviewRequest", "permission reduction prevented review request change")
return
}
for _, r := range opts.Reviewers {
var reviewer *user_model.User
if strings.Contains(r, "@") {
reviewer, err = user_model.GetUserByEmail(ctx, r)
} else {
reviewer, err = user_model.GetUserByName(ctx, r)
}
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.NotFound("UserNotExist", fmt.Sprintf("User '%s' not exist", r))
return
}
ctx.Error(http.StatusInternalServerError, "GetUser", err)
return
}
err = issue_service.IsValidReviewRequest(ctx, reviewer, ctx.Doer(), isAdd, pr.Issue)
if err != nil {
if issues_model.IsErrNotValidReviewRequest(err) {
ctx.Error(http.StatusUnprocessableEntity, "NotValidReviewRequest", err)
return
}
ctx.Error(http.StatusInternalServerError, "IsValidReviewRequest", err)
return
}
reviewers = append(reviewers, reviewer)
}
var reviews []*issues_model.Review
if isAdd {
reviews = make([]*issues_model.Review, 0, len(reviewers))
}
for _, reviewer := range reviewers {
comment, err := issue_service.ReviewRequest(ctx, pr.Issue, ctx.Doer(), reviewer, isAdd)
if err != nil {
if issues_model.IsErrReviewRequestOnClosedPR(err) {
ctx.Error(http.StatusForbidden, "", err)
return
}
ctx.Error(http.StatusInternalServerError, "ReviewRequest", err)
return
}
if comment != nil && isAdd {
if err = comment.LoadReview(ctx); err != nil {
ctx.ServerError("ReviewRequest", err)
return
}
reviews = append(reviews, comment.Review)
}
}
if ctx.Repo().Repository.Owner.IsOrganization() && len(opts.TeamReviewers) > 0 {
teamReviewers := make([]*organization.Team, 0, len(opts.TeamReviewers))
for _, t := range opts.TeamReviewers {
var teamReviewer *organization.Team
teamReviewer, err = organization.GetTeam(ctx, ctx.Repo().Owner.ID, t)
if err != nil {
if organization.IsErrTeamNotExist(err) {
ctx.NotFound("TeamNotExist", fmt.Sprintf("Team '%s' not exist", t))
return
}
ctx.Error(http.StatusInternalServerError, "ReviewRequest", err)
return
}
err = issue_service.IsValidTeamReviewRequest(ctx, teamReviewer, ctx.Doer(), isAdd, pr.Issue)
if err != nil {
if issues_model.IsErrNotValidReviewRequest(err) {
ctx.Error(http.StatusUnprocessableEntity, "NotValidReviewRequest", err)
return
}
ctx.Error(http.StatusInternalServerError, "IsValidTeamReviewRequest", err)
return
}
teamReviewers = append(teamReviewers, teamReviewer)
}
for _, teamReviewer := range teamReviewers {
comment, err := issue_service.TeamReviewRequest(ctx, pr.Issue, ctx.Doer(), teamReviewer, isAdd)
if err != nil {
ctx.ServerError("TeamReviewRequest", err)
return
}
if comment != nil && isAdd {
if err = comment.LoadReview(ctx); err != nil {
ctx.ServerError("ReviewRequest", err)
return
}
reviews = append(reviews, comment.Review)
}
}
}
if isAdd {
apiReviews, err := convert.ToPullReviewList(ctx, reviews, ctx.Doer())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convertToPullReviewList", err)
return
}
ctx.JSON(http.StatusCreated, apiReviews)
} else {
ctx.Status(http.StatusNoContent)
return
}
}
// DismissPullReview dismiss a review for a pull request
func DismissPullReview(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/reviews/{id}/dismissals repository repoDismissPullReview
// ---
// summary: Dismiss a review for a pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/DismissPullReviewOptions"
// responses:
// "200":
// "$ref": "#/responses/PullReview"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/validationError"
opts := web.GetForm(ctx).(*api.DismissPullReviewOptions)
dismissReview(ctx, opts.Message, true, opts.Priors)
}
// UnDismissPullReview cancel to dismiss a review for a pull request
func UnDismissPullReview(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/reviews/{id}/undismissals repository repoUnDismissPullReview
// ---
// summary: Cancel to dismiss a review for a pull request
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// responses:
// "200":
// "$ref": "#/responses/PullReview"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/validationError"
dismissReview(ctx, "", false, false)
}
// DeletePullReviewComment delete a pull review comment
func DeletePullReviewComment(ctx *context.APIContext) {
// swagger:operation DELETE /repos/{owner}/{repo}/pulls/{index}/reviews/{id}/comments/{comment} repository repoDeletePullReviewComment
// ---
// summary: Delete a pull review comment
// 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: index
// in: path
// description: index of the pull request
// type: integer
// format: int64
// required: true
// - name: id
// in: path
// description: id of the review
// type: integer
// format: int64
// required: true
// - name: comment
// in: path
// description: id of the comment
// type: integer
// format: int64
// required: true
// responses:
// "204":
// "$ref": "#/responses/empty"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
deleteIssueComment(ctx, "comment", issues_model.CommentTypeCode)
}
func dismissReview(ctx *context.APIContext, msg string, isDismiss, dismissPriors bool) {
if !ctx.IsUserRepoAdmin() {
ctx.Error(http.StatusForbidden, "", "Must be repo admin")
return
}
review, _, isWrong := prepareSingleReview(ctx)
if isWrong {
return
}
if review.Type != issues_model.ReviewTypeApprove && review.Type != issues_model.ReviewTypeReject {
ctx.Error(http.StatusForbidden, "", "not need to dismiss this review because it's type is not Approve or change request")
return
}
_, err := pull_service.DismissReview(ctx, review.ID, ctx.Repo().Repository.ID, msg, ctx.Doer(), isDismiss, dismissPriors)
if err != nil {
if pull_service.IsErrDismissRequestOnClosedPR(err) {
ctx.Error(http.StatusForbidden, "", err)
return
}
ctx.Error(http.StatusInternalServerError, "pull_service.DismissReview", err)
return
}
if review, err = issues_model.GetReviewByID(ctx, review.ID); err != nil {
ctx.Error(http.StatusInternalServerError, "GetReviewByID", err)
return
}
// convert response
apiReview, err := convert.ToPullReview(ctx, review, ctx.Doer())
if err != nil {
ctx.Error(http.StatusInternalServerError, "convertToPullReview", err)
return
}
ctx.JSON(http.StatusOK, apiReview)
}
// ResolvePullReviewConversation marks the review conversation of a pull review comment as resolved
func ResolvePullReviewConversation(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/comments/{id}/resolve repository repoResolvePullReviewConversation
// ---
// summary: Resolve the review conversation a pull review comment belongs to
// produces:
// - application/json
// parameters:
// - name: owner
// in: path
// description: owner of the repository
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repository
// type: string
// required: true
// - name: id
// in: path
// description: ID of any comment in the conversation
// type: integer
// format: int64
// required: true
// responses:
// "200":
// "$ref": "#/responses/PullReviewComment"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/validationError"
markPullReviewConversation(ctx, true)
}
// UnresolvePullReviewConversation marks the review conversation of a pull review comment as unresolved
func UnresolvePullReviewConversation(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/pulls/comments/{id}/unresolve repository repoUnresolvePullReviewConversation
// ---
// summary: Unresolve the review conversation a pull review comment belongs to
// produces:
// - application/json
// parameters:
// - name: owner
// in: path
// description: owner of the repository
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repository
// type: string
// required: true
// - name: id
// in: path
// description: ID of any comment in the conversation
// type: integer
// format: int64
// required: true
// responses:
// "200":
// "$ref": "#/responses/PullReviewComment"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/validationError"
markPullReviewConversation(ctx, false)
}
func markPullReviewConversation(ctx *context.APIContext, isResolve bool) {
comment := ctx.LoadComment(":id")
if ctx.Written() {
return
}
root, err := pull_service.MarkConversation(ctx, comment, ctx.Doer(), isResolve)
switch {
case errors.Is(err, util.ErrNotExist):
ctx.NotFound()
return
case errors.Is(err, util.ErrInvalidArgument):
ctx.Error(http.StatusUnprocessableEntity, "", err)
return
case errors.Is(err, util.ErrPermissionDenied):
ctx.Error(http.StatusForbidden, "", err)
return
case err != nil:
ctx.InternalServerError(err)
return
}
root.Review.Issue = comment.Issue
apiComment, err := convert.ToPullReviewComment(ctx, root.Review, root, ctx.Doer())
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusOK, apiComment)
}