You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

review.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // Copyright 2019 The Gitea Authors.
  2. // All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package pull
  5. import (
  6. "context"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "regexp"
  11. "strings"
  12. "code.gitea.io/gitea/models/db"
  13. issues_model "code.gitea.io/gitea/models/issues"
  14. repo_model "code.gitea.io/gitea/models/repo"
  15. user_model "code.gitea.io/gitea/models/user"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/gitrepo"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/optional"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/util"
  22. notify_service "code.gitea.io/gitea/services/notify"
  23. )
  24. var notEnoughLines = regexp.MustCompile(`fatal: file .* has only \d+ lines?`)
  25. // ErrDismissRequestOnClosedPR represents an error when an user tries to dismiss a review associated to a closed or merged PR.
  26. type ErrDismissRequestOnClosedPR struct{}
  27. // IsErrDismissRequestOnClosedPR checks if an error is an ErrDismissRequestOnClosedPR.
  28. func IsErrDismissRequestOnClosedPR(err error) bool {
  29. _, ok := err.(ErrDismissRequestOnClosedPR)
  30. return ok
  31. }
  32. func (err ErrDismissRequestOnClosedPR) Error() string {
  33. return "can't dismiss a review associated to a closed or merged PR"
  34. }
  35. func (err ErrDismissRequestOnClosedPR) Unwrap() error {
  36. return util.ErrPermissionDenied
  37. }
  38. // ErrSubmitReviewOnClosedPR represents an error when an user tries to submit an approve or reject review associated to a closed or merged PR.
  39. var ErrSubmitReviewOnClosedPR = errors.New("can't submit review for a closed or merged PR")
  40. // checkInvalidation checks if the line of code comment got changed by another commit.
  41. // If the line got changed the comment is going to be invalidated.
  42. func checkInvalidation(ctx context.Context, c *issues_model.Comment, repo *git.Repository, branch string) error {
  43. // FIXME differentiate between previous and proposed line
  44. commit, err := repo.LineBlame(branch, repo.Path, c.TreePath, uint(c.UnsignedLine()))
  45. if err != nil && (strings.Contains(err.Error(), "fatal: no such path") || notEnoughLines.MatchString(err.Error())) {
  46. c.Invalidated = true
  47. return issues_model.UpdateCommentInvalidate(ctx, c)
  48. }
  49. if err != nil {
  50. return err
  51. }
  52. if c.CommitSHA != "" && c.CommitSHA != commit.ID.String() {
  53. c.Invalidated = true
  54. return issues_model.UpdateCommentInvalidate(ctx, c)
  55. }
  56. return nil
  57. }
  58. // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change
  59. func InvalidateCodeComments(ctx context.Context, prs issues_model.PullRequestList, doer *user_model.User, repo *git.Repository, branch string) error {
  60. if len(prs) == 0 {
  61. return nil
  62. }
  63. issueIDs := prs.GetIssueIDs()
  64. codeComments, err := db.Find[issues_model.Comment](ctx, issues_model.FindCommentsOptions{
  65. ListOptions: db.ListOptionsAll,
  66. Type: issues_model.CommentTypeCode,
  67. Invalidated: optional.Some(false),
  68. IssueIDs: issueIDs,
  69. })
  70. if err != nil {
  71. return fmt.Errorf("find code comments: %v", err)
  72. }
  73. for _, comment := range codeComments {
  74. if err := checkInvalidation(ctx, comment, repo, branch); err != nil {
  75. return err
  76. }
  77. }
  78. return nil
  79. }
  80. // CreateCodeComment creates a comment on the code line
  81. func CreateCodeComment(ctx context.Context, doer *user_model.User, gitRepo *git.Repository, issue *issues_model.Issue, line int64, content, treePath string, pendingReview bool, replyReviewID int64, latestCommitID string, attachments []string) (*issues_model.Comment, error) {
  82. var (
  83. existsReview bool
  84. err error
  85. )
  86. // CreateCodeComment() is used for:
  87. // - Single comments
  88. // - Comments that are part of a review
  89. // - Comments that reply to an existing review
  90. if !pendingReview && replyReviewID != 0 {
  91. // It's not part of a review; maybe a reply to a review comment or a single comment.
  92. // Check if there are reviews for that line already; if there are, this is a reply
  93. if existsReview, err = issues_model.ReviewExists(ctx, issue, treePath, line); err != nil {
  94. return nil, err
  95. }
  96. }
  97. // Comments that are replies don't require a review header to show up in the issue view
  98. if !pendingReview && existsReview {
  99. if err = issue.LoadRepo(ctx); err != nil {
  100. return nil, err
  101. }
  102. comment, err := createCodeComment(ctx,
  103. doer,
  104. issue.Repo,
  105. issue,
  106. content,
  107. treePath,
  108. line,
  109. replyReviewID,
  110. attachments,
  111. )
  112. if err != nil {
  113. return nil, err
  114. }
  115. mentions, err := issues_model.FindAndUpdateIssueMentions(ctx, issue, doer, comment.Content)
  116. if err != nil {
  117. return nil, err
  118. }
  119. notify_service.CreateIssueComment(ctx, doer, issue.Repo, issue, comment, mentions)
  120. return comment, nil
  121. }
  122. review, err := issues_model.GetCurrentReview(ctx, doer, issue)
  123. if err != nil {
  124. if !issues_model.IsErrReviewNotExist(err) {
  125. return nil, err
  126. }
  127. if review, err = issues_model.CreateReview(ctx, issues_model.CreateReviewOptions{
  128. Type: issues_model.ReviewTypePending,
  129. Reviewer: doer,
  130. Issue: issue,
  131. Official: false,
  132. CommitID: latestCommitID,
  133. }); err != nil {
  134. return nil, err
  135. }
  136. }
  137. comment, err := createCodeComment(ctx,
  138. doer,
  139. issue.Repo,
  140. issue,
  141. content,
  142. treePath,
  143. line,
  144. review.ID,
  145. attachments,
  146. )
  147. if err != nil {
  148. return nil, err
  149. }
  150. if !pendingReview && !existsReview {
  151. // Submit the review we've just created so the comment shows up in the issue view
  152. if _, _, err = SubmitReview(ctx, doer, gitRepo, issue, issues_model.ReviewTypeComment, "", latestCommitID, nil); err != nil {
  153. return nil, err
  154. }
  155. }
  156. // NOTICE: if it's a pending review the notifications will not be fired until user submit review.
  157. return comment, nil
  158. }
  159. // createCodeComment creates a plain code comment at the specified line / path
  160. func createCodeComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, content, treePath string, line, reviewID int64, attachments []string) (*issues_model.Comment, error) {
  161. var commitID, patch string
  162. if err := issue.LoadPullRequest(ctx); err != nil {
  163. return nil, fmt.Errorf("LoadPullRequest: %w", err)
  164. }
  165. pr := issue.PullRequest
  166. if err := pr.LoadBaseRepo(ctx); err != nil {
  167. return nil, fmt.Errorf("LoadBaseRepo: %w", err)
  168. }
  169. gitRepo, closer, err := gitrepo.RepositoryFromContextOrOpen(ctx, pr.BaseRepo)
  170. if err != nil {
  171. return nil, fmt.Errorf("RepositoryFromContextOrOpen: %w", err)
  172. }
  173. defer closer.Close()
  174. invalidated := false
  175. head := pr.GetGitRefName()
  176. if line > 0 {
  177. if reviewID != 0 {
  178. first, err := issues_model.FindComments(ctx, &issues_model.FindCommentsOptions{
  179. ReviewID: reviewID,
  180. Line: line,
  181. TreePath: treePath,
  182. Type: issues_model.CommentTypeCode,
  183. ListOptions: db.ListOptions{
  184. PageSize: 1,
  185. Page: 1,
  186. },
  187. })
  188. if err == nil && len(first) > 0 {
  189. commitID = first[0].CommitSHA
  190. invalidated = first[0].Invalidated
  191. patch = first[0].Patch
  192. } else if err != nil && !issues_model.IsErrCommentNotExist(err) {
  193. return nil, fmt.Errorf("Find first comment for %d line %d path %s. Error: %w", reviewID, line, treePath, err)
  194. } else {
  195. review, err := issues_model.GetReviewByID(ctx, reviewID)
  196. if err == nil && len(review.CommitID) > 0 {
  197. head = review.CommitID
  198. } else if err != nil && !issues_model.IsErrReviewNotExist(err) {
  199. return nil, fmt.Errorf("GetReviewByID %d. Error: %w", reviewID, err)
  200. }
  201. }
  202. }
  203. if len(commitID) == 0 {
  204. // FIXME validate treePath
  205. // Get latest commit referencing the commented line
  206. // No need for get commit for base branch changes
  207. commit, err := gitRepo.LineBlame(head, gitRepo.Path, treePath, uint(line))
  208. if err == nil {
  209. commitID = commit.ID.String()
  210. } else if !(strings.Contains(err.Error(), "exit status 128 - fatal: no such path") || notEnoughLines.MatchString(err.Error())) {
  211. return nil, fmt.Errorf("LineBlame[%s, %s, %s, %d]: %w", pr.GetGitRefName(), gitRepo.Path, treePath, line, err)
  212. }
  213. }
  214. }
  215. // Only fetch diff if comment is review comment
  216. if len(patch) == 0 && reviewID != 0 {
  217. headCommitID, err := gitRepo.GetRefCommitID(pr.GetGitRefName())
  218. if err != nil {
  219. return nil, fmt.Errorf("GetRefCommitID[%s]: %w", pr.GetGitRefName(), err)
  220. }
  221. if len(commitID) == 0 {
  222. commitID = headCommitID
  223. }
  224. reader, writer := io.Pipe()
  225. defer func() {
  226. _ = reader.Close()
  227. _ = writer.Close()
  228. }()
  229. go func() {
  230. if err := git.GetRepoRawDiffForFile(gitRepo, pr.MergeBase, headCommitID, git.RawDiffNormal, treePath, writer); err != nil {
  231. _ = writer.CloseWithError(fmt.Errorf("GetRawDiffForLine[%s, %s, %s, %s]: %w", gitRepo.Path, pr.MergeBase, headCommitID, treePath, err))
  232. return
  233. }
  234. _ = writer.Close()
  235. }()
  236. patch, err = git.CutDiffAroundLine(reader, int64((&issues_model.Comment{Line: line}).UnsignedLine()), line < 0, setting.UI.CodeCommentLines)
  237. if err != nil {
  238. log.Error("Error whilst generating patch: %v", err)
  239. return nil, err
  240. }
  241. }
  242. return issues_model.CreateComment(ctx, &issues_model.CreateCommentOptions{
  243. Type: issues_model.CommentTypeCode,
  244. Doer: doer,
  245. Repo: repo,
  246. Issue: issue,
  247. Content: content,
  248. LineNum: line,
  249. TreePath: treePath,
  250. CommitSHA: commitID,
  251. ReviewID: reviewID,
  252. Patch: patch,
  253. Invalidated: invalidated,
  254. Attachments: attachments,
  255. })
  256. }
  257. // SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist
  258. func SubmitReview(ctx context.Context, doer *user_model.User, gitRepo *git.Repository, issue *issues_model.Issue, reviewType issues_model.ReviewType, content, commitID string, attachmentUUIDs []string) (*issues_model.Review, *issues_model.Comment, error) {
  259. if err := issue.LoadPullRequest(ctx); err != nil {
  260. return nil, nil, err
  261. }
  262. pr := issue.PullRequest
  263. var stale bool
  264. if reviewType != issues_model.ReviewTypeApprove && reviewType != issues_model.ReviewTypeReject {
  265. stale = false
  266. } else {
  267. if issue.IsClosed {
  268. return nil, nil, ErrSubmitReviewOnClosedPR
  269. }
  270. headCommitID, err := gitRepo.GetRefCommitID(pr.GetGitRefName())
  271. if err != nil {
  272. return nil, nil, err
  273. }
  274. if headCommitID == commitID {
  275. stale = false
  276. } else {
  277. stale, err = checkIfPRContentChanged(ctx, pr, commitID, headCommitID)
  278. if err != nil {
  279. return nil, nil, err
  280. }
  281. }
  282. }
  283. review, comm, err := issues_model.SubmitReview(ctx, doer, issue, reviewType, content, commitID, stale, attachmentUUIDs)
  284. if err != nil {
  285. return nil, nil, err
  286. }
  287. mentions, err := issues_model.FindAndUpdateIssueMentions(ctx, issue, doer, comm.Content)
  288. if err != nil {
  289. return nil, nil, err
  290. }
  291. notify_service.PullRequestReview(ctx, pr, review, comm, mentions)
  292. for _, lines := range review.CodeComments {
  293. for _, comments := range lines {
  294. for _, codeComment := range comments {
  295. mentions, err := issues_model.FindAndUpdateIssueMentions(ctx, issue, doer, codeComment.Content)
  296. if err != nil {
  297. return nil, nil, err
  298. }
  299. notify_service.PullRequestCodeComment(ctx, pr, codeComment, mentions)
  300. }
  301. }
  302. }
  303. return review, comm, nil
  304. }
  305. // DismissApprovalReviews dismiss all approval reviews because of new commits
  306. func DismissApprovalReviews(ctx context.Context, doer *user_model.User, pull *issues_model.PullRequest) error {
  307. reviews, err := issues_model.FindReviews(ctx, issues_model.FindReviewOptions{
  308. ListOptions: db.ListOptionsAll,
  309. IssueID: pull.IssueID,
  310. Type: issues_model.ReviewTypeApprove,
  311. Dismissed: optional.Some(false),
  312. })
  313. if err != nil {
  314. return err
  315. }
  316. if err := reviews.LoadIssues(ctx); err != nil {
  317. return err
  318. }
  319. return db.WithTx(ctx, func(ctx context.Context) error {
  320. for _, review := range reviews {
  321. if err := issues_model.DismissReview(ctx, review, true); err != nil {
  322. return err
  323. }
  324. comment, err := issues_model.CreateComment(ctx, &issues_model.CreateCommentOptions{
  325. Doer: doer,
  326. Content: "New commits pushed, approval review dismissed automatically according to repository settings",
  327. Type: issues_model.CommentTypeDismissReview,
  328. ReviewID: review.ID,
  329. Issue: review.Issue,
  330. Repo: review.Issue.Repo,
  331. })
  332. if err != nil {
  333. return err
  334. }
  335. comment.Review = review
  336. comment.Poster = doer
  337. comment.Issue = review.Issue
  338. notify_service.PullReviewDismiss(ctx, doer, review, comment)
  339. }
  340. return nil
  341. })
  342. }
  343. // DismissReview dismissing stale review by repo admin
  344. func DismissReview(ctx context.Context, reviewID, repoID int64, message string, doer *user_model.User, isDismiss, dismissPriors bool) (comment *issues_model.Comment, err error) {
  345. review, err := issues_model.GetReviewByID(ctx, reviewID)
  346. if err != nil {
  347. return nil, err
  348. }
  349. if review.Type != issues_model.ReviewTypeApprove && review.Type != issues_model.ReviewTypeReject {
  350. return nil, fmt.Errorf("not need to dismiss this review because it's type is not Approve or change request")
  351. }
  352. // load data for notify
  353. if err := review.LoadAttributes(ctx); err != nil {
  354. return nil, err
  355. }
  356. // Check if the review's repoID is the one we're currently expecting.
  357. if review.Issue.RepoID != repoID {
  358. return nil, fmt.Errorf("reviews's repository is not the same as the one we expect")
  359. }
  360. issue := review.Issue
  361. if issue.IsClosed {
  362. return nil, ErrDismissRequestOnClosedPR{}
  363. }
  364. if issue.IsPull {
  365. if err := issue.LoadPullRequest(ctx); err != nil {
  366. return nil, err
  367. }
  368. if issue.PullRequest.HasMerged {
  369. return nil, ErrDismissRequestOnClosedPR{}
  370. }
  371. }
  372. if err := issues_model.DismissReview(ctx, review, isDismiss); err != nil {
  373. return nil, err
  374. }
  375. if dismissPriors {
  376. reviews, err := issues_model.FindReviews(ctx, issues_model.FindReviewOptions{
  377. IssueID: review.IssueID,
  378. ReviewerID: review.ReviewerID,
  379. Dismissed: optional.Some(false),
  380. })
  381. if err != nil {
  382. return nil, err
  383. }
  384. for _, oldReview := range reviews {
  385. if err = issues_model.DismissReview(ctx, oldReview, true); err != nil {
  386. return nil, err
  387. }
  388. }
  389. }
  390. if !isDismiss {
  391. return nil, nil
  392. }
  393. if err := review.Issue.LoadAttributes(ctx); err != nil {
  394. return nil, err
  395. }
  396. comment, err = issues_model.CreateComment(ctx, &issues_model.CreateCommentOptions{
  397. Doer: doer,
  398. Content: message,
  399. Type: issues_model.CommentTypeDismissReview,
  400. ReviewID: review.ID,
  401. Issue: review.Issue,
  402. Repo: review.Issue.Repo,
  403. })
  404. if err != nil {
  405. return nil, err
  406. }
  407. comment.Review = review
  408. comment.Poster = doer
  409. comment.Issue = review.Issue
  410. notify_service.PullReviewDismiss(ctx, doer, review, comment)
  411. return comment, nil
  412. }