gitea源码

pull_review.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package repo
  4. import (
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. issues_model "code.gitea.io/gitea/models/issues"
  9. "code.gitea.io/gitea/models/organization"
  10. pull_model "code.gitea.io/gitea/models/pull"
  11. user_model "code.gitea.io/gitea/models/user"
  12. "code.gitea.io/gitea/modules/json"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/templates"
  16. "code.gitea.io/gitea/modules/web"
  17. "code.gitea.io/gitea/services/context"
  18. "code.gitea.io/gitea/services/context/upload"
  19. "code.gitea.io/gitea/services/forms"
  20. issue_service "code.gitea.io/gitea/services/issue"
  21. pull_service "code.gitea.io/gitea/services/pull"
  22. user_service "code.gitea.io/gitea/services/user"
  23. )
  24. const (
  25. tplDiffConversation templates.TplName = "repo/diff/conversation"
  26. tplConversationOutdated templates.TplName = "repo/diff/conversation_outdated"
  27. tplTimelineConversation templates.TplName = "repo/issue/view_content/conversation"
  28. tplNewComment templates.TplName = "repo/diff/new_comment"
  29. )
  30. // RenderNewCodeCommentForm will render the form for creating a new review comment
  31. func RenderNewCodeCommentForm(ctx *context.Context) {
  32. issue := GetActionIssue(ctx)
  33. if ctx.Written() {
  34. return
  35. }
  36. if !issue.IsPull {
  37. return
  38. }
  39. currentReview, err := issues_model.GetCurrentReview(ctx, ctx.Doer, issue)
  40. if err != nil && !issues_model.IsErrReviewNotExist(err) {
  41. ctx.ServerError("GetCurrentReview", err)
  42. return
  43. }
  44. ctx.Data["PageIsPullFiles"] = true
  45. ctx.Data["Issue"] = issue
  46. ctx.Data["CurrentReview"] = currentReview
  47. pullHeadCommitID, err := ctx.Repo.GitRepo.GetRefCommitID(issue.PullRequest.GetGitHeadRefName())
  48. if err != nil {
  49. ctx.ServerError("GetRefCommitID", err)
  50. return
  51. }
  52. ctx.Data["AfterCommitID"] = pullHeadCommitID
  53. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  54. upload.AddUploadContext(ctx, "comment")
  55. ctx.HTML(http.StatusOK, tplNewComment)
  56. }
  57. // CreateCodeComment will create a code comment including an pending review if required
  58. func CreateCodeComment(ctx *context.Context) {
  59. form := web.GetForm(ctx).(*forms.CodeCommentForm)
  60. issue := GetActionIssue(ctx)
  61. if ctx.Written() {
  62. return
  63. }
  64. if !issue.IsPull {
  65. return
  66. }
  67. if ctx.HasError() {
  68. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  69. ctx.Redirect(fmt.Sprintf("%s/pulls/%d/files", ctx.Repo.RepoLink, issue.Index))
  70. return
  71. }
  72. signedLine := form.Line
  73. if form.Side == "previous" {
  74. signedLine *= -1
  75. }
  76. var attachments []string
  77. if setting.Attachment.Enabled {
  78. attachments = form.Files
  79. }
  80. comment, err := pull_service.CreateCodeComment(ctx,
  81. ctx.Doer,
  82. ctx.Repo.GitRepo,
  83. issue,
  84. signedLine,
  85. form.Content,
  86. form.TreePath,
  87. !form.SingleReview,
  88. form.Reply,
  89. form.LatestCommitID,
  90. attachments,
  91. )
  92. if err != nil {
  93. ctx.ServerError("CreateCodeComment", err)
  94. return
  95. }
  96. if comment == nil {
  97. log.Trace("Comment not created: %-v #%d[%d]", ctx.Repo.Repository, issue.Index, issue.ID)
  98. ctx.Redirect(fmt.Sprintf("%s/pulls/%d/files", ctx.Repo.RepoLink, issue.Index))
  99. return
  100. }
  101. log.Trace("Comment created: %-v #%d[%d] Comment[%d]", ctx.Repo.Repository, issue.Index, issue.ID, comment.ID)
  102. renderConversation(ctx, comment, form.Origin)
  103. }
  104. // UpdateResolveConversation add or remove an Conversation resolved mark
  105. func UpdateResolveConversation(ctx *context.Context) {
  106. origin := ctx.FormString("origin")
  107. action := ctx.FormString("action")
  108. commentID := ctx.FormInt64("comment_id")
  109. comment, err := issues_model.GetCommentByID(ctx, commentID)
  110. if err != nil {
  111. ctx.ServerError("GetIssueByID", err)
  112. return
  113. }
  114. if err = comment.LoadIssue(ctx); err != nil {
  115. ctx.ServerError("comment.LoadIssue", err)
  116. return
  117. }
  118. if comment.Issue.RepoID != ctx.Repo.Repository.ID {
  119. ctx.NotFound(errors.New("comment's repoID is incorrect"))
  120. return
  121. }
  122. var permResult bool
  123. if permResult, err = issues_model.CanMarkConversation(ctx, comment.Issue, ctx.Doer); err != nil {
  124. ctx.ServerError("CanMarkConversation", err)
  125. return
  126. }
  127. if !permResult {
  128. ctx.HTTPError(http.StatusForbidden)
  129. return
  130. }
  131. if !comment.Issue.IsPull {
  132. ctx.HTTPError(http.StatusBadRequest)
  133. return
  134. }
  135. if action == "Resolve" || action == "UnResolve" {
  136. err = issues_model.MarkConversation(ctx, comment, ctx.Doer, action == "Resolve")
  137. if err != nil {
  138. ctx.ServerError("MarkConversation", err)
  139. return
  140. }
  141. } else {
  142. ctx.HTTPError(http.StatusBadRequest)
  143. return
  144. }
  145. renderConversation(ctx, comment, origin)
  146. }
  147. func renderConversation(ctx *context.Context, comment *issues_model.Comment, origin string) {
  148. ctx.Data["PageIsPullFiles"] = origin == "diff"
  149. showOutdatedComments := origin == "timeline" || ctx.Data["ShowOutdatedComments"].(bool)
  150. comments, err := issues_model.FetchCodeCommentsByLine(ctx, comment.Issue, ctx.Doer, comment.TreePath, comment.Line, showOutdatedComments)
  151. if err != nil {
  152. ctx.ServerError("FetchCodeCommentsByLine", err)
  153. return
  154. }
  155. if len(comments) == 0 {
  156. // if the comments are empty (deleted, outdated, etc), it's better to tell the users that it is outdated
  157. ctx.HTML(http.StatusOK, tplConversationOutdated)
  158. return
  159. }
  160. if err := comments.LoadAttachments(ctx); err != nil {
  161. ctx.ServerError("LoadAttachments", err)
  162. return
  163. }
  164. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  165. upload.AddUploadContext(ctx, "comment")
  166. ctx.Data["comments"] = comments
  167. if ctx.Data["CanMarkConversation"], err = issues_model.CanMarkConversation(ctx, comment.Issue, ctx.Doer); err != nil {
  168. ctx.ServerError("CanMarkConversation", err)
  169. return
  170. }
  171. ctx.Data["Issue"] = comment.Issue
  172. if err = comment.Issue.LoadPullRequest(ctx); err != nil {
  173. ctx.ServerError("comment.Issue.LoadPullRequest", err)
  174. return
  175. }
  176. pullHeadCommitID, err := ctx.Repo.GitRepo.GetRefCommitID(comment.Issue.PullRequest.GetGitHeadRefName())
  177. if err != nil {
  178. ctx.ServerError("GetRefCommitID", err)
  179. return
  180. }
  181. ctx.Data["AfterCommitID"] = pullHeadCommitID
  182. ctx.Data["CanBlockUser"] = func(blocker, blockee *user_model.User) bool {
  183. return user_service.CanBlockUser(ctx, ctx.Doer, blocker, blockee)
  184. }
  185. switch origin {
  186. case "diff":
  187. ctx.HTML(http.StatusOK, tplDiffConversation)
  188. case "timeline":
  189. ctx.HTML(http.StatusOK, tplTimelineConversation)
  190. default:
  191. ctx.HTTPError(http.StatusBadRequest, "Unknown origin: "+origin)
  192. }
  193. }
  194. // SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist
  195. func SubmitReview(ctx *context.Context) {
  196. form := web.GetForm(ctx).(*forms.SubmitReviewForm)
  197. issue := GetActionIssue(ctx)
  198. if ctx.Written() {
  199. return
  200. }
  201. if !issue.IsPull {
  202. return
  203. }
  204. if ctx.HasError() {
  205. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  206. ctx.JSONRedirect(fmt.Sprintf("%s/pulls/%d/files", ctx.Repo.RepoLink, issue.Index))
  207. return
  208. }
  209. reviewType := form.ReviewType()
  210. switch reviewType {
  211. case issues_model.ReviewTypeUnknown:
  212. ctx.ServerError("ReviewType", fmt.Errorf("unknown ReviewType: %s", form.Type))
  213. return
  214. // can not approve/reject your own PR
  215. case issues_model.ReviewTypeApprove, issues_model.ReviewTypeReject:
  216. if issue.IsPoster(ctx.Doer.ID) {
  217. var translated string
  218. if reviewType == issues_model.ReviewTypeApprove {
  219. translated = ctx.Locale.TrString("repo.issues.review.self.approval")
  220. } else {
  221. translated = ctx.Locale.TrString("repo.issues.review.self.rejection")
  222. }
  223. ctx.Flash.Error(translated)
  224. ctx.JSONRedirect(fmt.Sprintf("%s/pulls/%d/files", ctx.Repo.RepoLink, issue.Index))
  225. return
  226. }
  227. }
  228. var attachments []string
  229. if setting.Attachment.Enabled {
  230. attachments = form.Files
  231. }
  232. _, comm, err := pull_service.SubmitReview(ctx, ctx.Doer, ctx.Repo.GitRepo, issue, reviewType, form.Content, form.CommitID, attachments)
  233. if err != nil {
  234. if issues_model.IsContentEmptyErr(err) {
  235. ctx.Flash.Error(ctx.Tr("repo.issues.review.content.empty"))
  236. ctx.JSONRedirect(fmt.Sprintf("%s/pulls/%d/files", ctx.Repo.RepoLink, issue.Index))
  237. } else if errors.Is(err, pull_service.ErrSubmitReviewOnClosedPR) {
  238. ctx.Status(http.StatusUnprocessableEntity)
  239. } else {
  240. ctx.ServerError("SubmitReview", err)
  241. }
  242. return
  243. }
  244. ctx.JSONRedirect(fmt.Sprintf("%s/pulls/%d#%s", ctx.Repo.RepoLink, issue.Index, comm.HashTag()))
  245. }
  246. // DismissReview dismissing stale review by repo admin
  247. func DismissReview(ctx *context.Context) {
  248. form := web.GetForm(ctx).(*forms.DismissReviewForm)
  249. comm, err := pull_service.DismissReview(ctx, form.ReviewID, ctx.Repo.Repository.ID, form.Message, ctx.Doer, true, true)
  250. if err != nil {
  251. if pull_service.IsErrDismissRequestOnClosedPR(err) {
  252. ctx.Status(http.StatusForbidden)
  253. return
  254. }
  255. ctx.ServerError("pull_service.DismissReview", err)
  256. return
  257. }
  258. ctx.Redirect(fmt.Sprintf("%s/pulls/%d#%s", ctx.Repo.RepoLink, comm.Issue.Index, comm.HashTag()))
  259. }
  260. // viewedFilesUpdate Struct to parse the body of a request to update the reviewed files of a PR
  261. // If you want to implement an API to update the review, simply move this struct into modules.
  262. type viewedFilesUpdate struct {
  263. Files map[string]bool `json:"files"`
  264. HeadCommitSHA string `json:"headCommitSHA"`
  265. }
  266. func UpdateViewedFiles(ctx *context.Context) {
  267. // Find corresponding PR
  268. issue, ok := getPullInfo(ctx)
  269. if !ok {
  270. return
  271. }
  272. pull := issue.PullRequest
  273. var data *viewedFilesUpdate
  274. err := json.NewDecoder(ctx.Req.Body).Decode(&data)
  275. if err != nil {
  276. log.Warn("Attempted to update a review but could not parse request body: %v", err)
  277. ctx.Resp.WriteHeader(http.StatusBadRequest)
  278. return
  279. }
  280. // Expect the review to have been now if no head commit was supplied
  281. if data.HeadCommitSHA == "" {
  282. data.HeadCommitSHA = pull.HeadCommitID
  283. }
  284. updatedFiles := make(map[string]pull_model.ViewedState, len(data.Files))
  285. for file, viewed := range data.Files {
  286. // Only unviewed and viewed are possible, has-changed can not be set from the outside
  287. state := pull_model.Unviewed
  288. if viewed {
  289. state = pull_model.Viewed
  290. }
  291. updatedFiles[file] = state
  292. }
  293. if err := pull_model.UpdateReviewState(ctx, ctx.Doer.ID, pull.ID, data.HeadCommitSHA, updatedFiles); err != nil {
  294. ctx.ServerError("UpdateReview", err)
  295. }
  296. }
  297. // UpdatePullReviewRequest add or remove review request
  298. func UpdatePullReviewRequest(ctx *context.Context) {
  299. issues := getActionIssues(ctx)
  300. if ctx.Written() {
  301. return
  302. }
  303. reviewID := ctx.FormInt64("id")
  304. action := ctx.FormString("action")
  305. // TODO: Not support 'clear' now
  306. if action != "attach" && action != "detach" {
  307. ctx.Status(http.StatusForbidden)
  308. return
  309. }
  310. for _, issue := range issues {
  311. if err := issue.LoadRepo(ctx); err != nil {
  312. ctx.ServerError("issue.LoadRepo", err)
  313. return
  314. }
  315. if !issue.IsPull {
  316. log.Warn(
  317. "UpdatePullReviewRequest: refusing to add review request for non-PR issue %-v#%d",
  318. issue.Repo, issue.Index,
  319. )
  320. ctx.Status(http.StatusForbidden)
  321. return
  322. }
  323. if reviewID < 0 {
  324. // negative reviewIDs represent team requests
  325. if err := issue.Repo.LoadOwner(ctx); err != nil {
  326. ctx.ServerError("issue.Repo.LoadOwner", err)
  327. return
  328. }
  329. if !issue.Repo.Owner.IsOrganization() {
  330. log.Warn(
  331. "UpdatePullReviewRequest: refusing to add team review request for %s#%d owned by non organization UID[%d]",
  332. issue.Repo.FullName(), issue.Index, issue.Repo.ID,
  333. )
  334. ctx.Status(http.StatusForbidden)
  335. return
  336. }
  337. team, err := organization.GetTeamByID(ctx, -reviewID)
  338. if err != nil {
  339. ctx.ServerError("GetTeamByID", err)
  340. return
  341. }
  342. if team.OrgID != issue.Repo.OwnerID {
  343. log.Warn(
  344. "UpdatePullReviewRequest: refusing to add team review request for UID[%d] team %s to %s#%d owned by UID[%d]",
  345. team.OrgID, team.Name, issue.Repo.FullName(), issue.Index, issue.Repo.ID)
  346. ctx.Status(http.StatusForbidden)
  347. return
  348. }
  349. _, err = issue_service.TeamReviewRequest(ctx, issue, ctx.Doer, team, action == "attach")
  350. if err != nil {
  351. if issues_model.IsErrNotValidReviewRequest(err) {
  352. log.Warn(
  353. "UpdatePullReviewRequest: refusing to add invalid team review request for UID[%d] team %s to %s#%d owned by UID[%d]: Error: %v",
  354. team.OrgID, team.Name, issue.Repo.FullName(), issue.Index, issue.Repo.ID,
  355. err,
  356. )
  357. ctx.Status(http.StatusForbidden)
  358. return
  359. }
  360. ctx.ServerError("TeamReviewRequest", err)
  361. return
  362. }
  363. continue
  364. }
  365. reviewer, err := user_model.GetUserByID(ctx, reviewID)
  366. if err != nil {
  367. if user_model.IsErrUserNotExist(err) {
  368. log.Warn(
  369. "UpdatePullReviewRequest: requested reviewer [%d] for %-v to %-v#%d is not exist: Error: %v",
  370. reviewID, issue.Repo, issue.Index,
  371. err,
  372. )
  373. ctx.Status(http.StatusForbidden)
  374. return
  375. }
  376. ctx.ServerError("GetUserByID", err)
  377. return
  378. }
  379. _, err = issue_service.ReviewRequest(ctx, issue, ctx.Doer, &ctx.Repo.Permission, reviewer, action == "attach")
  380. if err != nil {
  381. if issues_model.IsErrNotValidReviewRequest(err) {
  382. log.Warn(
  383. "UpdatePullReviewRequest: refusing to add invalid review request for %-v to %-v#%d: Error: %v",
  384. reviewer, issue.Repo, issue.Index,
  385. err,
  386. )
  387. ctx.Status(http.StatusForbidden)
  388. return
  389. }
  390. if issues_model.IsErrReviewRequestOnClosedPR(err) {
  391. ctx.Status(http.StatusForbidden)
  392. return
  393. }
  394. ctx.ServerError("ReviewRequest", err)
  395. return
  396. }
  397. }
  398. ctx.JSONOK()
  399. }