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

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