1package service
2
3import (
4 "path"
5
6 "git.gabrielgio.me/cerrado/pkg/config"
7 "git.gabrielgio.me/cerrado/pkg/git"
8 "github.com/go-git/go-git/v5/plumbing"
9 "github.com/go-git/go-git/v5/plumbing/object"
10)
11
12type (
13 Repository struct {
14 Name string
15 Title string
16 LastCommitMessage string
17 LastCommitDate string
18 Ref string
19 }
20
21 GitService struct {
22 configRepo configurationRepository
23 }
24
25 configurationRepository interface {
26 List() []*config.GitRepositoryConfiguration
27 GetByName(name string) *config.GitRepositoryConfiguration
28 }
29)
30
31// TODO: make it configurable
32const timeFormat = "2006.01.02 15:04:05"
33
34func NewGitService(configRepo configurationRepository) *GitService {
35 return &GitService{
36 configRepo: configRepo,
37 }
38}
39
40func (g *GitService) ListRepositories() ([]*Repository, error) {
41 rs := g.configRepo.List()
42
43 repos := make([]*Repository, len(rs))
44 for i, r := range rs {
45 repo, err := git.OpenRepository(r.Path)
46 if err != nil {
47 return nil, err
48 }
49 if err != nil {
50 return nil, err
51 }
52
53 obj, err := repo.LastCommit()
54 if err != nil {
55 return nil, err
56 }
57
58 head, err := repo.Head()
59 if err != nil {
60 return nil, err
61 }
62
63 baseName := path.Base(r.Path)
64 repos[i] = &Repository{
65 Name: baseName,
66 Title: baseName,
67 LastCommitMessage: obj.Message,
68 LastCommitDate: obj.Author.When.Format(timeFormat),
69 Ref: head.Name().Short(),
70 }
71 }
72
73 return repos, nil
74}
75
76func (g *GitService) ListCommits(name, ref string) ([]*object.Commit, error) {
77 // TODO: handle nil
78 r := g.configRepo.GetByName(name)
79
80 repo, err := git.OpenRepository(r.Path)
81 if err != nil {
82 return nil, err
83 }
84
85 err = repo.SetRef(ref)
86 if err != nil {
87 return nil, err
88 }
89 return repo.Commits()
90}
91
92func (g *GitService) ListTags(name string) ([]*object.Tag, error) {
93 // TODO: handle nil
94 r := g.configRepo.GetByName(name)
95
96 repo, err := git.OpenRepository(r.Path)
97 if err != nil {
98 return nil, err
99 }
100 return repo.Tags()
101}
102
103func (g *GitService) ListBranches(name string) ([]*plumbing.Reference, error) {
104 // TODO: handle nil
105 r := g.configRepo.GetByName(name)
106
107 repo, err := git.OpenRepository(r.Path)
108 if err != nil {
109 return nil, err
110 }
111 return repo.Branches()
112}
113
114func (g *GitService) GetHead(name string) (*plumbing.Reference, error) {
115 // TODO: handle nil
116 r := g.configRepo.GetByName(name)
117
118 repo, err := git.OpenRepository(r.Path)
119 if err != nil {
120 return nil, err
121 }
122
123 return repo.Head()
124}