gitea源码

repo_tree.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package git
  5. import (
  6. "bytes"
  7. "os"
  8. "strings"
  9. "time"
  10. "code.gitea.io/gitea/modules/git/gitcmd"
  11. )
  12. // CommitTreeOpts represents the possible options to CommitTree
  13. type CommitTreeOpts struct {
  14. Parents []string
  15. Message string
  16. Key *SigningKey
  17. NoGPGSign bool
  18. AlwaysSign bool
  19. }
  20. // CommitTree creates a commit from a given tree id for the user with provided message
  21. func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opts CommitTreeOpts) (ObjectID, error) {
  22. commitTimeStr := time.Now().Format(time.RFC3339)
  23. // Because this may call hooks we should pass in the environment
  24. env := append(os.Environ(),
  25. "GIT_AUTHOR_NAME="+author.Name,
  26. "GIT_AUTHOR_EMAIL="+author.Email,
  27. "GIT_AUTHOR_DATE="+commitTimeStr,
  28. "GIT_COMMITTER_NAME="+committer.Name,
  29. "GIT_COMMITTER_EMAIL="+committer.Email,
  30. "GIT_COMMITTER_DATE="+commitTimeStr,
  31. )
  32. cmd := gitcmd.NewCommand("commit-tree").AddDynamicArguments(tree.ID.String())
  33. for _, parent := range opts.Parents {
  34. cmd.AddArguments("-p").AddDynamicArguments(parent)
  35. }
  36. messageBytes := new(bytes.Buffer)
  37. _, _ = messageBytes.WriteString(opts.Message)
  38. _, _ = messageBytes.WriteString("\n")
  39. if opts.Key != nil {
  40. if opts.Key.Format != "" {
  41. cmd.AddConfig("gpg.format", opts.Key.Format)
  42. }
  43. cmd.AddOptionFormat("-S%s", opts.Key.KeyID)
  44. } else if opts.AlwaysSign {
  45. cmd.AddOptionFormat("-S")
  46. }
  47. if opts.NoGPGSign {
  48. cmd.AddArguments("--no-gpg-sign")
  49. }
  50. stdout := new(bytes.Buffer)
  51. stderr := new(bytes.Buffer)
  52. err := cmd.Run(repo.Ctx, &gitcmd.RunOpts{
  53. Env: env,
  54. Dir: repo.Path,
  55. Stdin: messageBytes,
  56. Stdout: stdout,
  57. Stderr: stderr,
  58. })
  59. if err != nil {
  60. return nil, gitcmd.ConcatenateError(err, stderr.String())
  61. }
  62. return NewIDFromString(strings.TrimSpace(stdout.String()))
  63. }