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.

comments.go 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package comments
  5. import (
  6. "bytes"
  7. "fmt"
  8. "strings"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/git"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/services/gitdiff"
  13. )
  14. // CreateCodeComment creates a plain code comment at the specified line / path
  15. func CreateCodeComment(doer *models.User, repo *models.Repository, issue *models.Issue, content, treePath string, line, reviewID int64) (*models.Comment, error) {
  16. var commitID, patch string
  17. pr, err := models.GetPullRequestByIssueID(issue.ID)
  18. if err != nil {
  19. return nil, fmt.Errorf("GetPullRequestByIssueID: %v", err)
  20. }
  21. if err := pr.GetBaseRepo(); err != nil {
  22. return nil, fmt.Errorf("GetHeadRepo: %v", err)
  23. }
  24. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  25. if err != nil {
  26. return nil, fmt.Errorf("OpenRepository: %v", err)
  27. }
  28. // FIXME validate treePath
  29. // Get latest commit referencing the commented line
  30. // No need for get commit for base branch changes
  31. if line > 0 {
  32. commit, err := gitRepo.LineBlame(pr.GetGitRefName(), gitRepo.Path, treePath, uint(line))
  33. if err == nil {
  34. commitID = commit.ID.String()
  35. } else if !strings.Contains(err.Error(), "exit status 128 - fatal: no such path") {
  36. return nil, fmt.Errorf("LineBlame[%s, %s, %s, %d]: %v", pr.GetGitRefName(), gitRepo.Path, treePath, line, err)
  37. }
  38. }
  39. // Only fetch diff if comment is review comment
  40. if reviewID != 0 {
  41. headCommitID, err := gitRepo.GetRefCommitID(pr.GetGitRefName())
  42. if err != nil {
  43. return nil, fmt.Errorf("GetRefCommitID[%s]: %v", pr.GetGitRefName(), err)
  44. }
  45. patchBuf := new(bytes.Buffer)
  46. if err := gitdiff.GetRawDiffForFile(gitRepo.Path, pr.MergeBase, headCommitID, gitdiff.RawDiffNormal, treePath, patchBuf); err != nil {
  47. return nil, fmt.Errorf("GetRawDiffForLine[%s, %s, %s, %s]: %v", err, gitRepo.Path, pr.MergeBase, headCommitID, treePath)
  48. }
  49. patch = gitdiff.CutDiffAroundLine(patchBuf, int64((&models.Comment{Line: line}).UnsignedLine()), line < 0, setting.UI.CodeCommentLines)
  50. }
  51. return models.CreateComment(&models.CreateCommentOptions{
  52. Type: models.CommentTypeCode,
  53. Doer: doer,
  54. Repo: repo,
  55. Issue: issue,
  56. Content: content,
  57. LineNum: line,
  58. TreePath: treePath,
  59. CommitSHA: commitID,
  60. ReviewID: reviewID,
  61. Patch: patch,
  62. })
  63. }