gitea源码

tree.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package git
  5. import (
  6. "bytes"
  7. "strings"
  8. "code.gitea.io/gitea/modules/git/gitcmd"
  9. )
  10. // NewTree create a new tree according the repository and tree id
  11. func NewTree(repo *Repository, id ObjectID) *Tree {
  12. return &Tree{
  13. ID: id,
  14. repo: repo,
  15. }
  16. }
  17. // SubTree get a subtree by the sub dir path
  18. func (t *Tree) SubTree(rpath string) (*Tree, error) {
  19. if len(rpath) == 0 {
  20. return t, nil
  21. }
  22. paths := strings.Split(rpath, "/")
  23. var (
  24. err error
  25. g = t
  26. p = t
  27. te *TreeEntry
  28. )
  29. for _, name := range paths {
  30. te, err = p.GetTreeEntryByPath(name)
  31. if err != nil {
  32. return nil, err
  33. }
  34. g, err = t.repo.getTree(te.ID)
  35. if err != nil {
  36. return nil, err
  37. }
  38. g.ptree = p
  39. p = g
  40. }
  41. return g, nil
  42. }
  43. // LsTree checks if the given filenames are in the tree
  44. func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error) {
  45. cmd := gitcmd.NewCommand("ls-tree", "-z", "--name-only").
  46. AddDashesAndList(append([]string{ref}, filenames...)...)
  47. res, _, err := cmd.RunStdBytes(repo.Ctx, &gitcmd.RunOpts{Dir: repo.Path})
  48. if err != nil {
  49. return nil, err
  50. }
  51. filelist := make([]string, 0, len(filenames))
  52. for line := range bytes.SplitSeq(res, []byte{'\000'}) {
  53. filelist = append(filelist, string(line))
  54. }
  55. return filelist, err
  56. }
  57. // GetTreePathLatestCommit returns the latest commit of a tree path
  58. func (repo *Repository) GetTreePathLatestCommit(refName, treePath string) (*Commit, error) {
  59. stdout, _, err := gitcmd.NewCommand("rev-list", "-1").
  60. AddDynamicArguments(refName).AddDashesAndList(treePath).
  61. RunStdString(repo.Ctx, &gitcmd.RunOpts{Dir: repo.Path})
  62. if err != nil {
  63. return nil, err
  64. }
  65. return repo.GetCommit(strings.TrimSpace(stdout))
  66. }