all repos — legit @ b78354aee2f0fef8552896d75e106c915365d3ef

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)
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)
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(t *object.Tree) []NiceTree {
52	nts := []NiceTree{}
53
54	for _, e := range t.Entries {
55		mode, _ := e.Mode.ToOSFileMode()
56		sz, _ := t.Size(e.Name)
57		nts = append(nts, NiceTree{
58			Name:   e.Name,
59			Mode:   mode.String(),
60			IsFile: e.Mode.IsFile(),
61			Size:   sz,
62		})
63	}
64
65	return nts
66}