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.

temp_repo.go 15KB

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