本站源代码
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

407 lines
15KB

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