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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. "os/exec"
  12. "regexp"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/process"
  19. "code.gitea.io/gitea/modules/setting"
  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. 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 _, stderr, err := process.GetManager().ExecTimeout(5*time.Minute,
  45. fmt.Sprintf("Clone (git clone -s --bare): %s", t.basePath),
  46. "git", "clone", "-s", "--bare", "-b", branch, t.repo.RepoPath(), t.basePath); err != nil {
  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 _, stderr, err := process.GetManager().ExecDir(5*time.Minute,
  72. t.basePath,
  73. fmt.Sprintf("SetDefaultIndex (git read-tree HEAD): %s", t.basePath),
  74. "git", "read-tree", "HEAD"); err != nil {
  75. return fmt.Errorf("SetDefaultIndex: %v %s", err, stderr)
  76. }
  77. return nil
  78. }
  79. // LsFiles checks if the given filename arguments are in the index
  80. func (t *TemporaryUploadRepository) LsFiles(filenames ...string) ([]string, error) {
  81. stdOut := new(bytes.Buffer)
  82. stdErr := new(bytes.Buffer)
  83. timeout := 5 * time.Minute
  84. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  85. defer cancel()
  86. cmdArgs := []string{"ls-files", "-z", "--"}
  87. for _, arg := range filenames {
  88. if arg != "" {
  89. cmdArgs = append(cmdArgs, arg)
  90. }
  91. }
  92. cmd := exec.CommandContext(ctx, "git", cmdArgs...)
  93. desc := fmt.Sprintf("lsFiles: (git ls-files) %v", cmdArgs)
  94. cmd.Dir = t.basePath
  95. cmd.Stdout = stdOut
  96. cmd.Stderr = stdErr
  97. if err := cmd.Start(); err != nil {
  98. return nil, fmt.Errorf("exec(%s) failed: %v(%v)", desc, err, ctx.Err())
  99. }
  100. pid := process.GetManager().Add(desc, cmd)
  101. err := cmd.Wait()
  102. process.GetManager().Remove(pid)
  103. if err != nil {
  104. err = fmt.Errorf("exec(%d:%s) failed: %v(%v) stdout: %v stderr: %v", pid, desc, err, ctx.Err(), stdOut, stdErr)
  105. return nil, err
  106. }
  107. filelist := make([]string, len(filenames))
  108. for _, line := range bytes.Split(stdOut.Bytes(), []byte{'\000'}) {
  109. filelist = append(filelist, string(line))
  110. }
  111. return filelist, err
  112. }
  113. // RemoveFilesFromIndex removes the given files from the index
  114. func (t *TemporaryUploadRepository) RemoveFilesFromIndex(filenames ...string) error {
  115. stdOut := new(bytes.Buffer)
  116. stdErr := new(bytes.Buffer)
  117. stdIn := new(bytes.Buffer)
  118. for _, file := range filenames {
  119. if file != "" {
  120. stdIn.WriteString("0 0000000000000000000000000000000000000000\t")
  121. stdIn.WriteString(file)
  122. stdIn.WriteByte('\000')
  123. }
  124. }
  125. timeout := 5 * time.Minute
  126. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  127. defer cancel()
  128. cmdArgs := []string{"update-index", "--remove", "-z", "--index-info"}
  129. cmd := exec.CommandContext(ctx, "git", cmdArgs...)
  130. desc := fmt.Sprintf("removeFilesFromIndex: (git update-index) %v", filenames)
  131. cmd.Dir = t.basePath
  132. cmd.Stdout = stdOut
  133. cmd.Stderr = stdErr
  134. cmd.Stdin = bytes.NewReader(stdIn.Bytes())
  135. if err := cmd.Start(); err != nil {
  136. return fmt.Errorf("exec(%s) failed: %v(%v)", desc, err, ctx.Err())
  137. }
  138. pid := process.GetManager().Add(desc, cmd)
  139. err := cmd.Wait()
  140. process.GetManager().Remove(pid)
  141. if err != nil {
  142. err = fmt.Errorf("exec(%d:%s) failed: %v(%v) stdout: %v stderr: %v", pid, desc, err, ctx.Err(), stdOut, stdErr)
  143. }
  144. return err
  145. }
  146. // HashObject writes the provided content to the object db and returns its hash
  147. func (t *TemporaryUploadRepository) HashObject(content io.Reader) (string, error) {
  148. timeout := 5 * time.Minute
  149. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  150. defer cancel()
  151. hashCmd := exec.CommandContext(ctx, "git", "hash-object", "-w", "--stdin")
  152. hashCmd.Dir = t.basePath
  153. hashCmd.Stdin = content
  154. stdOutBuffer := new(bytes.Buffer)
  155. stdErrBuffer := new(bytes.Buffer)
  156. hashCmd.Stdout = stdOutBuffer
  157. hashCmd.Stderr = stdErrBuffer
  158. desc := fmt.Sprintf("hashObject: (git hash-object)")
  159. if err := hashCmd.Start(); err != nil {
  160. return "", fmt.Errorf("git hash-object: %s", err)
  161. }
  162. pid := process.GetManager().Add(desc, hashCmd)
  163. err := hashCmd.Wait()
  164. process.GetManager().Remove(pid)
  165. if err != nil {
  166. err = fmt.Errorf("exec(%d:%s) failed: %v(%v) stdout: %v stderr: %v", pid, desc, err, ctx.Err(), stdOutBuffer, stdErrBuffer)
  167. return "", err
  168. }
  169. return strings.TrimSpace(stdOutBuffer.String()), nil
  170. }
  171. // AddObjectToIndex adds the provided object hash to the index with the provided mode and path
  172. func (t *TemporaryUploadRepository) AddObjectToIndex(mode, objectHash, objectPath string) error {
  173. if _, stderr, err := process.GetManager().ExecDir(5*time.Minute,
  174. t.basePath,
  175. fmt.Sprintf("addObjectToIndex (git update-index): %s", t.basePath),
  176. "git", "update-index", "--add", "--replace", "--cacheinfo", mode, objectHash, objectPath); err != nil {
  177. if matched, _ := regexp.MatchString(".*Invalid path '.*", stderr); matched {
  178. return models.ErrFilePathInvalid{
  179. Message: objectPath,
  180. Path: objectPath,
  181. }
  182. }
  183. return fmt.Errorf("git update-index: %s", stderr)
  184. }
  185. return nil
  186. }
  187. // WriteTree writes the current index as a tree to the object db and returns its hash
  188. func (t *TemporaryUploadRepository) WriteTree() (string, error) {
  189. treeHash, stderr, err := process.GetManager().ExecDir(5*time.Minute,
  190. t.basePath,
  191. fmt.Sprintf("WriteTree (git write-tree): %s", t.basePath),
  192. "git", "write-tree")
  193. if err != nil {
  194. return "", fmt.Errorf("git write-tree: %s", stderr)
  195. }
  196. return strings.TrimSpace(treeHash), nil
  197. }
  198. // GetLastCommit gets the last commit ID SHA of the repo
  199. func (t *TemporaryUploadRepository) GetLastCommit() (string, error) {
  200. return t.GetLastCommitByRef("HEAD")
  201. }
  202. // GetLastCommitByRef gets the last commit ID SHA of the repo by ref
  203. func (t *TemporaryUploadRepository) GetLastCommitByRef(ref string) (string, error) {
  204. if ref == "" {
  205. ref = "HEAD"
  206. }
  207. treeHash, stderr, err := process.GetManager().ExecDir(5*time.Minute,
  208. t.basePath,
  209. fmt.Sprintf("GetLastCommit (git rev-parse %s): %s", ref, t.basePath),
  210. "git", "rev-parse", ref)
  211. if err != nil {
  212. return "", fmt.Errorf("git rev-parse %s: %s", ref, stderr)
  213. }
  214. return strings.TrimSpace(treeHash), nil
  215. }
  216. // CommitTree creates a commit from a given tree for the user with provided message
  217. func (t *TemporaryUploadRepository) CommitTree(author, committer *models.User, treeHash string, message string) (string, error) {
  218. commitTimeStr := time.Now().Format(time.UnixDate)
  219. authorSig := author.NewGitSig()
  220. committerSig := committer.NewGitSig()
  221. // FIXME: Should we add SSH_ORIGINAL_COMMAND to this
  222. // Because this may call hooks we should pass in the environment
  223. env := append(os.Environ(),
  224. "GIT_AUTHOR_NAME="+authorSig.Name,
  225. "GIT_AUTHOR_EMAIL="+authorSig.Email,
  226. "GIT_AUTHOR_DATE="+commitTimeStr,
  227. "GIT_COMMITTER_NAME="+committerSig.Name,
  228. "GIT_COMMITTER_EMAIL="+committerSig.Email,
  229. "GIT_COMMITTER_DATE="+commitTimeStr,
  230. )
  231. commitHash, stderr, err := process.GetManager().ExecDirEnv(5*time.Minute,
  232. t.basePath,
  233. fmt.Sprintf("commitTree (git commit-tree): %s", t.basePath),
  234. env,
  235. "git", "commit-tree", treeHash, "-p", "HEAD", "-m", message)
  236. if err != nil {
  237. return "", fmt.Errorf("git commit-tree: %s", stderr)
  238. }
  239. return strings.TrimSpace(commitHash), nil
  240. }
  241. // Push the provided commitHash to the repository branch by the provided user
  242. func (t *TemporaryUploadRepository) Push(doer *models.User, commitHash string, branch string) error {
  243. // Because calls hooks we need to pass in the environment
  244. env := models.PushingEnvironment(doer, t.repo)
  245. if _, stderr, err := process.GetManager().ExecDirEnv(5*time.Minute,
  246. t.basePath,
  247. fmt.Sprintf("actuallyPush (git push): %s", t.basePath),
  248. env,
  249. "git", "push", t.repo.RepoPath(), strings.TrimSpace(commitHash)+":refs/heads/"+strings.TrimSpace(branch)); err != nil {
  250. return fmt.Errorf("git push: %s", stderr)
  251. }
  252. return nil
  253. }
  254. // DiffIndex returns a Diff of the current index to the head
  255. func (t *TemporaryUploadRepository) DiffIndex() (diff *models.Diff, err error) {
  256. timeout := 5 * time.Minute
  257. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  258. defer cancel()
  259. stdErr := new(bytes.Buffer)
  260. cmd := exec.CommandContext(ctx, "git", "diff-index", "--cached", "-p", "HEAD")
  261. cmd.Dir = t.basePath
  262. cmd.Stderr = stdErr
  263. stdout, err := cmd.StdoutPipe()
  264. if err != nil {
  265. return nil, fmt.Errorf("StdoutPipe: %v stderr %s", err, stdErr.String())
  266. }
  267. if err = cmd.Start(); err != nil {
  268. return nil, fmt.Errorf("Start: %v stderr %s", err, stdErr.String())
  269. }
  270. pid := process.GetManager().Add(fmt.Sprintf("diffIndex [repo_path: %s]", t.repo.RepoPath()), cmd)
  271. defer process.GetManager().Remove(pid)
  272. diff, err = models.ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, stdout)
  273. if err != nil {
  274. return nil, fmt.Errorf("ParsePatch: %v", err)
  275. }
  276. if err = cmd.Wait(); err != nil {
  277. return nil, fmt.Errorf("Wait: %v", err)
  278. }
  279. return diff, nil
  280. }
  281. // CheckAttribute checks the given attribute of the provided files
  282. func (t *TemporaryUploadRepository) CheckAttribute(attribute string, args ...string) (map[string]map[string]string, error) {
  283. stdOut := new(bytes.Buffer)
  284. stdErr := new(bytes.Buffer)
  285. timeout := 5 * time.Minute
  286. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  287. defer cancel()
  288. cmdArgs := []string{"check-attr", "-z", attribute, "--cached", "--"}
  289. for _, arg := range args {
  290. if arg != "" {
  291. cmdArgs = append(cmdArgs, arg)
  292. }
  293. }
  294. cmd := exec.CommandContext(ctx, "git", cmdArgs...)
  295. desc := fmt.Sprintf("checkAttr: (git check-attr) %s %v", attribute, cmdArgs)
  296. cmd.Dir = t.basePath
  297. cmd.Stdout = stdOut
  298. cmd.Stderr = stdErr
  299. if err := cmd.Start(); err != nil {
  300. return nil, fmt.Errorf("exec(%s) failed: %v(%v)", desc, err, ctx.Err())
  301. }
  302. pid := process.GetManager().Add(desc, cmd)
  303. err := cmd.Wait()
  304. process.GetManager().Remove(pid)
  305. if err != nil {
  306. err = fmt.Errorf("exec(%d:%s) failed: %v(%v) stdout: %v stderr: %v", pid, desc, err, ctx.Err(), stdOut, stdErr)
  307. return nil, err
  308. }
  309. fields := bytes.Split(stdOut.Bytes(), []byte{'\000'})
  310. if len(fields)%3 != 1 {
  311. return nil, fmt.Errorf("Wrong number of fields in return from check-attr")
  312. }
  313. var name2attribute2info = make(map[string]map[string]string)
  314. for i := 0; i < (len(fields) / 3); i++ {
  315. filename := string(fields[3*i])
  316. attribute := string(fields[3*i+1])
  317. info := string(fields[3*i+2])
  318. attribute2info := name2attribute2info[filename]
  319. if attribute2info == nil {
  320. attribute2info = make(map[string]string)
  321. }
  322. attribute2info[attribute] = info
  323. name2attribute2info[filename] = attribute2info
  324. }
  325. return name2attribute2info, err
  326. }
  327. // GetBranchCommit Gets the commit object of the given branch
  328. func (t *TemporaryUploadRepository) GetBranchCommit(branch string) (*git.Commit, error) {
  329. if t.gitRepo == nil {
  330. return nil, fmt.Errorf("repository has not been cloned")
  331. }
  332. return t.gitRepo.GetBranchCommit(branch)
  333. }
  334. // GetCommit Gets the commit object of the given commit ID
  335. func (t *TemporaryUploadRepository) GetCommit(commitID string) (*git.Commit, error) {
  336. if t.gitRepo == nil {
  337. return nil, fmt.Errorf("repository has not been cloned")
  338. }
  339. return t.gitRepo.GetCommit(commitID)
  340. }