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

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