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.

merge.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // Copyright 2019 The Gitea Authors.
  2. // All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package pull
  6. import (
  7. "bufio"
  8. "bytes"
  9. "fmt"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/cache"
  17. "code.gitea.io/gitea/modules/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. api "code.gitea.io/gitea/modules/structs"
  21. "code.gitea.io/gitea/modules/util"
  22. )
  23. // Merge merges pull request to base repository.
  24. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  25. func Merge(pr *models.PullRequest, doer *models.User, baseGitRepo *git.Repository, mergeStyle models.MergeStyle, message string) (err error) {
  26. if err = pr.GetHeadRepo(); err != nil {
  27. return fmt.Errorf("GetHeadRepo: %v", err)
  28. } else if err = pr.GetBaseRepo(); err != nil {
  29. return fmt.Errorf("GetBaseRepo: %v", err)
  30. }
  31. prUnit, err := pr.BaseRepo.GetUnit(models.UnitTypePullRequests)
  32. if err != nil {
  33. return err
  34. }
  35. prConfig := prUnit.PullRequestsConfig()
  36. if err := pr.CheckUserAllowedToMerge(doer); err != nil {
  37. return fmt.Errorf("CheckUserAllowedToMerge: %v", err)
  38. }
  39. // Check if merge style is correct and allowed
  40. if !prConfig.IsMergeStyleAllowed(mergeStyle) {
  41. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  42. }
  43. defer func() {
  44. go models.HookQueue.Add(pr.BaseRepo.ID)
  45. go models.AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  46. }()
  47. // Clone base repo.
  48. tmpBasePath, err := models.CreateTemporaryPath("merge")
  49. if err != nil {
  50. return err
  51. }
  52. defer func() {
  53. if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
  54. log.Error("Merge: RemoveTemporaryPath: %s", err)
  55. }
  56. }()
  57. headRepoPath := models.RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  58. if err := git.Clone(baseGitRepo.Path, tmpBasePath, git.CloneRepoOptions{
  59. Shared: true,
  60. NoCheckout: true,
  61. Branch: pr.BaseBranch,
  62. }); err != nil {
  63. return fmt.Errorf("git clone: %v", err)
  64. }
  65. remoteRepoName := "head_repo"
  66. // Add head repo remote.
  67. addCacheRepo := func(staging, cache string) error {
  68. p := filepath.Join(staging, ".git", "objects", "info", "alternates")
  69. f, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0600)
  70. if err != nil {
  71. return err
  72. }
  73. defer f.Close()
  74. data := filepath.Join(cache, "objects")
  75. if _, err := fmt.Fprintln(f, data); err != nil {
  76. return err
  77. }
  78. return nil
  79. }
  80. if err := addCacheRepo(tmpBasePath, headRepoPath); err != nil {
  81. return fmt.Errorf("addCacheRepo [%s -> %s]: %v", headRepoPath, tmpBasePath, err)
  82. }
  83. var errbuf strings.Builder
  84. if err := git.NewCommand("remote", "add", remoteRepoName, headRepoPath).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  85. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  86. }
  87. // Fetch head branch
  88. if err := git.NewCommand("fetch", remoteRepoName).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  89. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  90. }
  91. trackingBranch := path.Join(remoteRepoName, pr.HeadBranch)
  92. stagingBranch := fmt.Sprintf("%s_%s", remoteRepoName, pr.HeadBranch)
  93. // Enable sparse-checkout
  94. sparseCheckoutList, err := getDiffTree(tmpBasePath, pr.BaseBranch, trackingBranch)
  95. if err != nil {
  96. return fmt.Errorf("getDiffTree: %v", err)
  97. }
  98. infoPath := filepath.Join(tmpBasePath, ".git", "info")
  99. if err := os.MkdirAll(infoPath, 0700); err != nil {
  100. return fmt.Errorf("creating directory failed [%s]: %v", infoPath, err)
  101. }
  102. sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout")
  103. if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil {
  104. return fmt.Errorf("Writing sparse-checkout file to %s: %v", sparseCheckoutListPath, err)
  105. }
  106. // Switch off LFS process (set required, clean and smudge here also)
  107. if err := git.NewCommand("config", "--local", "filter.lfs.process", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  108. return fmt.Errorf("git config [filter.lfs.process -> <> ]: %v", errbuf.String())
  109. }
  110. if err := git.NewCommand("config", "--local", "filter.lfs.required", "false").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  111. return fmt.Errorf("git config [filter.lfs.required -> <false> ]: %v", errbuf.String())
  112. }
  113. if err := git.NewCommand("config", "--local", "filter.lfs.clean", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  114. return fmt.Errorf("git config [filter.lfs.clean -> <> ]: %v", errbuf.String())
  115. }
  116. if err := git.NewCommand("config", "--local", "filter.lfs.smudge", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  117. return fmt.Errorf("git config [filter.lfs.smudge -> <> ]: %v", errbuf.String())
  118. }
  119. if err := git.NewCommand("config", "--local", "core.sparseCheckout", "true").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  120. return fmt.Errorf("git config [core.sparsecheckout -> true]: %v", errbuf.String())
  121. }
  122. // Read base branch index
  123. if err := git.NewCommand("read-tree", "HEAD").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  124. return fmt.Errorf("git read-tree HEAD: %s", errbuf.String())
  125. }
  126. // Merge commits.
  127. switch mergeStyle {
  128. case models.MergeStyleMerge:
  129. if err := git.NewCommand("merge", "--no-ff", "--no-commit", trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  130. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  131. }
  132. sig := doer.NewGitSig()
  133. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  134. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  135. }
  136. case models.MergeStyleRebase:
  137. // Checkout head branch
  138. if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  139. return fmt.Errorf("git checkout: %s", errbuf.String())
  140. }
  141. // Rebase before merging
  142. if err := git.NewCommand("rebase", "-q", pr.BaseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  143. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  144. }
  145. // Checkout base branch again
  146. if err := git.NewCommand("checkout", pr.BaseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  147. return fmt.Errorf("git checkout: %s", errbuf.String())
  148. }
  149. // Merge fast forward
  150. if err := git.NewCommand("merge", "--ff-only", "-q", stagingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  151. return fmt.Errorf("git merge --ff-only [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  152. }
  153. case models.MergeStyleRebaseMerge:
  154. // Checkout head branch
  155. if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  156. return fmt.Errorf("git checkout: %s", errbuf.String())
  157. }
  158. // Rebase before merging
  159. if err := git.NewCommand("rebase", "-q", pr.BaseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  160. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  161. }
  162. // Checkout base branch again
  163. if err := git.NewCommand("checkout", pr.BaseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  164. return fmt.Errorf("git checkout: %s", errbuf.String())
  165. }
  166. // Prepare merge with commit
  167. if err := git.NewCommand("merge", "--no-ff", "--no-commit", "-q", stagingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  168. return fmt.Errorf("git merge --no-ff [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  169. }
  170. // Set custom message and author and create merge commit
  171. sig := doer.NewGitSig()
  172. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  173. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  174. }
  175. case models.MergeStyleSquash:
  176. // Merge with squash
  177. if err := git.NewCommand("merge", "-q", "--squash", trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  178. return fmt.Errorf("git merge --squash [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  179. }
  180. sig := pr.Issue.Poster.NewGitSig()
  181. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  182. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  183. }
  184. default:
  185. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  186. }
  187. // OK we should cache our current head and origin/headbranch
  188. mergeHeadSHA, err := git.GetFullCommitID(tmpBasePath, "HEAD")
  189. if err != nil {
  190. return fmt.Errorf("Failed to get full commit id for HEAD: %v", err)
  191. }
  192. mergeBaseSHA, err := git.GetFullCommitID(tmpBasePath, "origin/"+pr.BaseBranch)
  193. if err != nil {
  194. return fmt.Errorf("Failed to get full commit id for origin/%s: %v", pr.BaseBranch, err)
  195. }
  196. // Now it's questionable about where this should go - either after or before the push
  197. // I think in the interests of data safety - failures to push to the lfs should prevent
  198. // the merge as you can always remerge.
  199. if setting.LFS.StartServer {
  200. if err := LFSPush(tmpBasePath, mergeHeadSHA, mergeBaseSHA, pr); err != nil {
  201. return err
  202. }
  203. }
  204. env := models.PushingEnvironment(doer, pr.BaseRepo)
  205. // Push back to upstream.
  206. if err := git.NewCommand("push", "origin", pr.BaseBranch).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  207. return fmt.Errorf("git push: %s", errbuf.String())
  208. }
  209. pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch)
  210. if err != nil {
  211. return fmt.Errorf("GetBranchCommit: %v", err)
  212. }
  213. pr.MergedUnix = util.TimeStampNow()
  214. pr.Merger = doer
  215. pr.MergerID = doer.ID
  216. if err = pr.SetMerged(); err != nil {
  217. log.Error("setMerged [%d]: %v", pr.ID, err)
  218. }
  219. if err = models.MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  220. log.Error("MergePullRequestAction [%d]: %v", pr.ID, err)
  221. }
  222. // Reset cached commit count
  223. cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
  224. // Reload pull request information.
  225. if err = pr.LoadAttributes(); err != nil {
  226. log.Error("LoadAttributes: %v", err)
  227. return nil
  228. }
  229. mode, _ := models.AccessLevel(doer, pr.Issue.Repo)
  230. if err = models.PrepareWebhooks(pr.Issue.Repo, models.HookEventPullRequest, &api.PullRequestPayload{
  231. Action: api.HookIssueClosed,
  232. Index: pr.Index,
  233. PullRequest: pr.APIFormat(),
  234. Repository: pr.Issue.Repo.APIFormat(mode),
  235. Sender: doer.APIFormat(),
  236. }); err != nil {
  237. log.Error("PrepareWebhooks: %v", err)
  238. } else {
  239. go models.HookQueue.Add(pr.Issue.Repo.ID)
  240. }
  241. l, err := baseGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  242. if err != nil {
  243. log.Error("CommitsBetweenIDs: %v", err)
  244. return nil
  245. }
  246. // It is possible that head branch is not fully sync with base branch for merge commits,
  247. // so we need to get latest head commit and append merge commit manually
  248. // to avoid strange diff commits produced.
  249. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  250. if err != nil {
  251. log.Error("GetBranchCommit: %v", err)
  252. return nil
  253. }
  254. if mergeStyle == models.MergeStyleMerge {
  255. l.PushFront(mergeCommit)
  256. }
  257. p := &api.PushPayload{
  258. Ref: git.BranchPrefix + pr.BaseBranch,
  259. Before: pr.MergeBase,
  260. After: mergeCommit.ID.String(),
  261. CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  262. Commits: models.ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()),
  263. Repo: pr.BaseRepo.APIFormat(mode),
  264. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  265. Sender: doer.APIFormat(),
  266. }
  267. if err = models.PrepareWebhooks(pr.BaseRepo, models.HookEventPush, p); err != nil {
  268. log.Error("PrepareWebhooks: %v", err)
  269. } else {
  270. go models.HookQueue.Add(pr.BaseRepo.ID)
  271. }
  272. return nil
  273. }
  274. func getDiffTree(repoPath, baseBranch, headBranch string) (string, error) {
  275. getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
  276. var outbuf, errbuf strings.Builder
  277. // Compute the diff-tree for sparse-checkout
  278. // The branch argument must be enclosed with double-quotes ("") in case it contains slashes (e.g "feature/test")
  279. if err := git.NewCommand("diff-tree", "--no-commit-id", "--name-only", "-r", "--root", baseBranch, headBranch).RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil {
  280. return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String())
  281. }
  282. return outbuf.String(), nil
  283. }
  284. list, err := getDiffTreeFromBranch(repoPath, baseBranch, headBranch)
  285. if err != nil {
  286. return "", err
  287. }
  288. // Prefixing '/' for each entry, otherwise all files with the same name in subdirectories would be matched.
  289. out := bytes.Buffer{}
  290. scanner := bufio.NewScanner(strings.NewReader(list))
  291. for scanner.Scan() {
  292. fmt.Fprintf(&out, "/%s\n", scanner.Text())
  293. }
  294. return out.String(), nil
  295. }