gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package pull
  4. import (
  5. "context"
  6. issues_model "code.gitea.io/gitea/models/issues"
  7. repo_model "code.gitea.io/gitea/models/repo"
  8. user_model "code.gitea.io/gitea/models/user"
  9. "code.gitea.io/gitea/modules/gitrepo"
  10. "code.gitea.io/gitea/modules/json"
  11. )
  12. // getCommitIDsFromRepo get commit IDs from repo in between oldCommitID and newCommitID
  13. // Commit on baseBranch will skip
  14. func getCommitIDsFromRepo(ctx context.Context, repo *repo_model.Repository, oldCommitID, newCommitID, baseBranch string) (commitIDs []string, err error) {
  15. gitRepo, closer, err := gitrepo.RepositoryFromContextOrOpen(ctx, repo)
  16. if err != nil {
  17. return nil, err
  18. }
  19. defer closer.Close()
  20. oldCommit, err := gitRepo.GetCommit(oldCommitID)
  21. if err != nil {
  22. return nil, err
  23. }
  24. newCommit, err := gitRepo.GetCommit(newCommitID)
  25. if err != nil {
  26. return nil, err
  27. }
  28. // Find commits between new and old commit excluding base branch commits
  29. commits, err := gitRepo.CommitsBetweenNotBase(newCommit, oldCommit, baseBranch)
  30. if err != nil {
  31. return nil, err
  32. }
  33. commitIDs = make([]string, 0, len(commits))
  34. for i := len(commits) - 1; i >= 0; i-- {
  35. commitIDs = append(commitIDs, commits[i].ID.String())
  36. }
  37. return commitIDs, err
  38. }
  39. // CreatePushPullComment create push code to pull base comment
  40. func CreatePushPullComment(ctx context.Context, pusher *user_model.User, pr *issues_model.PullRequest, oldCommitID, newCommitID string, isForcePush bool) (comment *issues_model.Comment, err error) {
  41. if pr.HasMerged || oldCommitID == "" || newCommitID == "" {
  42. return nil, nil
  43. }
  44. opts := &issues_model.CreateCommentOptions{
  45. Type: issues_model.CommentTypePullRequestPush,
  46. Doer: pusher,
  47. Repo: pr.BaseRepo,
  48. IsForcePush: isForcePush,
  49. Issue: pr.Issue,
  50. }
  51. var data issues_model.PushActionContent
  52. if opts.IsForcePush {
  53. data.CommitIDs = []string{oldCommitID, newCommitID}
  54. } else {
  55. data.CommitIDs, err = getCommitIDsFromRepo(ctx, pr.BaseRepo, oldCommitID, newCommitID, pr.BaseBranch)
  56. if err != nil {
  57. return nil, err
  58. }
  59. }
  60. dataJSON, err := json.Marshal(data)
  61. if err != nil {
  62. return nil, err
  63. }
  64. opts.Content = string(dataJSON)
  65. comment, err = issues_model.CreateComment(ctx, opts)
  66. return comment, err
  67. }