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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. "time"
  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. "github.com/mcuadros/go-version"
  23. )
  24. // Merge merges pull request to base repository.
  25. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  26. func Merge(pr *models.PullRequest, doer *models.User, baseGitRepo *git.Repository, mergeStyle models.MergeStyle, message string) (err error) {
  27. binVersion, err := git.BinVersion()
  28. if err != nil {
  29. return fmt.Errorf("Unable to get git version: %v", err)
  30. }
  31. if err = pr.GetHeadRepo(); err != nil {
  32. return fmt.Errorf("GetHeadRepo: %v", err)
  33. } else if err = pr.GetBaseRepo(); err != nil {
  34. return fmt.Errorf("GetBaseRepo: %v", err)
  35. }
  36. prUnit, err := pr.BaseRepo.GetUnit(models.UnitTypePullRequests)
  37. if err != nil {
  38. return err
  39. }
  40. prConfig := prUnit.PullRequestsConfig()
  41. if err := pr.CheckUserAllowedToMerge(doer); err != nil {
  42. return fmt.Errorf("CheckUserAllowedToMerge: %v", err)
  43. }
  44. // Check if merge style is correct and allowed
  45. if !prConfig.IsMergeStyleAllowed(mergeStyle) {
  46. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  47. }
  48. defer func() {
  49. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  50. }()
  51. // Clone base repo.
  52. tmpBasePath, err := models.CreateTemporaryPath("merge")
  53. if err != nil {
  54. return err
  55. }
  56. defer func() {
  57. if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
  58. log.Error("Merge: RemoveTemporaryPath: %s", err)
  59. }
  60. }()
  61. headRepoPath := models.RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  62. if err := git.InitRepository(tmpBasePath, false); err != nil {
  63. return fmt.Errorf("git init: %v", err)
  64. }
  65. remoteRepoName := "head_repo"
  66. baseBranch := "base"
  67. // Add head repo remote.
  68. addCacheRepo := func(staging, cache string) error {
  69. p := filepath.Join(staging, ".git", "objects", "info", "alternates")
  70. f, err := os.OpenFile(p, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
  71. if err != nil {
  72. return err
  73. }
  74. defer f.Close()
  75. data := filepath.Join(cache, "objects")
  76. if _, err := fmt.Fprintln(f, data); err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. if err := addCacheRepo(tmpBasePath, baseGitRepo.Path); err != nil {
  82. return fmt.Errorf("addCacheRepo [%s -> %s]: %v", headRepoPath, tmpBasePath, err)
  83. }
  84. var errbuf strings.Builder
  85. if err := git.NewCommand("remote", "add", "-t", pr.BaseBranch, "-m", pr.BaseBranch, "origin", baseGitRepo.Path).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  86. return fmt.Errorf("git remote add [%s -> %s]: %s", baseGitRepo.Path, tmpBasePath, errbuf.String())
  87. }
  88. if err := git.NewCommand("fetch", "origin", "--no-tags", pr.BaseBranch+":"+baseBranch, pr.BaseBranch+":original_"+baseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  89. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  90. }
  91. if err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+baseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  92. return fmt.Errorf("git symbolic-ref HEAD base [%s]: %s", tmpBasePath, errbuf.String())
  93. }
  94. if err := addCacheRepo(tmpBasePath, headRepoPath); err != nil {
  95. return fmt.Errorf("addCacheRepo [%s -> %s]: %v", headRepoPath, tmpBasePath, err)
  96. }
  97. if err := git.NewCommand("remote", "add", remoteRepoName, headRepoPath).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  98. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  99. }
  100. trackingBranch := "tracking"
  101. // Fetch head branch
  102. if err := git.NewCommand("fetch", "--no-tags", remoteRepoName, pr.HeadBranch+":"+trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  103. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  104. }
  105. stagingBranch := "staging"
  106. // Enable sparse-checkout
  107. sparseCheckoutList, err := getDiffTree(tmpBasePath, baseBranch, trackingBranch)
  108. if err != nil {
  109. return fmt.Errorf("getDiffTree: %v", err)
  110. }
  111. infoPath := filepath.Join(tmpBasePath, ".git", "info")
  112. if err := os.MkdirAll(infoPath, 0700); err != nil {
  113. return fmt.Errorf("creating directory failed [%s]: %v", infoPath, err)
  114. }
  115. sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout")
  116. if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil {
  117. return fmt.Errorf("Writing sparse-checkout file to %s: %v", sparseCheckoutListPath, err)
  118. }
  119. gitConfigCommand := func() func() *git.Command {
  120. binVersion, err := git.BinVersion()
  121. if err != nil {
  122. log.Fatal("Error retrieving git version: %v", err)
  123. }
  124. if version.Compare(binVersion, "1.8.0", ">=") {
  125. return func() *git.Command {
  126. return git.NewCommand("config", "--local")
  127. }
  128. }
  129. return func() *git.Command {
  130. return git.NewCommand("config")
  131. }
  132. }()
  133. // Switch off LFS process (set required, clean and smudge here also)
  134. if err := gitConfigCommand().AddArguments("filter.lfs.process", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  135. return fmt.Errorf("git config [filter.lfs.process -> <> ]: %v", errbuf.String())
  136. }
  137. if err := gitConfigCommand().AddArguments("filter.lfs.required", "false").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  138. return fmt.Errorf("git config [filter.lfs.required -> <false> ]: %v", errbuf.String())
  139. }
  140. if err := gitConfigCommand().AddArguments("filter.lfs.clean", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  141. return fmt.Errorf("git config [filter.lfs.clean -> <> ]: %v", errbuf.String())
  142. }
  143. if err := gitConfigCommand().AddArguments("filter.lfs.smudge", "").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  144. return fmt.Errorf("git config [filter.lfs.smudge -> <> ]: %v", errbuf.String())
  145. }
  146. if err := gitConfigCommand().AddArguments("core.sparseCheckout", "true").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  147. return fmt.Errorf("git config [core.sparsecheckout -> true]: %v", errbuf.String())
  148. }
  149. // Read base branch index
  150. if err := git.NewCommand("read-tree", "HEAD").RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  151. return fmt.Errorf("git read-tree HEAD: %s", errbuf.String())
  152. }
  153. // Determine if we should sign
  154. signArg := ""
  155. if version.Compare(binVersion, "1.7.9", ">=") {
  156. sign, keyID := pr.BaseRepo.SignMerge(doer, tmpBasePath, "HEAD", trackingBranch)
  157. if sign {
  158. signArg = "-S" + keyID
  159. } else if version.Compare(binVersion, "2.0.0", ">=") {
  160. signArg = "--no-gpg-sign"
  161. }
  162. }
  163. sig := doer.NewGitSig()
  164. commitTimeStr := time.Now().Format(time.RFC3339)
  165. // Because this may call hooks we should pass in the environment
  166. env := append(os.Environ(),
  167. "GIT_AUTHOR_NAME="+sig.Name,
  168. "GIT_AUTHOR_EMAIL="+sig.Email,
  169. "GIT_AUTHOR_DATE="+commitTimeStr,
  170. "GIT_COMMITTER_NAME="+sig.Name,
  171. "GIT_COMMITTER_EMAIL="+sig.Email,
  172. "GIT_COMMITTER_DATE="+commitTimeStr,
  173. )
  174. // Merge commits.
  175. switch mergeStyle {
  176. case models.MergeStyleMerge:
  177. if err := git.NewCommand("merge", "--no-ff", "--no-commit", trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  178. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  179. }
  180. if signArg == "" {
  181. if err := git.NewCommand("commit", "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  182. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  183. }
  184. } else {
  185. if err := git.NewCommand("commit", signArg, "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  186. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  187. }
  188. }
  189. case models.MergeStyleRebase:
  190. // Checkout head branch
  191. if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  192. return fmt.Errorf("git checkout: %s", errbuf.String())
  193. }
  194. // Rebase before merging
  195. if err := git.NewCommand("rebase", "-q", baseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  196. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  197. }
  198. // Checkout base branch again
  199. if err := git.NewCommand("checkout", baseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  200. return fmt.Errorf("git checkout: %s", errbuf.String())
  201. }
  202. // Merge fast forward
  203. if err := git.NewCommand("merge", "--ff-only", "-q", stagingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  204. return fmt.Errorf("git merge --ff-only [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  205. }
  206. case models.MergeStyleRebaseMerge:
  207. // Checkout head branch
  208. if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  209. return fmt.Errorf("git checkout: %s", errbuf.String())
  210. }
  211. // Rebase before merging
  212. if err := git.NewCommand("rebase", "-q", baseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  213. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  214. }
  215. // Checkout base branch again
  216. if err := git.NewCommand("checkout", baseBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  217. return fmt.Errorf("git checkout: %s", errbuf.String())
  218. }
  219. // Prepare merge with commit
  220. if err := git.NewCommand("merge", "--no-ff", "--no-commit", "-q", stagingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  221. return fmt.Errorf("git merge --no-ff [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  222. }
  223. // Set custom message and author and create merge commit
  224. if signArg == "" {
  225. if err := git.NewCommand("commit", "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  226. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  227. }
  228. } else {
  229. if err := git.NewCommand("commit", signArg, "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  230. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  231. }
  232. }
  233. case models.MergeStyleSquash:
  234. // Merge with squash
  235. if err := git.NewCommand("merge", "-q", "--squash", trackingBranch).RunInDirPipeline(tmpBasePath, nil, &errbuf); err != nil {
  236. return fmt.Errorf("git merge --squash [%s -> %s]: %s", headRepoPath, tmpBasePath, errbuf.String())
  237. }
  238. sig := pr.Issue.Poster.NewGitSig()
  239. if signArg == "" {
  240. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  241. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  242. }
  243. } else {
  244. if err := git.NewCommand("commit", signArg, fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  245. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, errbuf.String())
  246. }
  247. }
  248. default:
  249. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  250. }
  251. // OK we should cache our current head and origin/headbranch
  252. mergeHeadSHA, err := git.GetFullCommitID(tmpBasePath, "HEAD")
  253. if err != nil {
  254. return fmt.Errorf("Failed to get full commit id for HEAD: %v", err)
  255. }
  256. mergeBaseSHA, err := git.GetFullCommitID(tmpBasePath, "original_"+baseBranch)
  257. if err != nil {
  258. return fmt.Errorf("Failed to get full commit id for origin/%s: %v", pr.BaseBranch, err)
  259. }
  260. // Now it's questionable about where this should go - either after or before the push
  261. // I think in the interests of data safety - failures to push to the lfs should prevent
  262. // the merge as you can always remerge.
  263. if setting.LFS.StartServer {
  264. if err := LFSPush(tmpBasePath, mergeHeadSHA, mergeBaseSHA, pr); err != nil {
  265. return err
  266. }
  267. }
  268. headUser, err := models.GetUserByName(pr.HeadUserName)
  269. if err != nil {
  270. if !models.IsErrUserNotExist(err) {
  271. log.Error("Can't find user: %s for head repository - %v", pr.HeadUserName, err)
  272. return err
  273. }
  274. log.Error("Can't find user: %s for head repository - defaulting to doer: %s - %v", pr.HeadUserName, doer.Name, err)
  275. headUser = doer
  276. }
  277. env = models.FullPushingEnvironment(
  278. headUser,
  279. doer,
  280. pr.BaseRepo,
  281. pr.BaseRepo.Name,
  282. pr.ID,
  283. )
  284. // Push back to upstream.
  285. if err := git.NewCommand("push", "origin", baseBranch+":"+pr.BaseBranch).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, nil, &errbuf); err != nil {
  286. return fmt.Errorf("git push: %s", errbuf.String())
  287. }
  288. pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch)
  289. if err != nil {
  290. return fmt.Errorf("GetBranchCommit: %v", err)
  291. }
  292. pr.MergedUnix = timeutil.TimeStampNow()
  293. pr.Merger = doer
  294. pr.MergerID = doer.ID
  295. if err = pr.SetMerged(); err != nil {
  296. log.Error("setMerged [%d]: %v", pr.ID, err)
  297. }
  298. if err = models.MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  299. log.Error("MergePullRequestAction [%d]: %v", pr.ID, err)
  300. }
  301. // Reset cached commit count
  302. cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
  303. // Reload pull request information.
  304. if err = pr.LoadAttributes(); err != nil {
  305. log.Error("LoadAttributes: %v", err)
  306. return nil
  307. }
  308. mode, _ := models.AccessLevel(doer, pr.Issue.Repo)
  309. if err = models.PrepareWebhooks(pr.Issue.Repo, models.HookEventPullRequest, &api.PullRequestPayload{
  310. Action: api.HookIssueClosed,
  311. Index: pr.Index,
  312. PullRequest: pr.APIFormat(),
  313. Repository: pr.Issue.Repo.APIFormat(mode),
  314. Sender: doer.APIFormat(),
  315. }); err != nil {
  316. log.Error("PrepareWebhooks: %v", err)
  317. } else {
  318. go models.HookQueue.Add(pr.Issue.Repo.ID)
  319. }
  320. return nil
  321. }
  322. func getDiffTree(repoPath, baseBranch, headBranch string) (string, error) {
  323. getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
  324. var outbuf, errbuf strings.Builder
  325. // Compute the diff-tree for sparse-checkout
  326. if err := git.NewCommand("diff-tree", "--no-commit-id", "--name-only", "-r", "--root", baseBranch, headBranch, "--").RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil {
  327. return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String())
  328. }
  329. return outbuf.String(), nil
  330. }
  331. list, err := getDiffTreeFromBranch(repoPath, baseBranch, headBranch)
  332. if err != nil {
  333. return "", err
  334. }
  335. // Prefixing '/' for each entry, otherwise all files with the same name in subdirectories would be matched.
  336. out := bytes.Buffer{}
  337. scanner := bufio.NewScanner(strings.NewReader(list))
  338. for scanner.Scan() {
  339. fmt.Fprintf(&out, "/%s\n", scanner.Text())
  340. }
  341. return out.String(), nil
  342. }