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

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