選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

merge.go 15KB

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