-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
316 lines (233 loc) · 7.4 KB
/
git.go
File metadata and controls
316 lines (233 loc) · 7.4 KB
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package git
import (
"context"
"fmt"
"iter"
"log/slog"
"net/url"
"os"
"path/filepath"
"strconv"
"sync/atomic"
"time"
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/whosonfirst/go-ioutil"
"github.com/whosonfirst/go-whosonfirst-iterate/v3"
"github.com/whosonfirst/go-whosonfirst-iterate/v3/filters"
)
func init() {
ctx := context.Background()
iterate.RegisterIterator(ctx, "git", NewGitIterator)
}
// GitIterator implements the `Iterator` interface for crawling records in a Git repository.
type GitIterator struct {
iterate.Iterator
// An optional path on disk where Git respositories will be cloned.
target string
// A boolean value indicating whether a Git repository (cloned to disk) should not be removed after processing.
preserve bool
// filters is a `filters.Filters` instance used to include or exclude specific records from being crawled.
filters filters.Filters
// The branch of the Git repository to clone.
branch string
// Limit fetching to the specified number of commits.
depth int
// The count of documents that have been processed so far.
seen int64
// Boolean value indicating whether records are still being iterated.
iterating *atomic.Bool
}
// NewGitIterator() returns a new `GitIterator` instance configured by 'uri' in the form of:
//
// git://{PATH}?{PARAMETERS}
//
// Where {PATH} is an optional path on disk where a repository will be clone to (default is to clone repository in memory) and {PARAMETERS} may be:
// * `?include=` Zero or more `aaronland/go-json-query` query strings containing rules that must match for a document to be considered for further processing.
// * `?exclude=` Zero or more `aaronland/go-json-query` query strings containing rules that if matched will prevent a document from being considered for further processing.
// * `?include_mode=` A valid `aaronland/go-json-query` query mode string for testing inclusion rules.
// * `?exclude_mode=` A valid `aaronland/go-json-query` query mode string for testing exclusion rules.
// * `?preserve=` A boolean value indicating whether a Git repository (cloned to disk) should not be removed after processing.
// * `?depth=` An integer value indicating the number of commits to fetch. Default is 1.
func NewGitIterator(ctx context.Context, uri string) (iterate.Iterator, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, fmt.Errorf("Failed to parse URI, %w", err)
}
em := &GitIterator{
target: u.Path,
depth: 1,
seen: int64(0),
iterating: new(atomic.Bool),
}
q := u.Query()
f, err := filters.NewQueryFiltersFromQuery(ctx, q)
if err != nil {
return nil, fmt.Errorf("Failed to create query filters, %w", err)
}
em.filters = f
str_preserve := q.Get("preserve")
if str_preserve != "" {
preserve, err := strconv.ParseBool(str_preserve)
if err != nil {
return nil, fmt.Errorf("Failed to parse 'preserve' parameter, %w", err)
}
em.preserve = preserve
}
branch := q.Get("branch")
if branch != "" {
em.branch = branch
}
if q.Has("depth") {
v, err := strconv.Atoi(q.Get("depth"))
if err != nil {
return nil, fmt.Errorf("Failed to parse '?depth=' parameter, %w", err)
}
em.depth = v
}
return em, nil
}
// Iterate will return an `iter.Seq2[*Record, error]` for each record encountered in 'uris'.
func (it *GitIterator) Iterate(ctx context.Context, uris ...string) iter.Seq2[*iterate.Record, error] {
return func(yield func(rec *iterate.Record, err error) bool) {
it.iterating.Swap(true)
defer it.iterating.Swap(false)
for _, uri := range uris {
logger := slog.Default()
logger = logger.With("uri", uri)
logger = logger.With("branch", it.branch)
var repo *gogit.Repository
clone_opts := &gogit.CloneOptions{
URL: uri,
Depth: it.depth,
}
if it.branch != "" {
br := plumbing.NewBranchReferenceName(it.branch)
clone_opts.ReferenceName = br
}
logger = logger.With("target", it.target)
t1 := time.Now()
switch it.target {
case "":
logger.Debug("Clone in to memory")
r, err := gogit.Clone(memory.NewStorage(), nil, clone_opts)
if err != nil {
logger.Error("Failed to clone repo", "error", err)
if !yield(nil, err) {
return
}
continue
}
repo = r
default:
fname := filepath.Base(uri)
path := filepath.Join(it.target, fname)
logger.Debug("Clone to path", "path", path)
r, err := gogit.PlainClone(path, false, clone_opts)
if err != nil {
logger.Error("Failed to clone repo", "error", err)
if !yield(nil, err) {
return
}
continue
}
if !it.preserve {
defer os.RemoveAll(path)
}
repo = r
}
logger.Debug("Time to clone repo", "time", time.Since(t1))
ref, err := repo.Head()
if err != nil {
logger.Error("Failed to derive HEAD", "error", err)
if !yield(nil, err) {
return
}
continue
}
logger = logger.With("ref", ref.Hash())
commit, err := repo.CommitObject(ref.Hash())
if err != nil {
logger.Error("Failed to derive commit object", "error", err)
if !yield(nil, err) {
return
}
continue
}
tree, err := commit.Tree()
if err != nil {
logger.Error("Failed to derive commit tree", "error", err)
if !yield(nil, err) {
return
}
continue
}
err = tree.Files().ForEach(func(f *object.File) error {
logger := slog.Default()
logger = logger.With("uri", uri)
logger = logger.With("path", f.Name)
logger = logger.With("branch", it.branch)
logger = logger.With("ref", ref.Hash())
switch filepath.Ext(f.Name) {
case ".geojson":
// continue
default:
// logger.Debug("Not a .geojson file, skipping.")
return nil
}
r, err := f.Reader()
if err != nil {
logger.Error("Failed to derive reader", "error", err)
return fmt.Errorf("Failed to derive reader for %s, %w", f.Name, err)
}
rsc, err := ioutil.NewReadSeekCloser(r)
if err != nil {
r.Close()
logger.Error("Failed to create ReadSeekCloser", "error", err)
return fmt.Errorf("Failed to create ReadSeekCloser for %s, %w", f.Name, err)
}
if it.filters != nil {
ok, err := it.filters.Apply(ctx, rsc)
if err != nil {
rsc.Close()
logger.Error("Failed to apply filters", "error", err)
return fmt.Errorf("Failed to apply query filters to %s, %w", f.Name, err)
}
if !ok {
// logger.Debug("Skipping because filters not true")
rsc.Close()
return nil
}
_, err = rsc.Seek(0, 0)
if err != nil {
rsc.Close()
logger.Error("Failed to rewind filehandler", "error", err)
return fmt.Errorf("Failed to reset filehandle for %s, %w", f.Name, err)
}
}
rec := iterate.NewRecord(f.Name, rsc)
yield(rec, nil)
return nil
})
if err != nil {
logger.Error("Failed to iterate tree", "error", err)
yield(nil, err)
return
}
}
}
}
// Seen() returns the total number of records processed so far.
func (it *GitIterator) Seen() int64 {
return atomic.LoadInt64(&it.seen)
}
// IsIterating() returns a boolean value indicating whether 'it' is still processing documents.
func (it *GitIterator) IsIterating() bool {
return it.iterating.Load()
}
// Close performs any implementation specific tasks before terminating the iterator.
func (it *GitIterator) Close() error {
return nil
}