github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/tree.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // Copyright 2015 The Gogs Authors. All rights reserved.
     7  
     8  package git
     9  
    10  import (
    11  	"bytes"
    12  	"strings"
    13  )
    14  
    15  // NewTree create a new tree according the repository and tree id
    16  func NewTree(repo *Repository, id SHA1) *Tree {
    17  	return &Tree{
    18  		ID:   id,
    19  		repo: repo,
    20  	}
    21  }
    22  
    23  // SubTree get a sub tree by the sub dir path
    24  func (t *Tree) SubTree(rpath string) (*Tree, error) {
    25  	if len(rpath) == 0 {
    26  		return t, nil
    27  	}
    28  
    29  	paths := strings.Split(rpath, "/")
    30  	var (
    31  		err error
    32  		g   = t
    33  		p   = t
    34  		te  *TreeEntry
    35  	)
    36  	for _, name := range paths {
    37  		te, err = p.GetTreeEntryByPath(name)
    38  		if err != nil {
    39  			return nil, err
    40  		}
    41  
    42  		g, err = t.repo.getTree(te.ID)
    43  		if err != nil {
    44  			return nil, err
    45  		}
    46  		g.ptree = p
    47  		p = g
    48  	}
    49  	return g, nil
    50  }
    51  
    52  // LsTree checks if the given filenames are in the tree
    53  func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error) {
    54  	cmd := NewCommand(repo.Ctx, "ls-tree", "-z", "--name-only", "--", ref)
    55  	for _, arg := range filenames {
    56  		if arg != "" {
    57  			cmd.AddArguments(arg)
    58  		}
    59  	}
    60  	res, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
    61  	if err != nil {
    62  		return nil, err
    63  	}
    64  	filelist := make([]string, 0, len(filenames))
    65  	for _, line := range bytes.Split(res, []byte{'\000'}) {
    66  		filelist = append(filelist, string(line))
    67  	}
    68  
    69  	return filelist, err
    70  }