Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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