all repos — legit @ 150d81df6c82ee9ea735f988d1c06edd9059819a

web frontend for git

git/tree.go (view raw)

 1package git
 2
 3import (
 4	"fmt"
 5
 6	"github.com/go-git/go-git/v5/plumbing/object"
 7)
 8
 9func (g *GitRepo) FileTree(path string) ([]NiceTree, error) {
10	c, err := g.r.CommitObject(g.h)
11	if err != nil {
12		return nil, fmt.Errorf("commit object: %w", err)
13	}
14
15	files := []NiceTree{}
16	tree, err := c.Tree()
17	if err != nil {
18		return nil, fmt.Errorf("file tree: %w", err)
19	}
20
21	if path == "" {
22		files = makeNiceTree(tree.Entries)
23	} else {
24		o, err := tree.FindEntry(path)
25		if err != nil {
26			return nil, err
27		}
28
29		if !o.Mode.IsFile() {
30			subtree, err := tree.Tree(path)
31			if err != nil {
32				return nil, err
33			}
34
35			files = makeNiceTree(subtree.Entries)
36		}
37	}
38
39	return files, nil
40}
41
42// A nicer git tree representation.
43type NiceTree struct {
44	Name      string
45	Mode      string
46	Size      int64
47	IsFile    bool
48	IsSubtree bool
49}
50
51func makeNiceTree(es []object.TreeEntry) []NiceTree {
52	nts := []NiceTree{}
53
54	for _, e := range es {
55		mode, _ := e.Mode.ToOSFileMode()
56		nts = append(nts, NiceTree{
57			Name:   e.Name,
58			Mode:   mode.String(),
59			IsFile: e.Mode.IsFile(),
60		})
61	}
62
63	return nts
64}