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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. "os"
  11. "path/filepath"
  12. "regexp"
  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/notification"
  20. "code.gitea.io/gitea/modules/references"
  21. "code.gitea.io/gitea/modules/setting"
  22. "code.gitea.io/gitea/modules/timeutil"
  23. issue_service "code.gitea.io/gitea/services/issue"
  24. )
  25. // Merge merges pull request to base repository.
  26. // Caller should check PR is ready to be merged (review and status checks)
  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. if err = pr.LoadHeadRepo(); err != nil {
  30. log.Error("LoadHeadRepo: %v", err)
  31. return fmt.Errorf("LoadHeadRepo: %v", err)
  32. } else if err = pr.LoadBaseRepo(); err != nil {
  33. log.Error("LoadBaseRepo: %v", err)
  34. return fmt.Errorf("LoadBaseRepo: %v", err)
  35. }
  36. prUnit, err := pr.BaseRepo.GetUnit(models.UnitTypePullRequests)
  37. if err != nil {
  38. log.Error("pr.BaseRepo.GetUnit(models.UnitTypePullRequests): %v", err)
  39. return err
  40. }
  41. prConfig := prUnit.PullRequestsConfig()
  42. // Check if merge style is correct and allowed
  43. if !prConfig.IsMergeStyleAllowed(mergeStyle) {
  44. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  45. }
  46. defer func() {
  47. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false, "", "")
  48. }()
  49. pr.MergedCommitID, err = rawMerge(pr, doer, mergeStyle, message)
  50. if err != nil {
  51. return err
  52. }
  53. pr.MergedUnix = timeutil.TimeStampNow()
  54. pr.Merger = doer
  55. pr.MergerID = doer.ID
  56. if _, err := pr.SetMerged(); err != nil {
  57. log.Error("setMerged [%d]: %v", pr.ID, err)
  58. }
  59. if err := pr.LoadIssue(); err != nil {
  60. log.Error("loadIssue [%d]: %v", pr.ID, err)
  61. }
  62. if err := pr.Issue.LoadRepo(); err != nil {
  63. log.Error("loadRepo for issue [%d]: %v", pr.ID, err)
  64. }
  65. if err := pr.Issue.Repo.GetOwner(); err != nil {
  66. log.Error("GetOwner for issue repo [%d]: %v", pr.ID, err)
  67. }
  68. notification.NotifyMergePullRequest(pr, doer)
  69. // Reset cached commit count
  70. cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
  71. // Resolve cross references
  72. refs, err := pr.ResolveCrossReferences()
  73. if err != nil {
  74. log.Error("ResolveCrossReferences: %v", err)
  75. return nil
  76. }
  77. for _, ref := range refs {
  78. if err = ref.LoadIssue(); err != nil {
  79. return err
  80. }
  81. if err = ref.Issue.LoadRepo(); err != nil {
  82. return err
  83. }
  84. close := ref.RefAction == references.XRefActionCloses
  85. if close != ref.Issue.IsClosed {
  86. if err = issue_service.ChangeStatus(ref.Issue, doer, close); err != nil {
  87. return err
  88. }
  89. }
  90. }
  91. return nil
  92. }
  93. // rawMerge perform the merge operation without changing any pull information in database
  94. func rawMerge(pr *models.PullRequest, doer *models.User, mergeStyle models.MergeStyle, message string) (string, error) {
  95. err := git.LoadGitVersion()
  96. if err != nil {
  97. log.Error("git.LoadGitVersion: %v", err)
  98. return "", fmt.Errorf("Unable to get git version: %v", err)
  99. }
  100. // Clone base repo.
  101. tmpBasePath, err := createTemporaryRepo(pr)
  102. if err != nil {
  103. log.Error("CreateTemporaryPath: %v", err)
  104. return "", err
  105. }
  106. defer func() {
  107. if err := models.RemoveTemporaryPath(tmpBasePath); err != nil {
  108. log.Error("Merge: RemoveTemporaryPath: %s", err)
  109. }
  110. }()
  111. baseBranch := "base"
  112. trackingBranch := "tracking"
  113. stagingBranch := "staging"
  114. var outbuf, errbuf strings.Builder
  115. // Enable sparse-checkout
  116. sparseCheckoutList, err := getDiffTree(tmpBasePath, baseBranch, trackingBranch)
  117. if err != nil {
  118. log.Error("getDiffTree(%s, %s, %s): %v", tmpBasePath, baseBranch, trackingBranch, err)
  119. return "", fmt.Errorf("getDiffTree: %v", err)
  120. }
  121. infoPath := filepath.Join(tmpBasePath, ".git", "info")
  122. if err := os.MkdirAll(infoPath, 0700); err != nil {
  123. log.Error("Unable to create .git/info in %s: %v", tmpBasePath, err)
  124. return "", fmt.Errorf("Unable to create .git/info in tmpBasePath: %v", err)
  125. }
  126. sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout")
  127. if err := os.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil {
  128. log.Error("Unable to write .git/info/sparse-checkout file in %s: %v", tmpBasePath, err)
  129. return "", fmt.Errorf("Unable to write .git/info/sparse-checkout file in tmpBasePath: %v", err)
  130. }
  131. var gitConfigCommand func() *git.Command
  132. if git.CheckGitVersionAtLeast("1.8.0") == nil {
  133. gitConfigCommand = func() *git.Command {
  134. return git.NewCommand("config", "--local")
  135. }
  136. } else {
  137. gitConfigCommand = func() *git.Command {
  138. return git.NewCommand("config")
  139. }
  140. }
  141. // Switch off LFS process (set required, clean and smudge here also)
  142. if err := gitConfigCommand().AddArguments("filter.lfs.process", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  143. log.Error("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  144. return "", fmt.Errorf("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  145. }
  146. outbuf.Reset()
  147. errbuf.Reset()
  148. if err := gitConfigCommand().AddArguments("filter.lfs.required", "false").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  149. log.Error("git config [filter.lfs.required -> <false> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  150. return "", fmt.Errorf("git config [filter.lfs.required -> <false> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  151. }
  152. outbuf.Reset()
  153. errbuf.Reset()
  154. if err := gitConfigCommand().AddArguments("filter.lfs.clean", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  155. log.Error("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  156. return "", fmt.Errorf("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  157. }
  158. outbuf.Reset()
  159. errbuf.Reset()
  160. if err := gitConfigCommand().AddArguments("filter.lfs.smudge", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  161. log.Error("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  162. return "", fmt.Errorf("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  163. }
  164. outbuf.Reset()
  165. errbuf.Reset()
  166. if err := gitConfigCommand().AddArguments("core.sparseCheckout", "true").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  167. log.Error("git config [core.sparseCheckout -> true ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  168. return "", fmt.Errorf("git config [core.sparsecheckout -> true]: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  169. }
  170. outbuf.Reset()
  171. errbuf.Reset()
  172. // Read base branch index
  173. if err := git.NewCommand("read-tree", "HEAD").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  174. log.Error("git read-tree HEAD: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  175. return "", fmt.Errorf("Unable to read base branch in to the index: %v\n%s\n%s", err, outbuf.String(), errbuf.String())
  176. }
  177. outbuf.Reset()
  178. errbuf.Reset()
  179. sig := doer.NewGitSig()
  180. committer := sig
  181. // Determine if we should sign
  182. signArg := ""
  183. if git.CheckGitVersionAtLeast("1.7.9") == nil {
  184. sign, keyID, signer, _ := pr.SignMerge(doer, tmpBasePath, "HEAD", trackingBranch)
  185. if sign {
  186. signArg = "-S" + keyID
  187. if pr.BaseRepo.GetTrustModel() == models.CommitterTrustModel || pr.BaseRepo.GetTrustModel() == models.CollaboratorCommitterTrustModel {
  188. committer = signer
  189. }
  190. } else if git.CheckGitVersionAtLeast("2.0.0") == nil {
  191. signArg = "--no-gpg-sign"
  192. }
  193. }
  194. commitTimeStr := time.Now().Format(time.RFC3339)
  195. // Because this may call hooks we should pass in the environment
  196. env := append(os.Environ(),
  197. "GIT_AUTHOR_NAME="+sig.Name,
  198. "GIT_AUTHOR_EMAIL="+sig.Email,
  199. "GIT_AUTHOR_DATE="+commitTimeStr,
  200. "GIT_COMMITTER_NAME="+committer.Name,
  201. "GIT_COMMITTER_EMAIL="+committer.Email,
  202. "GIT_COMMITTER_DATE="+commitTimeStr,
  203. )
  204. // Merge commits.
  205. switch mergeStyle {
  206. case models.MergeStyleMerge:
  207. cmd := git.NewCommand("merge", "--no-ff", "--no-commit", trackingBranch)
  208. if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil {
  209. log.Error("Unable to merge tracking into base: %v", err)
  210. return "", err
  211. }
  212. if err := commitAndSignNoAuthor(pr, message, signArg, tmpBasePath, env); err != nil {
  213. log.Error("Unable to make final commit: %v", err)
  214. return "", err
  215. }
  216. case models.MergeStyleRebase:
  217. fallthrough
  218. case models.MergeStyleRebaseUpdate:
  219. fallthrough
  220. case models.MergeStyleRebaseMerge:
  221. // Checkout head branch
  222. if err := git.NewCommand("checkout", "-b", stagingBranch, trackingBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  223. 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())
  224. 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())
  225. }
  226. outbuf.Reset()
  227. errbuf.Reset()
  228. // Rebase before merging
  229. if err := git.NewCommand("rebase", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  230. // Rebase will leave a REBASE_HEAD file in .git if there is a conflict
  231. if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "REBASE_HEAD")); statErr == nil {
  232. var commitSha string
  233. ok := false
  234. failingCommitPaths := []string{
  235. filepath.Join(tmpBasePath, ".git", "rebase-apply", "original-commit"), // Git < 2.26
  236. filepath.Join(tmpBasePath, ".git", "rebase-merge", "stopped-sha"), // Git >= 2.26
  237. }
  238. for _, failingCommitPath := range failingCommitPaths {
  239. if _, statErr := os.Stat(filepath.Join(failingCommitPath)); statErr == nil {
  240. commitShaBytes, readErr := os.ReadFile(filepath.Join(failingCommitPath))
  241. if readErr != nil {
  242. // Abandon this attempt to handle the error
  243. 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())
  244. 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())
  245. }
  246. commitSha = strings.TrimSpace(string(commitShaBytes))
  247. ok = true
  248. break
  249. }
  250. }
  251. if !ok {
  252. log.Error("Unable to determine failing commit sha for this rebase message. Cannot cast as models.ErrRebaseConflicts.")
  253. 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())
  254. 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())
  255. }
  256. log.Debug("RebaseConflict at %s [%s:%s -> %s:%s]: %v\n%s\n%s", commitSha, pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
  257. return "", models.ErrRebaseConflicts{
  258. Style: mergeStyle,
  259. CommitSHA: commitSha,
  260. StdOut: outbuf.String(),
  261. StdErr: errbuf.String(),
  262. Err: err,
  263. }
  264. }
  265. 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())
  266. 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())
  267. }
  268. outbuf.Reset()
  269. errbuf.Reset()
  270. // not need merge, just update by rebase. so skip
  271. if mergeStyle == models.MergeStyleRebaseUpdate {
  272. break
  273. }
  274. // Checkout base branch again
  275. if err := git.NewCommand("checkout", baseBranch).RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  276. 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())
  277. 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())
  278. }
  279. outbuf.Reset()
  280. errbuf.Reset()
  281. cmd := git.NewCommand("merge")
  282. if mergeStyle == models.MergeStyleRebase {
  283. cmd.AddArguments("--ff-only")
  284. } else {
  285. cmd.AddArguments("--no-ff", "--no-commit")
  286. }
  287. cmd.AddArguments(stagingBranch)
  288. // Prepare merge with commit
  289. if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil {
  290. log.Error("Unable to merge staging into base: %v", err)
  291. return "", err
  292. }
  293. if mergeStyle == models.MergeStyleRebaseMerge {
  294. if err := commitAndSignNoAuthor(pr, message, signArg, tmpBasePath, env); err != nil {
  295. log.Error("Unable to make final commit: %v", err)
  296. return "", err
  297. }
  298. }
  299. case models.MergeStyleSquash:
  300. // Merge with squash
  301. cmd := git.NewCommand("merge", "--squash", trackingBranch)
  302. if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil {
  303. log.Error("Unable to merge --squash tracking into base: %v", err)
  304. return "", err
  305. }
  306. if err = pr.Issue.LoadPoster(); err != nil {
  307. log.Error("LoadPoster: %v", err)
  308. return "", fmt.Errorf("LoadPoster: %v", err)
  309. }
  310. sig := pr.Issue.Poster.NewGitSig()
  311. if signArg == "" {
  312. if err := git.NewCommand("commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  313. 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())
  314. 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())
  315. }
  316. } else {
  317. if committer != sig {
  318. // add trailer
  319. message += fmt.Sprintf("\nCo-authored-by: %s\nCo-committed-by: %s\n", sig.String(), sig.String())
  320. }
  321. 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 {
  322. 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())
  323. 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())
  324. }
  325. }
  326. outbuf.Reset()
  327. errbuf.Reset()
  328. default:
  329. return "", models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: mergeStyle}
  330. }
  331. // OK we should cache our current head and origin/headbranch
  332. mergeHeadSHA, err := git.GetFullCommitID(tmpBasePath, "HEAD")
  333. if err != nil {
  334. return "", fmt.Errorf("Failed to get full commit id for HEAD: %v", err)
  335. }
  336. mergeBaseSHA, err := git.GetFullCommitID(tmpBasePath, "original_"+baseBranch)
  337. if err != nil {
  338. return "", fmt.Errorf("Failed to get full commit id for origin/%s: %v", pr.BaseBranch, err)
  339. }
  340. mergeCommitID, err := git.GetFullCommitID(tmpBasePath, baseBranch)
  341. if err != nil {
  342. return "", fmt.Errorf("Failed to get full commit id for the new merge: %v", err)
  343. }
  344. // Now it's questionable about where this should go - either after or before the push
  345. // I think in the interests of data safety - failures to push to the lfs should prevent
  346. // the merge as you can always remerge.
  347. if setting.LFS.StartServer {
  348. if err := LFSPush(tmpBasePath, mergeHeadSHA, mergeBaseSHA, pr); err != nil {
  349. return "", err
  350. }
  351. }
  352. var headUser *models.User
  353. err = pr.HeadRepo.GetOwner()
  354. if err != nil {
  355. if !models.IsErrUserNotExist(err) {
  356. log.Error("Can't find user: %d for head repository - %v", pr.HeadRepo.OwnerID, err)
  357. return "", err
  358. }
  359. log.Error("Can't find user: %d for head repository - defaulting to doer: %s - %v", pr.HeadRepo.OwnerID, doer.Name, err)
  360. headUser = doer
  361. } else {
  362. headUser = pr.HeadRepo.Owner
  363. }
  364. env = models.FullPushingEnvironment(
  365. headUser,
  366. doer,
  367. pr.BaseRepo,
  368. pr.BaseRepo.Name,
  369. pr.ID,
  370. )
  371. var pushCmd *git.Command
  372. if mergeStyle == models.MergeStyleRebaseUpdate {
  373. // force push the rebase result to head brach
  374. pushCmd = git.NewCommand("push", "-f", "head_repo", stagingBranch+":refs/heads/"+pr.HeadBranch)
  375. } else {
  376. pushCmd = git.NewCommand("push", "origin", baseBranch+":refs/heads/"+pr.BaseBranch)
  377. }
  378. // Push back to upstream.
  379. if err := pushCmd.RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  380. if strings.Contains(errbuf.String(), "non-fast-forward") {
  381. return "", &git.ErrPushOutOfDate{
  382. StdOut: outbuf.String(),
  383. StdErr: errbuf.String(),
  384. Err: err,
  385. }
  386. } else if strings.Contains(errbuf.String(), "! [remote rejected]") {
  387. err := &git.ErrPushRejected{
  388. StdOut: outbuf.String(),
  389. StdErr: errbuf.String(),
  390. Err: err,
  391. }
  392. err.GenerateMessage()
  393. return "", err
  394. }
  395. return "", fmt.Errorf("git push: %s", errbuf.String())
  396. }
  397. outbuf.Reset()
  398. errbuf.Reset()
  399. return mergeCommitID, nil
  400. }
  401. func commitAndSignNoAuthor(pr *models.PullRequest, message, signArg, tmpBasePath string, env []string) error {
  402. var outbuf, errbuf strings.Builder
  403. if signArg == "" {
  404. if err := git.NewCommand("commit", "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  405. 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())
  406. 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())
  407. }
  408. } else {
  409. if err := git.NewCommand("commit", signArg, "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  410. 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())
  411. 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())
  412. }
  413. }
  414. return nil
  415. }
  416. func runMergeCommand(pr *models.PullRequest, mergeStyle models.MergeStyle, cmd *git.Command, tmpBasePath string) error {
  417. var outbuf, errbuf strings.Builder
  418. if err := cmd.RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  419. // Merge will leave a MERGE_HEAD file in the .git folder if there is a conflict
  420. if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "MERGE_HEAD")); statErr == nil {
  421. // We have a merge conflict error
  422. 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())
  423. return models.ErrMergeConflicts{
  424. Style: mergeStyle,
  425. StdOut: outbuf.String(),
  426. StdErr: errbuf.String(),
  427. Err: err,
  428. }
  429. } else if strings.Contains(errbuf.String(), "refusing to merge unrelated histories") {
  430. 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())
  431. return models.ErrMergeUnrelatedHistories{
  432. Style: mergeStyle,
  433. StdOut: outbuf.String(),
  434. StdErr: errbuf.String(),
  435. Err: err,
  436. }
  437. }
  438. 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())
  439. 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())
  440. }
  441. return nil
  442. }
  443. var escapedSymbols = regexp.MustCompile(`([*[?! \\])`)
  444. func getDiffTree(repoPath, baseBranch, headBranch string) (string, error) {
  445. getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
  446. var outbuf, errbuf strings.Builder
  447. // Compute the diff-tree for sparse-checkout
  448. if err := git.NewCommand("diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root", baseBranch, headBranch, "--").RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil {
  449. return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String())
  450. }
  451. return outbuf.String(), nil
  452. }
  453. scanNullTerminatedStrings := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  454. if atEOF && len(data) == 0 {
  455. return 0, nil, nil
  456. }
  457. if i := bytes.IndexByte(data, '\x00'); i >= 0 {
  458. return i + 1, data[0:i], nil
  459. }
  460. if atEOF {
  461. return len(data), data, nil
  462. }
  463. return 0, nil, nil
  464. }
  465. list, err := getDiffTreeFromBranch(repoPath, baseBranch, headBranch)
  466. if err != nil {
  467. return "", err
  468. }
  469. // Prefixing '/' for each entry, otherwise all files with the same name in subdirectories would be matched.
  470. out := bytes.Buffer{}
  471. scanner := bufio.NewScanner(strings.NewReader(list))
  472. scanner.Split(scanNullTerminatedStrings)
  473. for scanner.Scan() {
  474. filepath := scanner.Text()
  475. // escape '*', '?', '[', spaces and '!' prefix
  476. filepath = escapedSymbols.ReplaceAllString(filepath, `\$1`)
  477. // no necessary to escape the first '#' symbol because the first symbol is '/'
  478. fmt.Fprintf(&out, "/%s\n", filepath)
  479. }
  480. return out.String(), nil
  481. }
  482. // IsSignedIfRequired check if merge will be signed if required
  483. func IsSignedIfRequired(pr *models.PullRequest, doer *models.User) (bool, error) {
  484. if err := pr.LoadProtectedBranch(); err != nil {
  485. return false, err
  486. }
  487. if pr.ProtectedBranch == nil || !pr.ProtectedBranch.RequireSignedCommits {
  488. return true, nil
  489. }
  490. sign, _, _, err := pr.SignMerge(doer, pr.BaseRepo.RepoPath(), pr.BaseBranch, pr.GetGitRefName())
  491. return sign, err
  492. }
  493. // IsUserAllowedToMerge check if user is allowed to merge PR with given permissions and branch protections
  494. func IsUserAllowedToMerge(pr *models.PullRequest, p models.Permission, user *models.User) (bool, error) {
  495. if user == nil {
  496. return false, nil
  497. }
  498. err := pr.LoadProtectedBranch()
  499. if err != nil {
  500. return false, err
  501. }
  502. if (p.CanWrite(models.UnitTypeCode) && pr.ProtectedBranch == nil) || (pr.ProtectedBranch != nil && pr.ProtectedBranch.IsUserMergeWhitelisted(user.ID, p)) {
  503. return true, nil
  504. }
  505. return false, nil
  506. }
  507. // CheckPRReadyToMerge checks whether the PR is ready to be merged (reviews and status checks)
  508. func CheckPRReadyToMerge(pr *models.PullRequest, skipProtectedFilesCheck bool) (err error) {
  509. if err = pr.LoadBaseRepo(); err != nil {
  510. return fmt.Errorf("LoadBaseRepo: %v", err)
  511. }
  512. if err = pr.LoadProtectedBranch(); err != nil {
  513. return fmt.Errorf("LoadProtectedBranch: %v", err)
  514. }
  515. if pr.ProtectedBranch == nil {
  516. return nil
  517. }
  518. isPass, err := IsPullCommitStatusPass(pr)
  519. if err != nil {
  520. return err
  521. }
  522. if !isPass {
  523. return models.ErrNotAllowedToMerge{
  524. Reason: "Not all required status checks successful",
  525. }
  526. }
  527. if !pr.ProtectedBranch.HasEnoughApprovals(pr) {
  528. return models.ErrNotAllowedToMerge{
  529. Reason: "Does not have enough approvals",
  530. }
  531. }
  532. if pr.ProtectedBranch.MergeBlockedByRejectedReview(pr) {
  533. return models.ErrNotAllowedToMerge{
  534. Reason: "There are requested changes",
  535. }
  536. }
  537. if pr.ProtectedBranch.MergeBlockedByOfficialReviewRequests(pr) {
  538. return models.ErrNotAllowedToMerge{
  539. Reason: "There are official review requests",
  540. }
  541. }
  542. if pr.ProtectedBranch.MergeBlockedByOutdatedBranch(pr) {
  543. return models.ErrNotAllowedToMerge{
  544. Reason: "The head branch is behind the base branch",
  545. }
  546. }
  547. if skipProtectedFilesCheck {
  548. return nil
  549. }
  550. if pr.ProtectedBranch.MergeBlockedByProtectedFiles(pr) {
  551. return models.ErrNotAllowedToMerge{
  552. Reason: "Changed protected files",
  553. }
  554. }
  555. return nil
  556. }
  557. // MergedManually mark pr as merged manually
  558. func MergedManually(pr *models.PullRequest, doer *models.User, baseGitRepo *git.Repository, commitID string) (err error) {
  559. prUnit, err := pr.BaseRepo.GetUnit(models.UnitTypePullRequests)
  560. if err != nil {
  561. return
  562. }
  563. prConfig := prUnit.PullRequestsConfig()
  564. // Check if merge style is correct and allowed
  565. if !prConfig.IsMergeStyleAllowed(models.MergeStyleManuallyMerged) {
  566. return models.ErrInvalidMergeStyle{ID: pr.BaseRepo.ID, Style: models.MergeStyleManuallyMerged}
  567. }
  568. if len(commitID) < 40 {
  569. return fmt.Errorf("Wrong commit ID")
  570. }
  571. commit, err := baseGitRepo.GetCommit(commitID)
  572. if err != nil {
  573. if git.IsErrNotExist(err) {
  574. return fmt.Errorf("Wrong commit ID")
  575. }
  576. return
  577. }
  578. ok, err := baseGitRepo.IsCommitInBranch(commitID, pr.BaseBranch)
  579. if err != nil {
  580. return
  581. }
  582. if !ok {
  583. return fmt.Errorf("Wrong commit ID")
  584. }
  585. pr.MergedCommitID = commitID
  586. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  587. pr.Status = models.PullRequestStatusManuallyMerged
  588. pr.Merger = doer
  589. pr.MergerID = doer.ID
  590. merged := false
  591. if merged, err = pr.SetMerged(); err != nil {
  592. return
  593. } else if !merged {
  594. return fmt.Errorf("SetMerged failed")
  595. }
  596. notification.NotifyMergePullRequest(pr, doer)
  597. log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
  598. return nil
  599. }