Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

merge.go 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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/notification"
  21. "code.gitea.io/gitea/modules/references"
  22. "code.gitea.io/gitea/modules/setting"
  23. "code.gitea.io/gitea/modules/timeutil"
  24. issue_service "code.gitea.io/gitea/services/issue"
  25. "github.com/mcuadros/go-version"
  26. )
  27. // Merge merges pull request to base repository.
  28. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  29. func Merge(pr *models.PullRequest, doer *models.User, baseGitRepo *git.Repository, mergeStyle models.MergeStyle, message string) (err error) {
  30. binVersion, err := git.BinVersion()
  31. if err != nil {
  32. log.Error("git.BinVersion: %v", err)
  33. return fmt.Errorf("Unable to get git version: %v", err)
  34. }
  35. if err = pr.GetHeadRepo(); err != nil {
  36. log.Error("GetHeadRepo: %v", err)
  37. return fmt.Errorf("GetHeadRepo: %v", err)
  38. } else if err = pr.GetBaseRepo(); err != nil {
  39. log.Error("GetBaseRepo: %v", err)
  40. return fmt.Errorf("GetBaseRepo: %v", err)
  41. }
  42. prUnit, err := pr.BaseRepo.GetUnit(models.UnitTypePullRequests)
  43. if err != nil {
  44. log.Error("pr.BaseRepo.GetUnit(models.UnitTypePullRequests): %v", err)
  45. return err
  46. }
  47. prConfig := prUnit.PullRequestsConfig()
  48. if err := pr.CheckUserAllowedToMerge(doer); err != nil {
  49. log.Error("CheckUserAllowedToMerge(%v): %v", doer, err)
  50. return fmt.Errorf("CheckUserAllowedToMerge: %v", err)
  51. }
  52. // Check if merge style is correct and allowed
  53. if !prConfig.IsMergeStyleAllowed(mergeStyle) {
  54. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  55. }
  56. defer func() {
  57. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  58. }()
  59. // Clone base repo.
  60. tmpBasePath, err := models.CreateTemporaryPath("merge")
  61. if err != nil {
  62. log.Error("CreateTemporaryPath: %v", err)
  63. return err
  64. }
  65. defer func() {
  66. if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
  67. log.Error("Merge: RemoveTemporaryPath: %s", err)
  68. }
  69. }()
  70. headRepoPath := pr.HeadRepo.RepoPath()
  71. if err := git.InitRepository(tmpBasePath, false); err != nil {
  72. log.Error("git init tmpBasePath: %v", err)
  73. return err
  74. }
  75. remoteRepoName := "head_repo"
  76. baseBranch := "base"
  77. // Add head repo remote.
  78. addCacheRepo := func(staging, cache string) error {
  79. p := filepath.Join(staging, ".git", "objects", "info", "alternates")
  80. f, err := os.OpenFile(p, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
  81. if err != nil {
  82. log.Error("Could not create .git/objects/info/alternates file in %s: %v", staging, err)
  83. return err
  84. }
  85. defer f.Close()
  86. data := filepath.Join(cache, "objects")
  87. if _, err := fmt.Fprintln(f, data); err != nil {
  88. log.Error("Could not write to .git/objects/info/alternates file in %s: %v", staging, err)
  89. return err
  90. }
  91. return nil
  92. }
  93. if err := addCacheRepo(tmpBasePath, baseGitRepo.Path); err != nil {
  94. log.Error("Unable to add base repository to temporary repo [%s -> %s]: %v", pr.BaseRepo.FullName(), tmpBasePath, err)
  95. return fmt.Errorf("Unable to add base repository to temporary repo [%s -> tmpBasePath]: %v", pr.BaseRepo.FullName(), err)
  96. }
  97. var outbuf, errbuf strings.Builder
  98. if err := git.NewCommand("remote", "add", "-t", pr.BaseBranch, "-m", pr.BaseBranch, "origin", baseGitRepo.Path).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  99. log.Error("Unable to add base repository as origin [%s -> %s]: %v\n%s\n%s", pr.BaseRepo.FullName(), tmpBasePath, err, outbuf.String(), errbuf.String())
  100. return fmt.Errorf("Unable to add base repository as origin [%s -> tmpBasePath]: %v\n%s\n%s", pr.BaseRepo.FullName(), err, outbuf.String(), errbuf.String())
  101. }
  102. outbuf.Reset()
  103. errbuf.Reset()
  104. if err := git.NewCommand("fetch", "origin", "--no-tags", pr.BaseBranch+":"+baseBranch, pr.BaseBranch+":original_"+baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  105. log.Error("Unable to fetch origin base branch [%s:%s -> base, original_base in %s]: %v:\n%s\n%s", pr.BaseRepo.FullName(), pr.BaseBranch, tmpBasePath, err, outbuf.String(), errbuf.String())
  106. return fmt.Errorf("Unable to fetch origin base branch [%s:%s -> base, original_base in tmpBasePath]: %v\n%s\n%s", pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  107. }
  108. outbuf.Reset()
  109. errbuf.Reset()
  110. if err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  111. log.Error("Unable to set HEAD as base branch [%s]: %v\n%s\n%s", tmpBasePath, err, outbuf.String(), errbuf.String())
  112. return fmt.Errorf("Unable to set HEAD as base branch [tmpBasePath]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  113. }
  114. outbuf.Reset()
  115. errbuf.Reset()
  116. if err := addCacheRepo(tmpBasePath, headRepoPath); err != nil {
  117. log.Error("Unable to add head repository to temporary repo [%s -> %s]: %v", pr.HeadRepo.FullName(), tmpBasePath, err)
  118. return fmt.Errorf("Unable to head base repository to temporary repo [%s -> tmpBasePath]: %v", pr.HeadRepo.FullName(), err)
  119. }
  120. if err := git.NewCommand("remote", "add", remoteRepoName, headRepoPath).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  121. log.Error("Unable to add head repository as head_repo [%s -> %s]: %v\n%s\n%s", pr.HeadRepo.FullName(), tmpBasePath, err, outbuf.String(), errbuf.String())
  122. return fmt.Errorf("Unable to add head repository as head_repo [%s -> tmpBasePath]: %v\n%s\n%s", pr.HeadRepo.FullName(), err, outbuf.String(), errbuf.String())
  123. }
  124. outbuf.Reset()
  125. errbuf.Reset()
  126. trackingBranch := "tracking"
  127. // Fetch head branch
  128. if err := git.NewCommand("fetch", "--no-tags", remoteRepoName, pr.HeadBranch+":"+trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  129. log.Error("Unable to fetch head_repo head branch [%s:%s -> tracking in %s]: %v:\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, tmpBasePath, err, outbuf.String(), errbuf.String())
  130. return fmt.Errorf("Unable to fetch head_repo head branch [%s:%s -> tracking in tmpBasePath]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, err, outbuf.String(), errbuf.String())
  131. }
  132. outbuf.Reset()
  133. errbuf.Reset()
  134. stagingBranch := "staging"
  135. // Enable sparse-checkout
  136. sparseCheckoutList, err := getDiffTree(tmpBasePath, baseBranch, trackingBranch)
  137. if err != nil {
  138. log.Error("getDiffTree(%s, %s, %s): %v", tmpBasePath, baseBranch, trackingBranch, err)
  139. return fmt.Errorf("getDiffTree: %v", err)
  140. }
  141. infoPath := filepath.Join(tmpBasePath, ".git", "info")
  142. if err := os.MkdirAll(infoPath, 0700); err != nil {
  143. log.Error("Unable to create .git/info in %s: %v", tmpBasePath, err)
  144. return fmt.Errorf("Unable to create .git/info in tmpBasePath: %v", err)
  145. }
  146. sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout")
  147. if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil {
  148. log.Error("Unable to write .git/info/sparse-checkout file in %s: %v", tmpBasePath, err)
  149. return fmt.Errorf("Unable to write .git/info/sparse-checkout file in tmpBasePath: %v", err)
  150. }
  151. var gitConfigCommand func() *git.Command
  152. if version.Compare(binVersion, "1.8.0", ">=") {
  153. gitConfigCommand = func() *git.Command {
  154. return git.NewCommand("config", "--local")
  155. }
  156. } else {
  157. gitConfigCommand = func() *git.Command {
  158. return git.NewCommand("config")
  159. }
  160. }
  161. // Switch off LFS process (set required, clean and smudge here also)
  162. if err := gitConfigCommand().AddArguments("filter.lfs.process", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  163. log.Error("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  164. return fmt.Errorf("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  165. }
  166. outbuf.Reset()
  167. errbuf.Reset()
  168. if err := gitConfigCommand().AddArguments("filter.lfs.required", "false").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  169. log.Error("git config [filter.lfs.required -> <false> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  170. return fmt.Errorf("git config [filter.lfs.required -> <false> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  171. }
  172. outbuf.Reset()
  173. errbuf.Reset()
  174. if err := gitConfigCommand().AddArguments("filter.lfs.clean", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  175. log.Error("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  176. return fmt.Errorf("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  177. }
  178. outbuf.Reset()
  179. errbuf.Reset()
  180. if err := gitConfigCommand().AddArguments("filter.lfs.smudge", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  181. log.Error("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  182. return fmt.Errorf("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  183. }
  184. outbuf.Reset()
  185. errbuf.Reset()
  186. if err := gitConfigCommand().AddArguments("core.sparseCheckout", "true").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  187. log.Error("git config [core.sparseCheckout -> true ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  188. return fmt.Errorf("git config [core.sparsecheckout -> true]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  189. }
  190. outbuf.Reset()
  191. errbuf.Reset()
  192. // Read base branch index
  193. if err := git.NewCommand("read-tree", "HEAD").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  194. log.Error("git read-tree HEAD: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  195. return fmt.Errorf("Unable to read base branch in to the index: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  196. }
  197. outbuf.Reset()
  198. errbuf.Reset()
  199. // Determine if we should sign
  200. signArg := ""
  201. if version.Compare(binVersion, "1.7.9", ">=") {
  202. sign, keyID := pr.BaseRepo.SignMerge(doer, tmpBasePath, "HEAD", trackingBranch)
  203. if sign {
  204. signArg = "-S" + keyID
  205. } else if version.Compare(binVersion, "2.0.0", ">=") {
  206. signArg = "--no-gpg-sign"
  207. }
  208. }
  209. sig := doer.NewGitSig()
  210. commitTimeStr := time.Now().Format(time.RFC3339)
  211. // Because this may call hooks we should pass in the environment
  212. env := append(os.Environ(),
  213. "GIT_AUTHOR_NAME="+sig.Name,
  214. "GIT_AUTHOR_EMAIL="+sig.Email,
  215. "GIT_AUTHOR_DATE="+commitTimeStr,
  216. "GIT_COMMITTER_NAME="+sig.Name,
  217. "GIT_COMMITTER_EMAIL="+sig.Email,
  218. "GIT_COMMITTER_DATE="+commitTimeStr,
  219. )
  220. // Merge commits.
  221. switch mergeStyle {
  222. case models.MergeStyleMerge:
  223. cmd := git.NewCommand("merge", "--no-ff", "--no-commit", trackingBranch)
  224. if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil {
  225. log.Error("Unable to merge tracking into base: %v", err)
  226. return err
  227. }
  228. if err := commitAndSignNoAuthor(pr, message, signArg, tmpBasePath, env); err != nil {
  229. log.Error("Unable to make final commit: %v", err)
  230. return err
  231. }
  232. case models.MergeStyleRebase:
  233. fallthrough
  234. case models.MergeStyleRebaseMerge:
  235. // Checkout head branch
  236. if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  237. log.Error("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  238. return fmt.Errorf("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  239. }
  240. outbuf.Reset()
  241. errbuf.Reset()
  242. // Rebase before merging
  243. if err := git.NewCommand("rebase", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  244. // Rebase will leave a REBASE_HEAD file in .git if there is a conflict
  245. if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "REBASE_HEAD")); statErr == nil {
  246. // The original commit SHA1 that is failing will be in .git/rebase-apply/original-commit
  247. commitShaBytes, readErr := ioutil.ReadFile(filepath.Join(tmpBasePath, ".git", "rebase-apply", "original-commit"))
  248. if readErr != nil {
  249. // Abandon this attempt to handle the error
  250. log.Error("git rebase staging on to base [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  251. return fmt.Errorf("git rebase staging on to base [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  252. }
  253. log.Debug("RebaseConflict at %s [%s:%s -> %s:%s]: %v\n%s\n%s", strings.TrimSpace(string(commitShaBytes)), pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  254. return models.ErrRebaseConflicts{
  255. Style: mergeStyle,
  256. CommitSHA: strings.TrimSpace(string(commitShaBytes)),
  257. StdOut: outbuf.String(),
  258. StdErr: errbuf.String(),
  259. Err: err,
  260. }
  261. }
  262. log.Error("git rebase staging on to base [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  263. return fmt.Errorf("git rebase staging on to base [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  264. }
  265. outbuf.Reset()
  266. errbuf.Reset()
  267. // Checkout base branch again
  268. if err := git.NewCommand("checkout", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  269. log.Error("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  270. return fmt.Errorf("git checkout base prior to merge post staging rebase [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  271. }
  272. outbuf.Reset()
  273. errbuf.Reset()
  274. cmd := git.NewCommand("merge")
  275. if mergeStyle == models.MergeStyleRebase {
  276. cmd.AddArguments("--ff-only")
  277. } else {
  278. cmd.AddArguments("--no-ff", "--no-commit")
  279. }
  280. cmd.AddArguments(stagingBranch)
  281. // Prepare merge with commit
  282. if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil {
  283. log.Error("Unable to merge staging into base: %v", err)
  284. return err
  285. }
  286. if mergeStyle == models.MergeStyleRebaseMerge {
  287. if err := commitAndSignNoAuthor(pr, message, signArg, tmpBasePath, env); err != nil {
  288. log.Error("Unable to make final commit: %v", err)
  289. return err
  290. }
  291. }
  292. case models.MergeStyleSquash:
  293. // Merge with squash
  294. cmd := git.NewCommand("merge", "--squash", trackingBranch)
  295. if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil {
  296. log.Error("Unable to merge --squash tracking into base: %v", err)
  297. return err
  298. }
  299. sig := pr.Issue.Poster.NewGitSig()
  300. if signArg == "" {
  301. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  302. log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  303. return fmt.Errorf("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  304. }
  305. } else {
  306. if err := git.NewCommand("commit", signArg, fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  307. log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  308. return fmt.Errorf("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  309. }
  310. }
  311. outbuf.Reset()
  312. errbuf.Reset()
  313. default:
  314. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  315. }
  316. // OK we should cache our current head and origin/headbranch
  317. mergeHeadSHA, err := git.GetFullCommitID(tmpBasePath, "HEAD")
  318. if err != nil {
  319. return fmt.Errorf("Failed to get full commit id for HEAD: %v", err)
  320. }
  321. mergeBaseSHA, err := git.GetFullCommitID(tmpBasePath, "original_"+baseBranch)
  322. if err != nil {
  323. return fmt.Errorf("Failed to get full commit id for origin/%s: %v", pr.BaseBranch, err)
  324. }
  325. // Now it's questionable about where this should go - either after or before the push
  326. // I think in the interests of data safety - failures to push to the lfs should prevent
  327. // the merge as you can always remerge.
  328. if setting.LFS.StartServer {
  329. if err := LFSPush(tmpBasePath, mergeHeadSHA, mergeBaseSHA, pr); err != nil {
  330. return err
  331. }
  332. }
  333. var headUser *models.User
  334. err = pr.HeadRepo.GetOwner()
  335. if err != nil {
  336. if !models.IsErrUserNotExist(err) {
  337. log.Error("Can't find user: %d for head repository - %v", pr.HeadRepo.OwnerID, err)
  338. return err
  339. }
  340. log.Error("Can't find user: %d for head repository - defaulting to doer: %s - %v", pr.HeadRepo.OwnerID, doer.Name, err)
  341. headUser = doer
  342. } else {
  343. headUser = pr.HeadRepo.Owner
  344. }
  345. env = models.FullPushingEnvironment(
  346. headUser,
  347. doer,
  348. pr.BaseRepo,
  349. pr.BaseRepo.Name,
  350. pr.ID,
  351. )
  352. // Push back to upstream.
  353. if err := git.NewCommand("push", "origin", baseBranch+":"+pr.BaseBranch).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  354. if strings.Contains(errbuf.String(), "non-fast-forward") {
  355. return models.ErrMergePushOutOfDate{
  356. Style: mergeStyle,
  357. StdOut: outbuf.String(),
  358. StdErr: errbuf.String(),
  359. Err: err,
  360. }
  361. }
  362. return fmt.Errorf("git push: %s", errbuf.String())
  363. }
  364. outbuf.Reset()
  365. errbuf.Reset()
  366. pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch)
  367. if err != nil {
  368. return fmt.Errorf("GetBranchCommit: %v", err)
  369. }
  370. pr.MergedUnix = timeutil.TimeStampNow()
  371. pr.Merger = doer
  372. pr.MergerID = doer.ID
  373. if err = pr.SetMerged(); err != nil {
  374. log.Error("setMerged [%d]: %v", pr.ID, err)
  375. }
  376. notification.NotifyMergePullRequest(pr, doer, baseGitRepo)
  377. // Reset cached commit count
  378. cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
  379. // Resolve cross references
  380. refs, err := pr.ResolveCrossReferences()
  381. if err != nil {
  382. log.Error("ResolveCrossReferences: %v", err)
  383. return nil
  384. }
  385. for _, ref := range refs {
  386. if err = ref.LoadIssue(); err != nil {
  387. return err
  388. }
  389. if err = ref.Issue.LoadRepo(); err != nil {
  390. return err
  391. }
  392. close := (ref.RefAction == references.XRefActionCloses)
  393. if err = issue_service.ChangeStatus(ref.Issue, doer, close); err != nil {
  394. return err
  395. }
  396. }
  397. return nil
  398. }
  399. func commitAndSignNoAuthor(pr *models.PullRequest, message, signArg, tmpBasePath string, env []string) error {
  400. var outbuf, errbuf strings.Builder
  401. if signArg == "" {
  402. if err := git.NewCommand("commit", "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  403. log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  404. return fmt.Errorf("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  405. }
  406. } else {
  407. if err := git.NewCommand("commit", signArg, "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  408. log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  409. return fmt.Errorf("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  410. }
  411. }
  412. return nil
  413. }
  414. func runMergeCommand(pr *models.PullRequest, mergeStyle models.MergeStyle, cmd *git.Command, tmpBasePath string) error {
  415. var outbuf, errbuf strings.Builder
  416. if err := cmd.RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  417. // Merge will leave a MERGE_HEAD file in the .git folder if there is a conflict
  418. if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "MERGE_HEAD")); statErr == nil {
  419. // We have a merge conflict error
  420. log.Debug("MergeConflict [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  421. return models.ErrMergeConflicts{
  422. Style: mergeStyle,
  423. StdOut: outbuf.String(),
  424. StdErr: errbuf.String(),
  425. Err: err,
  426. }
  427. } else if strings.Contains(errbuf.String(), "refusing to merge unrelated histories") {
  428. log.Debug("MergeUnrelatedHistories [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  429. return models.ErrMergeUnrelatedHistories{
  430. Style: mergeStyle,
  431. StdOut: outbuf.String(),
  432. StdErr: errbuf.String(),
  433. Err: err,
  434. }
  435. }
  436. log.Error("git merge [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  437. return fmt.Errorf("git merge [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  438. }
  439. return nil
  440. }
  441. var escapedSymbols = regexp.MustCompile(`([*[?! \\])`)
  442. func getDiffTree(repoPath, baseBranch, headBranch string) (string, error) {
  443. getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
  444. var outbuf, errbuf strings.Builder
  445. // Compute the diff-tree for sparse-checkout
  446. if err := git.NewCommand("diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root", baseBranch, headBranch, "--").RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil {
  447. return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String())
  448. }
  449. return outbuf.String(), nil
  450. }
  451. scanNullTerminatedStrings := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  452. if atEOF && len(data) == 0 {
  453. return 0, nil, nil
  454. }
  455. if i := bytes.IndexByte(data, '\x00'); i >= 0 {
  456. return i + 1, data[0:i], nil
  457. }
  458. if atEOF {
  459. return len(data), data, nil
  460. }
  461. return 0, nil, nil
  462. }
  463. list, err := getDiffTreeFromBranch(repoPath, baseBranch, headBranch)
  464. if err != nil {
  465. return "", err
  466. }
  467. // Prefixing '/' for each entry, otherwise all files with the same name in subdirectories would be matched.
  468. out := bytes.Buffer{}
  469. scanner := bufio.NewScanner(strings.NewReader(list))
  470. scanner.Split(scanNullTerminatedStrings)
  471. for scanner.Scan() {
  472. filepath := scanner.Text()
  473. // escape '*', '?', '[', spaces and '!' prefix
  474. filepath = escapedSymbols.ReplaceAllString(filepath, `\$1`)
  475. // no necessary to escape the first '#' symbol because the first symbol is '/'
  476. fmt.Fprintf(&out, "/%s\n", filepath)
  477. }
  478. return out.String(), nil
  479. }