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.

patch.go 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package files
  4. import (
  5. "context"
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/models"
  9. git_model "code.gitea.io/gitea/models/git"
  10. repo_model "code.gitea.io/gitea/models/repo"
  11. user_model "code.gitea.io/gitea/models/user"
  12. "code.gitea.io/gitea/modules/git"
  13. "code.gitea.io/gitea/modules/gitrepo"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/structs"
  16. asymkey_service "code.gitea.io/gitea/services/asymkey"
  17. )
  18. // ApplyDiffPatchOptions holds the repository diff patch update options
  19. type ApplyDiffPatchOptions struct {
  20. LastCommitID string
  21. OldBranch string
  22. NewBranch string
  23. Message string
  24. Content string
  25. SHA string
  26. Author *IdentityOptions
  27. Committer *IdentityOptions
  28. Dates *CommitDateOptions
  29. Signoff bool
  30. }
  31. // Validate validates the provided options
  32. func (opts *ApplyDiffPatchOptions) Validate(ctx context.Context, repo *repo_model.Repository, doer *user_model.User) error {
  33. // If no branch name is set, assume master
  34. if opts.OldBranch == "" {
  35. opts.OldBranch = repo.DefaultBranch
  36. }
  37. if opts.NewBranch == "" {
  38. opts.NewBranch = opts.OldBranch
  39. }
  40. gitRepo, closer, err := gitrepo.RepositoryFromContextOrOpen(ctx, repo)
  41. if err != nil {
  42. return err
  43. }
  44. defer closer.Close()
  45. // oldBranch must exist for this operation
  46. if _, err := gitRepo.GetBranch(opts.OldBranch); err != nil {
  47. return err
  48. }
  49. // A NewBranch can be specified for the patch to be applied to.
  50. // Check to make sure the branch does not already exist, otherwise we can't proceed.
  51. // If we aren't branching to a new branch, make sure user can commit to the given branch
  52. if opts.NewBranch != opts.OldBranch {
  53. existingBranch, err := gitRepo.GetBranch(opts.NewBranch)
  54. if existingBranch != nil {
  55. return git_model.ErrBranchAlreadyExists{
  56. BranchName: opts.NewBranch,
  57. }
  58. }
  59. if err != nil && !git.IsErrBranchNotExist(err) {
  60. return err
  61. }
  62. } else {
  63. protectedBranch, err := git_model.GetFirstMatchProtectedBranchRule(ctx, repo.ID, opts.OldBranch)
  64. if err != nil {
  65. return err
  66. }
  67. if protectedBranch != nil {
  68. protectedBranch.Repo = repo
  69. if !protectedBranch.CanUserPush(ctx, doer) {
  70. return models.ErrUserCannotCommit{
  71. UserName: doer.LowerName,
  72. }
  73. }
  74. }
  75. if protectedBranch != nil && protectedBranch.RequireSignedCommits {
  76. _, _, _, err := asymkey_service.SignCRUDAction(ctx, repo.RepoPath(), doer, repo.RepoPath(), opts.OldBranch)
  77. if err != nil {
  78. if !asymkey_service.IsErrWontSign(err) {
  79. return err
  80. }
  81. return models.ErrUserCannotCommit{
  82. UserName: doer.LowerName,
  83. }
  84. }
  85. }
  86. }
  87. return nil
  88. }
  89. // ApplyDiffPatch applies a patch to the given repository
  90. func ApplyDiffPatch(ctx context.Context, repo *repo_model.Repository, doer *user_model.User, opts *ApplyDiffPatchOptions) (*structs.FileResponse, error) {
  91. err := repo.MustNotBeArchived()
  92. if err != nil {
  93. return nil, err
  94. }
  95. if err := opts.Validate(ctx, repo, doer); err != nil {
  96. return nil, err
  97. }
  98. message := strings.TrimSpace(opts.Message)
  99. author, committer := GetAuthorAndCommitterUsers(opts.Author, opts.Committer, doer)
  100. t, err := NewTemporaryUploadRepository(ctx, repo)
  101. if err != nil {
  102. log.Error("NewTemporaryUploadRepository failed: %v", err)
  103. }
  104. defer t.Close()
  105. if err := t.Clone(opts.OldBranch, true); err != nil {
  106. return nil, err
  107. }
  108. if err := t.SetDefaultIndex(); err != nil {
  109. return nil, err
  110. }
  111. // Get the commit of the original branch
  112. commit, err := t.GetBranchCommit(opts.OldBranch)
  113. if err != nil {
  114. return nil, err // Couldn't get a commit for the branch
  115. }
  116. // Assigned LastCommitID in opts if it hasn't been set
  117. if opts.LastCommitID == "" {
  118. opts.LastCommitID = commit.ID.String()
  119. } else {
  120. lastCommitID, err := t.gitRepo.ConvertToGitID(opts.LastCommitID)
  121. if err != nil {
  122. return nil, fmt.Errorf("ApplyPatch: Invalid last commit ID: %w", err)
  123. }
  124. opts.LastCommitID = lastCommitID.String()
  125. if commit.ID.String() != opts.LastCommitID {
  126. return nil, models.ErrCommitIDDoesNotMatch{
  127. GivenCommitID: opts.LastCommitID,
  128. CurrentCommitID: opts.LastCommitID,
  129. }
  130. }
  131. }
  132. stdout := &strings.Builder{}
  133. stderr := &strings.Builder{}
  134. cmdApply := git.NewCommand(ctx, "apply", "--index", "--recount", "--cached", "--ignore-whitespace", "--whitespace=fix", "--binary")
  135. if git.DefaultFeatures().CheckVersionAtLeast("2.32") {
  136. cmdApply.AddArguments("-3")
  137. }
  138. if err := cmdApply.Run(&git.RunOpts{
  139. Dir: t.basePath,
  140. Stdout: stdout,
  141. Stderr: stderr,
  142. Stdin: strings.NewReader(opts.Content),
  143. }); err != nil {
  144. return nil, fmt.Errorf("Error: Stdout: %s\nStderr: %s\nErr: %w", stdout.String(), stderr.String(), err)
  145. }
  146. // Now write the tree
  147. treeHash, err := t.WriteTree()
  148. if err != nil {
  149. return nil, err
  150. }
  151. // Now commit the tree
  152. var commitHash string
  153. if opts.Dates != nil {
  154. commitHash, err = t.CommitTreeWithDate("HEAD", author, committer, treeHash, message, opts.Signoff, opts.Dates.Author, opts.Dates.Committer)
  155. } else {
  156. commitHash, err = t.CommitTree("HEAD", author, committer, treeHash, message, opts.Signoff)
  157. }
  158. if err != nil {
  159. return nil, err
  160. }
  161. // Then push this tree to NewBranch
  162. if err := t.Push(doer, commitHash, opts.NewBranch); err != nil {
  163. return nil, err
  164. }
  165. commit, err = t.GetCommit(commitHash)
  166. if err != nil {
  167. return nil, err
  168. }
  169. fileCommitResponse, _ := GetFileCommitResponse(repo, commit) // ok if fails, then will be nil
  170. verification := GetPayloadCommitVerification(ctx, commit)
  171. fileResponse := &structs.FileResponse{
  172. Commit: fileCommitResponse,
  173. Verification: verification,
  174. }
  175. return fileResponse, nil
  176. }