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

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