/
git.go
88 lines (79 loc) · 1.76 KB
/
git.go
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
83
84
85
86
87
88
package main
import (
"fmt"
"path/filepath"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/transport"
)
type Git struct {
dir string
remote string
auth transport.AuthMethod
r *git.Repository
}
func NewGit(dir, remote string, auth transport.AuthMethod) (*Git, error) {
path, err := filepath.Abs(dir)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path: %w", err)
}
var repo *git.Repository
for {
repo, err = git.PlainOpen(path)
if err != nil {
path = filepath.Dir(path)
if path == "/" {
return nil, fmt.Errorf("repository does not exist")
}
continue
}
break
}
return &Git{
dir: dir,
remote: remote,
auth: auth,
r: repo,
}, nil
}
func (g *Git) RemoteTags() ([]string, error) {
remote, err := g.r.Remote(g.remote)
if err != nil {
return nil, fmt.Errorf("failed to get remote: %w", err)
}
list, err := remote.List(&git.ListOptions{
Auth: g.auth,
})
if err != nil {
return nil, fmt.Errorf("failed to list remote: %w", err)
}
var tags []string
for _, ref := range list {
if ref.Name().IsTag() {
tags = append(tags, ref.Name().Short())
}
}
return tags, nil
}
func (g *Git) CreateTag(tag string) error {
l, err := g.r.Log(&git.LogOptions{})
if err != nil {
return fmt.Errorf("failed to get commit log: %w", err)
}
c, err := l.Next()
if err != nil {
return fmt.Errorf("failed to get current commit: %w", err)
}
_, err = g.r.CreateTag(tag, c.Hash, &git.CreateTagOptions{
Message: tag,
})
return err
}
func (g *Git) PushTag(tag string) error {
err := g.r.Push(&git.PushOptions{
Auth: g.auth,
RemoteName: g.remote,
RefSpecs: []config.RefSpec{config.RefSpec("refs/tags/" + tag + ":refs/tags/" + tag)},
})
return err
}