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.

repo_pull.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. return strings.TrimSpace(stdout), err
  22. }
  23. // GetPullRequestInfo generates and returns pull request information
  24. // between base and head branches of repositories.
  25. func (repo *Repository) GetPullRequestInfo(basePath, baseBranch, headBranch string) (_ *PullRequestInfo, err error) {
  26. var remoteBranch string
  27. // We don't need a temporary remote for same repository.
  28. if repo.Path != basePath {
  29. // Add a temporary remote
  30. tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10)
  31. if err = repo.AddRemote(tmpRemote, basePath, true); err != nil {
  32. return nil, fmt.Errorf("AddRemote: %v", err)
  33. }
  34. defer repo.RemoveRemote(tmpRemote)
  35. remoteBranch = "remotes/" + tmpRemote + "/" + baseBranch
  36. } else {
  37. remoteBranch = baseBranch
  38. }
  39. prInfo := new(PullRequestInfo)
  40. prInfo.MergeBase, err = repo.GetMergeBase(remoteBranch, headBranch)
  41. if err != nil {
  42. return nil, fmt.Errorf("GetMergeBase: %v", err)
  43. }
  44. logs, err := NewCommand("log", prInfo.MergeBase+"..."+headBranch, _PRETTY_LOG_FORMAT).RunInDirBytes(repo.Path)
  45. if err != nil {
  46. return nil, err
  47. }
  48. prInfo.Commits, err = repo.parsePrettyFormatLogToList(logs)
  49. if err != nil {
  50. return nil, fmt.Errorf("parsePrettyFormatLogToList: %v", err)
  51. }
  52. // Count number of changed files.
  53. stdout, err := NewCommand("diff", "--name-only", remoteBranch+"..."+headBranch).RunInDir(repo.Path)
  54. if err != nil {
  55. return nil, err
  56. }
  57. prInfo.NumFiles = len(strings.Split(stdout, "\n")) - 1
  58. return prInfo, nil
  59. }
  60. // GetPatch generates and returns patch data between given revisions.
  61. func (repo *Repository) GetPatch(base, head string) ([]byte, error) {
  62. return NewCommand("diff", "-p", "--binary", base, head).RunInDirBytes(repo.Path)
  63. }