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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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/timeutil"
  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.AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  45. }()
  46. // Clone base repo.
  47. tmpBasePath, err := models.CreateTemporaryPath("merge")
  48. if err != nil {
  49. return err
  50. }
  51. defer func() {
  52. if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
  53. log.Error("Merge: RemoveTemporaryPath: %s", err)
  54. }
  55. }()
  56. headRepoPath := models.RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  57. if err := git.Clone(baseGitRepo.Path, tmpBasePath, git.CloneRepoOptions{
  58. Shared: true,
  59. NoCheckout: true,
  60. Branch: pr.BaseBranch,
  61. }); err != nil {
  62. return fmt.Errorf("git clone: %v", err)
  63. }
  64. remoteRepoName := "head_repo"
  65. // Add head repo remote.
  66. addCacheRepo := func(staging, cache string) error {
  67. p := filepath.Join(staging, ".git", "objects", "info", "alternates")
  68. f, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0600)
  69. if err != nil {
  70. return err
  71. }
  72. defer f.Close()
  73. data := filepath.Join(cache, "objects")
  74. if _, err := fmt.Fprintln(f, data); err != nil {
  75. return err
  76. }
  77. return nil
  78. }
  79. if err := addCacheRepo(tmpBasePath, headRepoPath); err != nil {
  80. return fmt.Errorf("addCacheRepo [%s -> %s]: %v", headRepoPath, tmpBasePath, err)
  81. }
  82. var errbuf strings.Builder
  83. if err := git.NewCommand("remote", "add", remoteRepoName, headRepoPath).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  84. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  85. }
  86. // Fetch head branch
  87. if err := git.NewCommand("fetch", remoteRepoName, pr.HeadBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  88. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  89. }
  90. trackingBranch := path.Join(remoteRepoName, pr.HeadBranch)
  91. stagingBranch := fmt.Sprintf("%s_%s", remoteRepoName, pr.HeadBranch)
  92. // Enable sparse-checkout
  93. sparseCheckoutList, err := getDiffTree(tmpBasePath, pr.BaseBranch, trackingBranch)
  94. if err != nil {
  95. return fmt.Errorf("getDiffTree: %v", err)
  96. }
  97. infoPath := filepath.Join(tmpBasePath, ".git", "info")
  98. if err := os.MkdirAll(infoPath, 0700); err != nil {
  99. return fmt.Errorf("creating directory failed [%s]: %v", infoPath, err)
  100. }
  101. sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout")
  102. if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil {
  103. return fmt.Errorf("Writing sparse-checkout file to %s: %v", sparseCheckoutListPath, err)
  104. }
  105. // Switch off LFS process (set required, clean and smudge here also)
  106. if err := git.NewCommand("config", "--local", "filter.lfs.process", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  107. return fmt.Errorf("git config [filter.lfs.process -> <> ]: %v", errbuf.String())
  108. }
  109. if err := git.NewCommand("config", "--local", "filter.lfs.required", "false").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  110. return fmt.Errorf("git config [filter.lfs.required -> <false> ]: %v", errbuf.String())
  111. }
  112. if err := git.NewCommand("config", "--local", "filter.lfs.clean", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  113. return fmt.Errorf("git config [filter.lfs.clean -> <> ]: %v", errbuf.String())
  114. }
  115. if err := git.NewCommand("config", "--local", "filter.lfs.smudge", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  116. return fmt.Errorf("git config [filter.lfs.smudge -> <> ]: %v", errbuf.String())
  117. }
  118. if err := git.NewCommand("config", "--local", "core.sparseCheckout", "true").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  119. return fmt.Errorf("git config [core.sparsecheckout -> true]: %v", errbuf.String())
  120. }
  121. // Read base branch index
  122. if err := git.NewCommand("read-tree", "HEAD").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  123. return fmt.Errorf("git read-tree HEAD: %s", errbuf.String())
  124. }
  125. // Merge commits.
  126. switch mergeStyle {
  127. case models.MergeStyleMerge:
  128. if err := git.NewCommand("merge", "--no-ff", "--no-commit", trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  129. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  130. }
  131. sig := doer.NewGitSig()
  132. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  133. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  134. }
  135. case models.MergeStyleRebase:
  136. // Checkout head branch
  137. if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  138. return fmt.Errorf("git checkout: %s", errbuf.String())
  139. }
  140. // Rebase before merging
  141. if err := git.NewCommand("rebase", "-q", pr.BaseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  142. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  143. }
  144. // Checkout base branch again
  145. if err := git.NewCommand("checkout", pr.BaseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  146. return fmt.Errorf("git checkout: %s", errbuf.String())
  147. }
  148. // Merge fast forward
  149. if err := git.NewCommand("merge", "--ff-only", "-q", stagingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  150. return fmt.Errorf("git merge --ff-only [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  151. }
  152. case models.MergeStyleRebaseMerge:
  153. // Checkout head branch
  154. if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  155. return fmt.Errorf("git checkout: %s", errbuf.String())
  156. }
  157. // Rebase before merging
  158. if err := git.NewCommand("rebase", "-q", pr.BaseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  159. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  160. }
  161. // Checkout base branch again
  162. if err := git.NewCommand("checkout", pr.BaseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  163. return fmt.Errorf("git checkout: %s", errbuf.String())
  164. }
  165. // Prepare merge with commit
  166. if err := git.NewCommand("merge", "--no-ff", "--no-commit", "-q", stagingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  167. return fmt.Errorf("git merge --no-ff [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  168. }
  169. // Set custom message and author and create merge commit
  170. sig := doer.NewGitSig()
  171. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  172. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  173. }
  174. case models.MergeStyleSquash:
  175. // Merge with squash
  176. if err := git.NewCommand("merge", "-q", "--squash", trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  177. return fmt.Errorf("git merge --squash [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  178. }
  179. sig := pr.Issue.Poster.NewGitSig()
  180. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  181. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  182. }
  183. default:
  184. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  185. }
  186. // OK we should cache our current head and origin/headbranch
  187. mergeHeadSHA, err := git.GetFullCommitID(tmpBasePath, "HEAD")
  188. if err != nil {
  189. return fmt.Errorf("Failed to get full commit id for HEAD: %v", err)
  190. }
  191. mergeBaseSHA, err := git.GetFullCommitID(tmpBasePath, "origin/"+pr.BaseBranch)
  192. if err != nil {
  193. return fmt.Errorf("Failed to get full commit id for origin/%s: %v", pr.BaseBranch, err)
  194. }
  195. // Now it's questionable about where this should go - either after or before the push
  196. // I think in the interests of data safety - failures to push to the lfs should prevent
  197. // the merge as you can always remerge.
  198. if setting.LFS.StartServer {
  199. if err := LFSPush(tmpBasePath, mergeHeadSHA, mergeBaseSHA, pr); err != nil {
  200. return err
  201. }
  202. }
  203. headUser, err := models.GetUserByName(pr.HeadUserName)
  204. if err != nil {
  205. if !models.IsErrUserNotExist(err) {
  206. log.Error("Can't find user: %s for head repository - %v", pr.HeadUserName, err)
  207. return err
  208. }
  209. log.Error("Can't find user: %s for head repository - defaulting to doer: %s - %v", pr.HeadUserName, doer.Name, err)
  210. headUser = doer
  211. }
  212. env := models.FullPushingEnvironment(
  213. headUser,
  214. doer,
  215. pr.BaseRepo,
  216. pr.BaseRepo.Name,
  217. pr.ID,
  218. )
  219. // Push back to upstream.
  220. if err := git.NewCommand("push", "origin", pr.BaseBranch).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  221. return fmt.Errorf("git push: %s", errbuf.String())
  222. }
  223. pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch)
  224. if err != nil {
  225. return fmt.Errorf("GetBranchCommit: %v", err)
  226. }
  227. pr.MergedUnix = timeutil.TimeStampNow()
  228. pr.Merger = doer
  229. pr.MergerID = doer.ID
  230. if err = pr.SetMerged(); err != nil {
  231. log.Error("setMerged [%d]: %v", pr.ID, err)
  232. }
  233. if err = models.MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  234. log.Error("MergePullRequestAction [%d]: %v", pr.ID, err)
  235. }
  236. // Reset cached commit count
  237. cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
  238. // Reload pull request information.
  239. if err = pr.LoadAttributes(); err != nil {
  240. log.Error("LoadAttributes: %v", err)
  241. return nil
  242. }
  243. mode, _ := models.AccessLevel(doer, pr.Issue.Repo)
  244. if err = models.PrepareWebhooks(pr.Issue.Repo, models.HookEventPullRequest, &api.PullRequestPayload{
  245. Action: api.HookIssueClosed,
  246. Index: pr.Index,
  247. PullRequest: pr.APIFormat(),
  248. Repository: pr.Issue.Repo.APIFormat(mode),
  249. Sender: doer.APIFormat(),
  250. }); err != nil {
  251. log.Error("PrepareWebhooks: %v", err)
  252. } else {
  253. go models.HookQueue.Add(pr.Issue.Repo.ID)
  254. }
  255. return nil
  256. }
  257. func getDiffTree(repoPath, baseBranch, headBranch string) (string, error) {
  258. getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
  259. var outbuf, errbuf strings.Builder
  260. // Compute the diff-tree for sparse-checkout
  261. // The branch argument must be enclosed with double-quotes ("") in case it contains slashes (e.g "feature/test")
  262. if err := git.NewCommand("diff-tree", "--no-commit-id", "--name-only", "-r", "--root", baseBranch, headBranch).RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil {
  263. return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String())
  264. }
  265. return outbuf.String(), nil
  266. }
  267. list, err := getDiffTreeFromBranch(repoPath, baseBranch, headBranch)
  268. if err != nil {
  269. return "", err
  270. }
  271. // Prefixing '/' for each entry, otherwise all files with the same name in subdirectories would be matched.
  272. out := bytes.Buffer{}
  273. scanner := bufio.NewScanner(strings.NewReader(list))
  274. for scanner.Scan() {
  275. fmt.Fprintf(&out, "/%s\n", scanner.Text())
  276. }
  277. return out.String(), nil
  278. }