cerrado @ 4534dffb865eb1a50bfbc291a5c3798183081caf

 1package git
 2
 3import (
 4	"errors"
 5	"os"
 6	"path"
 7
 8	"git.gabrielgio.me/cerrado/pkg/u"
 9	"github.com/go-git/go-git/v5"
10	"github.com/go-git/go-git/v5/plumbing/object"
11)
12
13var (
14	ScanPathErr    = errors.New("Scan path does not exist")
15	RepoPathErr    = errors.New("Repository path does not exist")
16	missingHeadErr = errors.New("Head not found")
17)
18
19type (
20	GitServerRepository struct {
21		scanPath string
22	}
23
24	GitRepository struct {
25		path string
26	}
27)
28
29func NewGitServerRepository(scanPath string) *GitServerRepository {
30	return &GitServerRepository{scanPath}
31}
32
33func NewGitRepository(dir string) *GitRepository {
34	return &GitRepository{
35		path: dir,
36	}
37}
38
39func (g *GitServerRepository) List() ([]*GitRepository, error) {
40	if !u.FileExist(g.scanPath) {
41		return nil, ScanPathErr
42	}
43
44	entries, err := os.ReadDir(g.scanPath)
45	if err != nil {
46		return nil, err
47	}
48
49	repos := make([]*GitRepository, 0)
50	for _, e := range entries {
51		if !e.IsDir() {
52			continue
53		}
54
55		fullPath := path.Join(g.scanPath, e.Name())
56		repos = append(repos, NewGitRepository(fullPath))
57	}
58
59	return repos, nil
60}
61
62func (g *GitRepository) Path() string {
63	return g.path
64}
65
66func (g *GitRepository) LastCommit() (*object.Commit, error) {
67	repo, err := git.PlainOpen(g.path)
68	if err != nil {
69		return nil, err
70	}
71
72	ref, err := repo.Head()
73	if err != nil {
74		return nil, errors.Join(missingHeadErr, err)
75	}
76
77	c, err := repo.CommitObject(ref.Hash())
78	if err != nil {
79		return nil, err
80	}
81	return c, nil
82}