Files
gitea/modules/git/tree.go
T
wxiaoguangandGitHub 82edc3da01 refactor: decouple git.Repository(ctx) from git.Commit & git.Tree (#38464)
1. Storing "ctx" in a long-living object is wrong
2. Make the commit & tree cacheable (for the future performance
optimization)
3. Also fix some bad designs like `// FIXME: bad design, this field can
be nil if the commit is from "last commit cache"`

ref:
* #33893
2026-07-15 17:30:01 +00:00

79 lines
1.8 KiB
Go

// Copyright 2015 The Gogs Authors. All rights reserved.
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package git
import (
"bytes"
"context"
"strings"
"gitea.dev/modules/git/gitcmd"
)
type TreeCommon struct {
ID ObjectID
}
func newTree(id ObjectID) *Tree {
return &Tree{TreeCommon: TreeCommon{ID: id}}
}
// SubTree get a subtree by the sub dir path
func (t *Tree) SubTree(ctx context.Context, gitRepo *Repository, rpath string) (*Tree, error) {
if len(rpath) == 0 {
return t, nil
}
paths := strings.Split(rpath, "/")
var (
err error
g = t
p = t
te *TreeEntry
)
for _, name := range paths {
te, err = p.GetTreeEntryByPath(ctx, gitRepo, name)
if err != nil {
return nil, err
}
g, err = gitRepo.getTree(te.ID)
if err != nil {
return nil, err
}
p = g
}
return g, nil
}
// LsTree checks if the given filenames are in the tree
func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error) {
cmd := gitcmd.NewCommand("ls-tree", "-z", "--name-only").
AddDashesAndList(append([]string{ref}, filenames...)...)
res, _, err := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx)
if err != nil {
return nil, err
}
filelist := make([]string, 0, len(filenames))
for line := range bytes.SplitSeq(res, []byte{'\000'}) {
filelist = append(filelist, string(line))
}
return filelist, err
}
// GetTreePathLatestCommit returns the latest commit of a tree path
func (repo *Repository) GetTreePathLatestCommit(refName, treePath string) (*Commit, error) {
stdout, _, err := gitcmd.NewCommand("rev-list", "-1").
AddDynamicArguments(refName).AddDashesAndList(treePath).
WithDir(repo.Path).
RunStdString(repo.Ctx)
if err != nil {
return nil, err
}
return repo.GetCommit(strings.TrimSpace(stdout))
}