Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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