gitea源码

temp_repo.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package files
  4. import (
  5. "bytes"
  6. "context"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "os"
  11. "regexp"
  12. "strings"
  13. "time"
  14. repo_model "code.gitea.io/gitea/models/repo"
  15. user_model "code.gitea.io/gitea/models/user"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/git/gitcmd"
  18. "code.gitea.io/gitea/modules/log"
  19. repo_module "code.gitea.io/gitea/modules/repository"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/util"
  22. asymkey_service "code.gitea.io/gitea/services/asymkey"
  23. "code.gitea.io/gitea/services/gitdiff"
  24. )
  25. // TemporaryUploadRepository is a type to wrap our upload repositories as a shallow clone
  26. type TemporaryUploadRepository struct {
  27. repo *repo_model.Repository
  28. gitRepo *git.Repository
  29. basePath string
  30. cleanup func()
  31. }
  32. // NewTemporaryUploadRepository creates a new temporary upload repository
  33. func NewTemporaryUploadRepository(repo *repo_model.Repository) (*TemporaryUploadRepository, error) {
  34. basePath, cleanup, err := repo_module.CreateTemporaryPath("upload")
  35. if err != nil {
  36. return nil, err
  37. }
  38. t := &TemporaryUploadRepository{repo: repo, basePath: basePath, cleanup: cleanup}
  39. return t, nil
  40. }
  41. // Close the repository cleaning up all files
  42. func (t *TemporaryUploadRepository) Close() {
  43. defer t.gitRepo.Close()
  44. if t.cleanup != nil {
  45. t.cleanup()
  46. }
  47. }
  48. // Clone the base repository to our path and set branch as the HEAD
  49. func (t *TemporaryUploadRepository) Clone(ctx context.Context, branch string, bare bool) error {
  50. cmd := gitcmd.NewCommand("clone", "-s", "-b").AddDynamicArguments(branch, t.repo.RepoPath(), t.basePath)
  51. if bare {
  52. cmd.AddArguments("--bare")
  53. }
  54. if _, _, err := cmd.RunStdString(ctx, nil); err != nil {
  55. stderr := err.Error()
  56. if matched, _ := regexp.MatchString(".*Remote branch .* not found in upstream origin.*", stderr); matched {
  57. return git.ErrBranchNotExist{
  58. Name: branch,
  59. }
  60. } else if matched, _ := regexp.MatchString(".* repository .* does not exist.*", stderr); matched {
  61. return repo_model.ErrRepoNotExist{
  62. ID: t.repo.ID,
  63. UID: t.repo.OwnerID,
  64. OwnerName: t.repo.OwnerName,
  65. Name: t.repo.Name,
  66. }
  67. }
  68. return fmt.Errorf("Clone: %w %s", err, stderr)
  69. }
  70. gitRepo, err := git.OpenRepository(ctx, t.basePath)
  71. if err != nil {
  72. return err
  73. }
  74. t.gitRepo = gitRepo
  75. return nil
  76. }
  77. // Init the repository
  78. func (t *TemporaryUploadRepository) Init(ctx context.Context, objectFormatName string) error {
  79. if err := git.InitRepository(ctx, t.basePath, false, objectFormatName); err != nil {
  80. return err
  81. }
  82. gitRepo, err := git.OpenRepository(ctx, t.basePath)
  83. if err != nil {
  84. return err
  85. }
  86. t.gitRepo = gitRepo
  87. return nil
  88. }
  89. // SetDefaultIndex sets the git index to our HEAD
  90. func (t *TemporaryUploadRepository) SetDefaultIndex(ctx context.Context) error {
  91. if _, _, err := gitcmd.NewCommand("read-tree", "HEAD").RunStdString(ctx, &gitcmd.RunOpts{Dir: t.basePath}); err != nil {
  92. return fmt.Errorf("SetDefaultIndex: %w", err)
  93. }
  94. return nil
  95. }
  96. // RefreshIndex looks at the current index and checks to see if merges or updates are needed by checking stat() information.
  97. func (t *TemporaryUploadRepository) RefreshIndex(ctx context.Context) error {
  98. if _, _, err := gitcmd.NewCommand("update-index", "--refresh").RunStdString(ctx, &gitcmd.RunOpts{Dir: t.basePath}); err != nil {
  99. return fmt.Errorf("RefreshIndex: %w", err)
  100. }
  101. return nil
  102. }
  103. // LsFiles checks if the given filename arguments are in the index
  104. func (t *TemporaryUploadRepository) LsFiles(ctx context.Context, filenames ...string) ([]string, error) {
  105. stdOut := new(bytes.Buffer)
  106. stdErr := new(bytes.Buffer)
  107. if err := gitcmd.NewCommand("ls-files", "-z").AddDashesAndList(filenames...).
  108. Run(ctx, &gitcmd.RunOpts{
  109. Dir: t.basePath,
  110. Stdout: stdOut,
  111. Stderr: stdErr,
  112. }); err != nil {
  113. log.Error("Unable to run git ls-files for temporary repo: %s (%s) Error: %v\nstdout: %s\nstderr: %s", t.repo.FullName(), t.basePath, err, stdOut.String(), stdErr.String())
  114. err = fmt.Errorf("Unable to run git ls-files for temporary repo of: %s Error: %w\nstdout: %s\nstderr: %s", t.repo.FullName(), err, stdOut.String(), stdErr.String())
  115. return nil, err
  116. }
  117. fileList := make([]string, 0, len(filenames))
  118. for line := range bytes.SplitSeq(stdOut.Bytes(), []byte{'\000'}) {
  119. fileList = append(fileList, string(line))
  120. }
  121. return fileList, nil
  122. }
  123. // RemoveFilesFromIndex removes the given files from the index
  124. func (t *TemporaryUploadRepository) RemoveFilesFromIndex(ctx context.Context, filenames ...string) error {
  125. objFmt, err := t.gitRepo.GetObjectFormat()
  126. if err != nil {
  127. return fmt.Errorf("unable to get object format for temporary repo: %q, error: %w", t.repo.FullName(), err)
  128. }
  129. stdOut := new(bytes.Buffer)
  130. stdErr := new(bytes.Buffer)
  131. stdIn := new(bytes.Buffer)
  132. for _, file := range filenames {
  133. if file != "" {
  134. // man git-update-index: input syntax (1): mode SP sha1 TAB path
  135. // mode=0 means "remove from index", then hash part "does not matter as long as it is well formatted."
  136. _, _ = fmt.Fprintf(stdIn, "0 %s\t%s\x00", objFmt.EmptyObjectID(), file)
  137. }
  138. }
  139. if err := gitcmd.NewCommand("update-index", "--remove", "-z", "--index-info").
  140. Run(ctx, &gitcmd.RunOpts{
  141. Dir: t.basePath,
  142. Stdin: stdIn,
  143. Stdout: stdOut,
  144. Stderr: stdErr,
  145. }); err != nil {
  146. return fmt.Errorf("unable to update-index for temporary repo: %q, error: %w\nstdout: %s\nstderr: %s", t.repo.FullName(), err, stdOut.String(), stdErr.String())
  147. }
  148. return nil
  149. }
  150. // HashObjectAndWrite writes the provided content to the object db and returns its hash
  151. func (t *TemporaryUploadRepository) HashObjectAndWrite(ctx context.Context, content io.Reader) (string, error) {
  152. stdOut := new(bytes.Buffer)
  153. stdErr := new(bytes.Buffer)
  154. if err := gitcmd.NewCommand("hash-object", "-w", "--stdin").
  155. Run(ctx, &gitcmd.RunOpts{
  156. Dir: t.basePath,
  157. Stdin: content,
  158. Stdout: stdOut,
  159. Stderr: stdErr,
  160. }); err != nil {
  161. log.Error("Unable to hash-object to temporary repo: %s (%s) Error: %v\nstdout: %s\nstderr: %s", t.repo.FullName(), t.basePath, err, stdOut.String(), stdErr.String())
  162. return "", fmt.Errorf("Unable to hash-object to temporary repo: %s Error: %w\nstdout: %s\nstderr: %s", t.repo.FullName(), err, stdOut.String(), stdErr.String())
  163. }
  164. return strings.TrimSpace(stdOut.String()), nil
  165. }
  166. // AddObjectToIndex adds the provided object hash to the index with the provided mode and path
  167. func (t *TemporaryUploadRepository) AddObjectToIndex(ctx context.Context, mode, objectHash, objectPath string) error {
  168. if _, _, err := gitcmd.NewCommand("update-index", "--add", "--replace", "--cacheinfo").AddDynamicArguments(mode, objectHash, objectPath).RunStdString(ctx, &gitcmd.RunOpts{Dir: t.basePath}); err != nil {
  169. stderr := err.Error()
  170. if matched, _ := regexp.MatchString(".*Invalid path '.*", stderr); matched {
  171. return ErrFilePathInvalid{
  172. Message: objectPath,
  173. Path: objectPath,
  174. }
  175. }
  176. log.Error("Unable to add object to index: %s %s %s in temporary repo %s(%s) Error: %v", mode, objectHash, objectPath, t.repo.FullName(), t.basePath, err)
  177. return fmt.Errorf("Unable to add object to index at %s in temporary repo %s Error: %w", objectPath, t.repo.FullName(), err)
  178. }
  179. return nil
  180. }
  181. // WriteTree writes the current index as a tree to the object db and returns its hash
  182. func (t *TemporaryUploadRepository) WriteTree(ctx context.Context) (string, error) {
  183. stdout, _, err := gitcmd.NewCommand("write-tree").RunStdString(ctx, &gitcmd.RunOpts{Dir: t.basePath})
  184. if err != nil {
  185. log.Error("Unable to write tree in temporary repo: %s(%s): Error: %v", t.repo.FullName(), t.basePath, err)
  186. return "", fmt.Errorf("Unable to write-tree in temporary repo for: %s Error: %w", t.repo.FullName(), err)
  187. }
  188. return strings.TrimSpace(stdout), nil
  189. }
  190. // GetLastCommit gets the last commit ID SHA of the repo
  191. func (t *TemporaryUploadRepository) GetLastCommit(ctx context.Context) (string, error) {
  192. return t.GetLastCommitByRef(ctx, "HEAD")
  193. }
  194. // GetLastCommitByRef gets the last commit ID SHA of the repo by ref
  195. func (t *TemporaryUploadRepository) GetLastCommitByRef(ctx context.Context, ref string) (string, error) {
  196. if ref == "" {
  197. ref = "HEAD"
  198. }
  199. stdout, _, err := gitcmd.NewCommand("rev-parse").AddDynamicArguments(ref).RunStdString(ctx, &gitcmd.RunOpts{Dir: t.basePath})
  200. if err != nil {
  201. log.Error("Unable to get last ref for %s in temporary repo: %s(%s): Error: %v", ref, t.repo.FullName(), t.basePath, err)
  202. return "", fmt.Errorf("Unable to rev-parse %s in temporary repo for: %s Error: %w", ref, t.repo.FullName(), err)
  203. }
  204. return strings.TrimSpace(stdout), nil
  205. }
  206. type CommitTreeUserOptions struct {
  207. ParentCommitID string
  208. TreeHash string
  209. CommitMessage string
  210. SignOff bool
  211. DoerUser *user_model.User
  212. AuthorIdentity *IdentityOptions // if nil, use doer
  213. AuthorTime *time.Time // if nil, use now
  214. CommitterIdentity *IdentityOptions
  215. CommitterTime *time.Time
  216. }
  217. func makeGitUserSignature(doer *user_model.User, identity, other *IdentityOptions) *git.Signature {
  218. gitSig := &git.Signature{}
  219. if identity != nil {
  220. gitSig.Name, gitSig.Email = identity.GitUserName, identity.GitUserEmail
  221. }
  222. if other != nil {
  223. gitSig.Name = util.IfZero(gitSig.Name, other.GitUserName)
  224. gitSig.Email = util.IfZero(gitSig.Email, other.GitUserEmail)
  225. }
  226. if gitSig.Name == "" {
  227. gitSig.Name = doer.GitName()
  228. }
  229. if gitSig.Email == "" {
  230. gitSig.Email = doer.GetEmail()
  231. }
  232. return gitSig
  233. }
  234. // CommitTree creates a commit from a given tree for the user with provided message
  235. func (t *TemporaryUploadRepository) CommitTree(ctx context.Context, opts *CommitTreeUserOptions) (string, error) {
  236. authorSig := makeGitUserSignature(opts.DoerUser, opts.AuthorIdentity, opts.CommitterIdentity)
  237. committerSig := makeGitUserSignature(opts.DoerUser, opts.CommitterIdentity, opts.AuthorIdentity)
  238. authorDate := opts.AuthorTime
  239. committerDate := opts.CommitterTime
  240. if authorDate == nil && committerDate == nil {
  241. authorDate = util.ToPointer(time.Now())
  242. committerDate = authorDate
  243. } else if authorDate == nil {
  244. authorDate = committerDate
  245. } else if committerDate == nil {
  246. committerDate = authorDate
  247. }
  248. // Because this may call hooks we should pass in the environment
  249. env := append(os.Environ(),
  250. "GIT_AUTHOR_NAME="+authorSig.Name,
  251. "GIT_AUTHOR_EMAIL="+authorSig.Email,
  252. "GIT_AUTHOR_DATE="+authorDate.Format(time.RFC3339),
  253. "GIT_COMMITTER_DATE="+committerDate.Format(time.RFC3339),
  254. )
  255. messageBytes := new(bytes.Buffer)
  256. _, _ = messageBytes.WriteString(opts.CommitMessage)
  257. _, _ = messageBytes.WriteString("\n")
  258. cmdCommitTree := gitcmd.NewCommand("commit-tree").AddDynamicArguments(opts.TreeHash)
  259. if opts.ParentCommitID != "" {
  260. cmdCommitTree.AddOptionValues("-p", opts.ParentCommitID)
  261. }
  262. var sign bool
  263. var key *git.SigningKey
  264. var signer *git.Signature
  265. if opts.ParentCommitID != "" {
  266. sign, key, signer, _ = asymkey_service.SignCRUDAction(ctx, t.repo.RepoPath(), opts.DoerUser, t.basePath, opts.ParentCommitID)
  267. } else {
  268. sign, key, signer, _ = asymkey_service.SignInitialCommit(ctx, t.repo.RepoPath(), opts.DoerUser)
  269. }
  270. if sign {
  271. if key.Format != "" {
  272. cmdCommitTree.AddConfig("gpg.format", key.Format)
  273. }
  274. cmdCommitTree.AddOptionFormat("-S%s", key.KeyID)
  275. if t.repo.GetTrustModel() == repo_model.CommitterTrustModel || t.repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
  276. if committerSig.Name != authorSig.Name || committerSig.Email != authorSig.Email {
  277. // Add trailers
  278. _, _ = messageBytes.WriteString("\n")
  279. _, _ = messageBytes.WriteString("Co-authored-by: ")
  280. _, _ = messageBytes.WriteString(committerSig.String())
  281. _, _ = messageBytes.WriteString("\n")
  282. _, _ = messageBytes.WriteString("Co-committed-by: ")
  283. _, _ = messageBytes.WriteString(committerSig.String())
  284. _, _ = messageBytes.WriteString("\n")
  285. }
  286. committerSig = signer
  287. }
  288. } else {
  289. cmdCommitTree.AddArguments("--no-gpg-sign")
  290. }
  291. if opts.SignOff {
  292. // Signed-off-by
  293. _, _ = messageBytes.WriteString("\n")
  294. _, _ = messageBytes.WriteString("Signed-off-by: ")
  295. _, _ = messageBytes.WriteString(committerSig.String())
  296. }
  297. env = append(env,
  298. "GIT_COMMITTER_NAME="+committerSig.Name,
  299. "GIT_COMMITTER_EMAIL="+committerSig.Email,
  300. )
  301. stdout := new(bytes.Buffer)
  302. stderr := new(bytes.Buffer)
  303. if err := cmdCommitTree.
  304. Run(ctx, &gitcmd.RunOpts{
  305. Env: env,
  306. Dir: t.basePath,
  307. Stdin: messageBytes,
  308. Stdout: stdout,
  309. Stderr: stderr,
  310. }); err != nil {
  311. log.Error("Unable to commit-tree in temporary repo: %s (%s) Error: %v\nStdout: %s\nStderr: %s",
  312. t.repo.FullName(), t.basePath, err, stdout, stderr)
  313. return "", fmt.Errorf("Unable to commit-tree in temporary repo: %s Error: %w\nStdout: %s\nStderr: %s",
  314. t.repo.FullName(), err, stdout, stderr)
  315. }
  316. return strings.TrimSpace(stdout.String()), nil
  317. }
  318. // Push the provided commitHash to the repository branch by the provided user
  319. func (t *TemporaryUploadRepository) Push(ctx context.Context, doer *user_model.User, commitHash, branch string) error {
  320. // Because calls hooks we need to pass in the environment
  321. env := repo_module.PushingEnvironment(doer, t.repo)
  322. if err := git.Push(ctx, t.basePath, git.PushOptions{
  323. Remote: t.repo.RepoPath(),
  324. Branch: strings.TrimSpace(commitHash) + ":" + git.BranchPrefix + strings.TrimSpace(branch),
  325. Env: env,
  326. }); err != nil {
  327. if git.IsErrPushOutOfDate(err) {
  328. return err
  329. } else if git.IsErrPushRejected(err) {
  330. rejectErr := err.(*git.ErrPushRejected)
  331. log.Info("Unable to push back to repo from temporary repo due to rejection: %s (%s)\nStdout: %s\nStderr: %s\nError: %v",
  332. t.repo.FullName(), t.basePath, rejectErr.StdOut, rejectErr.StdErr, rejectErr.Err)
  333. return err
  334. }
  335. log.Error("Unable to push back to repo from temporary repo: %s (%s)\nError: %v",
  336. t.repo.FullName(), t.basePath, err)
  337. return fmt.Errorf("Unable to push back to repo from temporary repo: %s (%s) Error: %v",
  338. t.repo.FullName(), t.basePath, err)
  339. }
  340. return nil
  341. }
  342. // DiffIndex returns a Diff of the current index to the head
  343. func (t *TemporaryUploadRepository) DiffIndex(ctx context.Context) (*gitdiff.Diff, error) {
  344. stdoutReader, stdoutWriter, err := os.Pipe()
  345. if err != nil {
  346. return nil, fmt.Errorf("unable to open stdout pipe: %w", err)
  347. }
  348. defer func() {
  349. _ = stdoutReader.Close()
  350. _ = stdoutWriter.Close()
  351. }()
  352. stderr := new(bytes.Buffer)
  353. var diff *gitdiff.Diff
  354. err = gitcmd.NewCommand("diff-index", "--src-prefix=\\a/", "--dst-prefix=\\b/", "--cached", "-p", "HEAD").
  355. Run(ctx, &gitcmd.RunOpts{
  356. Timeout: 30 * time.Second,
  357. Dir: t.basePath,
  358. Stdout: stdoutWriter,
  359. Stderr: stderr,
  360. PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
  361. _ = stdoutWriter.Close()
  362. defer cancel()
  363. var diffErr error
  364. diff, diffErr = gitdiff.ParsePatch(ctx, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdoutReader, "")
  365. _ = stdoutReader.Close()
  366. if diffErr != nil {
  367. // if the diffErr is not nil, it will be returned as the error of "Run()"
  368. return fmt.Errorf("ParsePatch: %w", diffErr)
  369. }
  370. return nil
  371. },
  372. })
  373. if err != nil && !git.IsErrCanceledOrKilled(err) {
  374. log.Error("Unable to diff-index in temporary repo %s (%s). Error: %v\nStderr: %s", t.repo.FullName(), t.basePath, err, stderr)
  375. return nil, fmt.Errorf("unable to run diff-index pipeline in temporary repo: %w", err)
  376. }
  377. return diff, nil
  378. }
  379. // GetBranchCommit Gets the commit object of the given branch
  380. func (t *TemporaryUploadRepository) GetBranchCommit(branch string) (*git.Commit, error) {
  381. if t.gitRepo == nil {
  382. return nil, errors.New("repository has not been cloned")
  383. }
  384. return t.gitRepo.GetBranchCommit(branch)
  385. }
  386. // GetCommit Gets the commit object of the given commit ID
  387. func (t *TemporaryUploadRepository) GetCommit(commitID string) (*git.Commit, error) {
  388. if t.gitRepo == nil {
  389. return nil, errors.New("repository has not been cloned")
  390. }
  391. return t.gitRepo.GetCommit(commitID)
  392. }