all repos — legit @ d62fb1442bc300dcee2a7c6a9c374201ba1c7ae6

web frontend for git

git/git.go (view raw)

 1package git
 2
 3import (
 4	"fmt"
 5
 6	"github.com/go-git/go-git/v5"
 7	"github.com/go-git/go-git/v5/plumbing"
 8	"github.com/go-git/go-git/v5/plumbing/object"
 9)
10
11func AllCommits(r *git.Repository) ([]*object.Commit, error) {
12	ci, err := r.Log(&git.LogOptions{All: true})
13	if err != nil {
14		return nil, fmt.Errorf("all commits: %w", err)
15	}
16
17	commits := []*object.Commit{}
18	ci.ForEach(func(c *object.Commit) error {
19		commits = append(commits, c)
20		return nil
21	})
22
23	return commits, nil
24}
25
26// A nicer git tree representation.
27type NiceTree struct {
28	Name   string
29	Mode   string
30	Size   int64
31	IsFile bool
32}
33
34func FilesAtRef(r *git.Repository, hash plumbing.Hash, path string) ([]NiceTree, error) {
35	c, err := r.CommitObject(hash)
36	if err != nil {
37		return nil, fmt.Errorf("commit object: %w", err)
38	}
39
40	files := []NiceTree{}
41	tree, err := c.Tree()
42	if err != nil {
43		return nil, fmt.Errorf("file tree: %w", err)
44	}
45
46	if path == "" {
47		files = makeNiceTree(tree.Entries)
48	} else {
49		o, err := tree.FindEntry(path)
50		if err != nil {
51			return nil, err
52		}
53
54		if !o.Mode.IsFile() {
55			subtree, err := tree.Tree(path)
56			if err != nil {
57				return nil, err
58			}
59
60			files = makeNiceTree(subtree.Entries)
61		}
62	}
63
64	return files, nil
65}
66
67func makeNiceTree(es []object.TreeEntry) []NiceTree {
68	nts := []NiceTree{}
69	for _, e := range es {
70		mode, _ := e.Mode.ToOSFileMode()
71		nts = append(nts, NiceTree{
72			Name:   e.Name,
73			Mode:   mode.String(),
74			IsFile: e.Mode.IsFile(),
75		})
76	}
77
78	return nts
79}