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 13KB

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