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

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