-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.go
132 lines (93 loc) · 1.96 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package git
import (
"bytes"
"context"
gogit "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/storage/memory"
"github.com/sfomuseum/go-lookup/catalog"
"github.com/sfomuseum/go-lookup/iterator"
"io/ioutil"
"log"
"net/url"
)
const DEFAULT_BRANCH string = "main"
type GitIterator struct {
iterator.Iterator
uri string
ref plumbing.ReferenceName
}
func init() {
ctx := context.Background()
schemes := []string{
"git",
"https",
}
for _, s := range schemes {
err := iterator.RegisterIterator(ctx, s, NewGitIterator)
if err != nil {
panic(err)
}
}
}
func NewGitIterator(ctx context.Context, uri string) (iterator.Iterator, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
ref := plumbing.NewBranchReferenceName(DEFAULT_BRANCH)
q := u.Query()
branch := q.Get("branch")
if branch != "" {
ref = plumbing.NewBranchReferenceName(branch)
}
l := &GitIterator{
uri: uri,
ref: ref,
}
return l, nil
}
func (l *GitIterator) Append(ctx context.Context, lu catalog.Catalog, append_funcs ...iterator.AppendLookupFunc) error {
r, err := gogit.Clone(memory.NewStorage(), nil, &gogit.CloneOptions{
URL: l.uri,
Depth: 1,
})
if err != nil {
return err
}
ref, err := r.Reference(l.ref, true)
if err != nil {
return err
}
commit, err := r.CommitObject(ref.Hash())
if err != nil {
return err
}
files, err := commit.Files()
if err != nil {
return err
}
err = files.ForEach(func(f *object.File) error {
fh, err := f.Reader()
if err != nil {
return err
}
defer fh.Close()
body, err := ioutil.ReadAll(fh)
if err != nil {
return err
}
for _, append_f := range append_funcs {
br := bytes.NewReader(body)
fh := ioutil.NopCloser(br)
err := append_f(ctx, lu, fh)
if err != nil {
log.Printf("GIT %s: %s\n", f.Name, err)
// return err
}
}
return nil
})
return err
}