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.

475 lines
19 KiB

Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
  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.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 close != ref.Issue.IsClosed {
  333. if err = issue_service.ChangeStatus(ref.Issue, doer, close); err != nil {
  334. return err
  335. }
  336. }
  337. }
  338. return nil
  339. }
  340. func commitAndSignNoAuthor(pr *models.PullRequest, message, signArg, tmpBasePath string, env []string) error {
  341. var outbuf, errbuf strings.Builder
  342. if signArg == "" {
  343. if err := git.NewCommand("commit", "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  344. 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())
  345. 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())
  346. }
  347. } else {
  348. if err := git.NewCommand("commit", signArg, "-m", message).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil {
  349. 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())
  350. 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())
  351. }
  352. }
  353. return nil
  354. }
  355. func runMergeCommand(pr *models.PullRequest, mergeStyle models.MergeStyle, cmd *git.Command, tmpBasePath string) error {
  356. var outbuf, errbuf strings.Builder
  357. if err := cmd.RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil {
  358. // Merge will leave a MERGE_HEAD file in the .git folder if there is a conflict
  359. if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "MERGE_HEAD")); statErr == nil {
  360. // We have a merge conflict error
  361. 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())
  362. return models.ErrMergeConflicts{
  363. Style: mergeStyle,
  364. StdOut: outbuf.String(),
  365. StdErr: errbuf.String(),
  366. Err: err,
  367. }
  368. } else if strings.Contains(errbuf.String(), "refusing to merge unrelated histories") {
  369. 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())
  370. return models.ErrMergeUnrelatedHistories{
  371. Style: mergeStyle,
  372. StdOut: outbuf.String(),
  373. StdErr: errbuf.String(),
  374. Err: err,
  375. }
  376. }
  377. 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())
  378. 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())
  379. }
  380. return nil
  381. }
  382. var escapedSymbols = regexp.MustCompile(`([*[?! \\])`)
  383. func getDiffTree(repoPath, baseBranch, headBranch string) (string, error) {
  384. getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
  385. var outbuf, errbuf strings.Builder
  386. // Compute the diff-tree for sparse-checkout
  387. if err := git.NewCommand("diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root", baseBranch, headBranch, "--").RunInDirPipeline(repoPath, &outbuf, &errbuf); err != nil {
  388. return "", fmt.Errorf("git diff-tree [%s base:%s head:%s]: %s", repoPath, baseBranch, headBranch, errbuf.String())
  389. }
  390. return outbuf.String(), nil
  391. }
  392. scanNullTerminatedStrings := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  393. if atEOF && len(data) == 0 {
  394. return 0, nil, nil
  395. }
  396. if i := bytes.IndexByte(data, '\x00'); i >= 0 {
  397. return i + 1, data[0:i], nil
  398. }
  399. if atEOF {
  400. return len(data), data, nil
  401. }
  402. return 0, nil, nil
  403. }
  404. list, err := getDiffTreeFromBranch(repoPath, baseBranch, headBranch)
  405. if err != nil {
  406. return "", err
  407. }
  408. // Prefixing '/' for each entry, otherwise all files with the same name in subdirectories would be matched.
  409. out := bytes.Buffer{}
  410. scanner := bufio.NewScanner(strings.NewReader(list))
  411. scanner.Split(scanNullTerminatedStrings)
  412. for scanner.Scan() {
  413. filepath := scanner.Text()
  414. // escape '*', '?', '[', spaces and '!' prefix
  415. filepath = escapedSymbols.ReplaceAllString(filepath, `\$1`)
  416. // no necessary to escape the first '#' symbol because the first symbol is '/'
  417. fmt.Fprintf(&out, "/%s\n", filepath)
  418. }
  419. return out.String(), nil
  420. }