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

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