repo_pull.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2015 The Gogs 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 git
  5. import (
  6. "container/list"
  7. "fmt"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // PullRequestInfo represents needed information for a pull request.
  13. type PullRequestInfo struct {
  14. MergeBase string
  15. Commits *list.List
  16. NumFiles int
  17. }
  18. // GetMergeBase checks and returns merge base of two branches.
  19. func (repo *Repository) GetMergeBase(base, head string) (string, error) {
  20. stdout, err := NewCommand("merge-base", base, head).RunInDir(repo.Path)
  21. if err != nil {
  22. if strings.Contains(err.Error(), "exit status 1") {
  23. return "", ErrNoMergeBase{}
  24. }
  25. return "", err
  26. }
  27. return strings.TrimSpace(stdout), nil
  28. }
  29. // GetPullRequestInfo generates and returns pull request information
  30. // between base and head branches of repositories.
  31. func (repo *Repository) GetPullRequestInfo(basePath, baseBranch, headBranch string) (_ *PullRequestInfo, err error) {
  32. var remoteBranch string
  33. // We don't need a temporary remote for same repository.
  34. if repo.Path != basePath {
  35. // Add a temporary remote
  36. tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10)
  37. if err = repo.AddRemote(tmpRemote, basePath, true); err != nil {
  38. return nil, fmt.Errorf("AddRemote: %v", err)
  39. }
  40. defer repo.RemoveRemote(tmpRemote)
  41. remoteBranch = "remotes/" + tmpRemote + "/" + baseBranch
  42. } else {
  43. remoteBranch = baseBranch
  44. }
  45. prInfo := new(PullRequestInfo)
  46. prInfo.MergeBase, err = repo.GetMergeBase(remoteBranch, headBranch)
  47. if err != nil {
  48. return nil, err
  49. }
  50. logs, err := NewCommand("log", prInfo.MergeBase+"..."+headBranch, _PRETTY_LOG_FORMAT).RunInDirBytes(repo.Path)
  51. if err != nil {
  52. return nil, err
  53. }
  54. prInfo.Commits, err = repo.parsePrettyFormatLogToList(logs)
  55. if err != nil {
  56. return nil, fmt.Errorf("parsePrettyFormatLogToList: %v", err)
  57. }
  58. // Count number of changed files.
  59. stdout, err := NewCommand("diff", "--name-only", remoteBranch+"..."+headBranch).RunInDir(repo.Path)
  60. if err != nil {
  61. return nil, err
  62. }
  63. prInfo.NumFiles = len(strings.Split(stdout, "\n")) - 1
  64. return prInfo, nil
  65. }
  66. // GetPatch generates and returns patch data between given revisions.
  67. func (repo *Repository) GetPatch(base, head string) ([]byte, error) {
  68. return NewCommand("diff", "-p", "--binary", base, head).RunInDirBytes(repo.Path)
  69. }