Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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