Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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