/
git.go
87 lines (72 loc) · 1.42 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
// Package git provides a git source
package git
import (
"os"
"path/filepath"
"strings"
"github.com/go-git/go-git/v5"
"github.com/micro/go-micro/v2/runtime/local/source"
)
// Source retrieves source code
// An empty struct can be used
type Source struct {
Options source.Options
}
func (g *Source) Fetch(url string) (*source.Repository, error) {
purl := url
if parts := strings.Split(url, "://"); len(parts) > 1 {
purl = parts[len(parts)-1]
}
name := filepath.Base(url)
path := filepath.Join(g.Options.Path, purl)
_, err := git.PlainClone(path, false, &git.CloneOptions{
URL: url,
})
if err == nil {
return &source.Repository{
Name: name,
Path: path,
URL: url,
}, nil
}
// repo already exists
if err != git.ErrRepositoryAlreadyExists {
return nil, err
}
// open repo
re, err := git.PlainOpen(path)
if err != nil {
return nil, err
}
// update it
if err := re.Fetch(nil); err != nil {
return nil, err
}
return &source.Repository{
Name: name,
Path: path,
URL: url,
}, nil
}
func (g *Source) Commit(r *source.Repository) error {
repo := filepath.Join(r.Path)
re, err := git.PlainOpen(repo)
if err != nil {
return err
}
return re.Push(nil)
}
func (g *Source) String() string {
return "git"
}
func NewSource(opts ...source.Option) *Source {
options := source.Options{
Path: os.TempDir(),
}
for _, o := range opts {
o(&options)
}
return &Source{
Options: options,
}
}