aboutsummaryrefslogtreecommitdiff
path: root/pkg/git/git.go
blob: 85a3b9560ac63e1915751dc8407365e72539c8fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package git

import (
	"errors"
	"os"
	"path"

	"git.gabrielgio.me/cerrado/pkg/u"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing/object"
)

var (
	ScanPathErr    = errors.New("Scan path does not exist")
	RepoPathErr    = errors.New("Repository path does not exist")
	missingHeadErr = errors.New("Head not found")
)

type (
	GitServerRepository struct {
		scanPath string
	}

	GitRepository struct {
		path string
	}
)

func NewGitServerRepository(scanPath string) *GitServerRepository {
	return &GitServerRepository{scanPath}
}

func NewGitRepository(dir string) *GitRepository {
	return &GitRepository{
		path: dir,
	}
}

func (g *GitServerRepository) List() ([]*GitRepository, error) {
	if !u.FileExist(g.scanPath) {
		return nil, ScanPathErr
	}

	entries, err := os.ReadDir(g.scanPath)
	if err != nil {
		return nil, err
	}

	repos := make([]*GitRepository, 0)
	for _, e := range entries {
		if !e.IsDir() {
			continue
		}

		fullPath := path.Join(g.scanPath, e.Name())
		repos = append(repos, NewGitRepository(fullPath))
	}

	return repos, nil
}

func (g *GitRepository) Path() string {
	return g.path
}

func (g *GitRepository) LastCommit() (*object.Commit, error) {
	repo, err := git.PlainOpen(g.path)
	if err != nil {
		return nil, err
	}

	ref, err := repo.Head()
	if err != nil {
		return nil, errors.Join(missingHeadErr, err)
	}

	c, err := repo.CommitObject(ref.Hash())
	if err != nil {
		return nil, err
	}
	return c, nil
}