-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.go
530 lines (509 loc) · 13.4 KB
/
repository.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
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package git2neo4j
import (
"bytes"
"encoding/csv"
"os"
"strconv"
"strings"
"github.com/jmcvetta/neoism"
git "github.com/libgit2/git2go"
)
// Repository contains a path string to the repository, relative to the folder
// the command is run from.
type Repository struct {
// The repository's unique id.
Id string
// Path to the .git file of the repository, which is obtained by using
// the parameter --mirror when cloning.
// Eg: git clone --mirror git@github.com:youaccount/repo.git
Path string
// Credentials contains the required ssh credentials to perform remote
Credentials
}
// CertificateCheckCallback is provided as one of the RemoteCallbacks functions
// during fetch.
func (r *Repository) CertificateCheckCallback(cert *git.Certificate, valid bool, hostname string) git.ErrorCode {
return 0
}
// CredentialsCallback is provided as one of the RemoteCallbacks functions
// during fetch.
func (r *Repository) CredentialsCallback(url string, uname_from_url string, allowed_types git.CredType) (git.ErrorCode, *git.Cred) {
return r.Credentials.LibgitCred()
}
// ExportToCsv exports the repository commits data to a csv file inside the
// tmp folder.
func (v *Repository) ExportToCsv() error {
r, err := v.Git2goRepo()
if err != nil {
return err
}
defer r.Free()
// Initiate the walk.
revWalk, err := r.Walk()
if err != nil {
return err
}
defer revWalk.Free()
// Iterate through all refs to get the starting Oid for the walk.
referenceIterator, err := r.NewReferenceIterator()
if err != nil {
return err
}
defer referenceIterator.Free()
for {
reference, err := referenceIterator.Next()
if err != nil {
break
}
defer reference.Free()
if isRemote := reference.IsRemote(); isRemote == true {
if target := reference.Target(); target != nil {
if err = revWalk.Push(target); err != nil {
return err
}
}
}
}
// Create a new temporary csv export file
csvPath, err := TemporaryCsvPath(r)
if err != nil {
return err
}
csvFile, err := os.Create(csvPath)
if err != nil {
return err
}
w := csv.NewWriter(csvFile)
defer csvFile.Close()
err = w.Write([]string{
"hash", "message", "author_name", "author_email", "author_time",
"author_timestamp", "commit_time", "commit_timestamp", "parents",
})
if err != nil {
return err
}
w.Flush()
if err = w.Error(); err != nil {
return err
}
// Iterate the walk.
err = revWalk.Iterate(revWalkHandler)
if err != nil {
return err
}
return nil
}
// FetchRemotes executes fetch from remotes. This will update info of all
// remote refspecs.
func (v *Repository) FetchRemotes() error {
r, err := v.Git2goRepo()
if err != nil {
return err
}
defer r.Free()
// Iterate through all remotes and perform fetches.
rnames, err := r.Remotes.List()
if err != nil {
return err
}
// Remote callbacks that contains required ssh credentials.
remotecb := git.RemoteCallbacks{
CredentialsCallback: v.CredentialsCallback,
CertificateCheckCallback: v.CertificateCheckCallback,
}
// Fetch options.
fetchoptions := git.FetchOptions{
RemoteCallbacks: remotecb,
DownloadTags: git.DownloadTagsAuto,
Prune: git.FetchPruneOn,
}
for _, rname := range rnames {
remote, err := r.Remotes.Lookup(rname)
if err != nil {
return err
}
defer remote.Free()
// Get refspecs list to be fetched.
refspecs, err := remote.FetchRefspecs()
if err != nil {
return err
}
// Perform the fetch.
if err = remote.Fetch(refspecs, &fetchoptions, ""); err != nil {
return err
}
}
return nil
}
// Git2goRepo returns the git2go.Repository struct from the Repository's path.
func (r *Repository) Git2goRepo() (*git.Repository, error) {
repo, err := git.OpenRepository(r.Path)
return repo, err
}
// ImportGraph issues a neo4j cypher to import the exported csv into neo4j.
func (v *Repository) ImportGraph() error {
// Export data to csv file.
if err := v.ExportToCsv(); err != nil {
return err
}
// Connect to Neo4j.
settings := GetSettings()
db, err := neoism.Connect(settings.DbUrl)
if err != nil {
return err
}
// Generate constraints
constraints := []neoism.CypherQuery{
neoism.CypherQuery{
Statement: `CREATE CONSTRAINT ON (r:Repository) ASSERT r.id IS UNIQUE`,
},
neoism.CypherQuery{
Statement: `CREATE CONSTRAINT ON (c:Commit) ASSERT c.hash IS UNIQUE`,
},
neoism.CypherQuery{
Statement: `CREATE CONSTRAINT ON (a:Author) ASSERT a.email IS UNIQUE`,
},
}
for _, constraintCq := range constraints {
if err = db.Cypher(&constraintCq); err != nil {
return err
}
}
// Get repo struct.
r, err := v.Git2goRepo()
if err != nil {
return err
}
// Create repo node.
cq := neoism.CypherQuery{
Statement: `MERGE (r:Repository {id: {id}, path: {path}})`,
Parameters: neoism.Props{
"id": v.Id,
"path": r.Path(),
},
}
if err = db.Cypher(&cq); err != nil {
return err
}
// Get csv file path.
var buffer bytes.Buffer
csvFilePath, err := TemporaryCsvPath(r)
if err != nil {
return err
}
buffer.WriteString("file://")
buffer.WriteString(csvFilePath)
csvFilePath = buffer.String()
// Construct cypher query to import CSV.
cq = neoism.CypherQuery{
Statement: `
USING PERIODIC COMMIT 1000
LOAD CSV WITH headers FROM {csv_file} as line
MATCH (r:Repository {id: {id}})
MERGE (c:Commit {hash: line.hash}) ON CREATE SET
c.message = line.message,
c.author_time = line.author_time,
c.author_timestamp = toInt(line.author_timestamp),
c.commit_time = line.commit_time,
c.commit_timestamp = toInt(line.commit_timestamp),
c.parents = split(line.parents, ' ')
MERGE (r)-[:HAS_COMMIT]->(c)
MERGE (u:User:Author {email:line.author_email}) ON CREATE SET u.name = line.author_name
MERGE (u)-[:AUTHORED]->(c)
MERGE (c)-[:AUTHORED_BY]->(u)
MERGE (u)-[:CONTRIBUTED_TO]->(r)
WITH c,line
WHERE line.parents <> ''
FOREACH (parent_hash in split(line.parents, ' ') |
MERGE (parent:Commit {hash: parent_hash})
MERGE (c)-[:HAS_PARENT]->(parent))
`,
Parameters: neoism.Props{
"csv_file": csvFilePath,
"id": v.Id,
},
}
if err = db.Cypher(&cq); err != nil {
return err
}
return nil
}
// importBranchGraph fetches the latest remote branches and add the according
// relationthips to their target commits.
func (v *Repository) ImportBranchGraph() error {
r, err := v.Git2goRepo()
if err != nil {
return err
}
defer r.Free()
// Connect to Neo4j.
settings := GetSettings()
db, err := neoism.Connect(settings.DbUrl)
// Remove all current branches before re-fetching remote branches.
cq := neoism.CypherQuery{
Statement: `MATCH (:Repository {id: {id}})-[:HAS_BRANCH]->(b) DETACH DELETE b`,
Parameters: neoism.Props{
"id": v.Id,
},
}
if err = db.Cypher(&cq); err != nil {
return err
}
// Add all remote branches to the graph.
referenceIterator, err := r.NewReferenceIterator()
if err != nil {
return err
}
for {
reference, err := referenceIterator.Next()
if err != nil {
break
}
if isRemote := reference.IsRemote(); isRemote == true {
if target := reference.Target(); target != nil {
// Get branch name.
branch := reference.Branch()
branchName, err := branch.Name()
if err != nil {
return err
}
// Get branch last commit target.
hash := reference.Target().String()
// Add branch to graph db.
cq := neoism.CypherQuery{
Statement: `
MATCH (r:Repository {id : {id}})
WITH r
MATCH (c:Commit {hash: {hash}})
WITH r, c
CREATE (r)-[:HAS_BRANCH]->(:Branch {name: {name}})-[:POINTS_TO]->(c)
`,
Parameters: neoism.Props{
"id": v.Id,
"hash": hash,
"name": branchName,
},
}
if err = db.Cypher(&cq); err != nil {
return err
}
}
}
}
return nil
}
// SyncRemotes checks if there are new commits after fetching new remote data,
// and update the graph accordingly. If there are new commits, return true.
func (v *Repository) SyncRemotes() error {
// Fetch remotes and go through the updated revwalk.
if err := v.FetchRemotes(); err != nil {
return err
}
r, err := v.Git2goRepo()
if err != nil {
return err
}
defer r.Free()
// Iterate through all refs to get the starting Oid for the walk.
referenceIterator, err := r.NewReferenceIterator()
if err != nil {
return err
}
defer referenceIterator.Free()
for {
reference, err := referenceIterator.Next()
if err != nil {
break
}
defer reference.Free()
if isRemote := reference.IsRemote(); isRemote == true {
if target := reference.Target(); target != nil {
// Initiate the walk.
revWalk, err := r.Walk()
if err != nil {
return err
}
defer revWalk.Free()
if err = revWalk.Push(target); err != nil {
return err
}
// Iterate the walk.
revWalk.Sorting(git.SortTime)
err = revWalk.Iterate(revWalkSyncHandler)
if err != nil {
return err
}
}
}
}
return nil
}
// TemoraryCsvPath returns the repository's path to the temp folder.
func TemporaryCsvPath(r *git.Repository) (string, error) {
// Create unique csv file name through path.
fileName := strings.Replace(r.Path(), "/", "_", -1)
var buffer bytes.Buffer
// Current path
currentPath, err := os.Getwd()
if err != nil {
return "", err
}
buffer.WriteString(currentPath)
buffer.WriteString("/tmp/")
buffer.WriteString(fileName)
buffer.WriteString(".csv")
return buffer.String(), nil
}
func remoteBranchIteratorHandler(branch *git.Branch, branchType git.BranchType) error {
return nil
}
// revWalkHandler goes through each commit and creates relevant info for each
// commit.
func revWalkHandler(commit *git.Commit) bool {
// Commit info.
hash := commit.Id().String()
if hash == "" {
return false
}
message := strings.Replace(commit.Message(), "\"", "'", -1)
// Parent info.
parentCount := commit.ParentCount()
var buffer bytes.Buffer
for i := uint(0); i < parentCount; i = i + 1 {
buffer.WriteString(commit.ParentId(i).String())
if i < parentCount-1 {
buffer.WriteString(" ")
}
}
parents := buffer.String()
// Author info.
authorSig := commit.Author()
authorName := authorSig.Name
authorEmail := authorSig.Email
authorTime := authorSig.When.Format("2006-01-02 15:04:05 +0000")
authorTimestamp := strconv.Itoa(int(authorSig.When.Unix()))
// Committer info.
committerSig := commit.Committer()
commitTime := committerSig.When.Format("2006-01-02 15:04:05 +0000")
commitTimestamp := strconv.Itoa(int(committerSig.When.Unix()))
// Write to csvFile
r := commit.Owner()
csvPath, err := TemporaryCsvPath(r)
if err != nil {
panic(err)
}
csvFile, err := os.OpenFile(csvPath, os.O_RDWR|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer csvFile.Close()
w := csv.NewWriter(csvFile)
err = w.Write([]string{
hash, message, authorName, authorEmail, authorTime, authorTimestamp,
commitTime, commitTimestamp, parents,
})
if err != nil {
panic(err)
}
w.Flush()
if err = w.Error(); err != nil {
panic(err)
}
return true
}
// revWalkSyncHandler adds new commits to the repo graph.
// The walk stops when reaching the previous lastest commit in the database.
func revWalkSyncHandler(commit *git.Commit) bool {
// Get repo path.
r := commit.Owner()
path := r.Path()
// Commit info.
hash := commit.Id().String()
settings := GetSettings()
db, err := neoism.Connect(settings.DbUrl)
if err != nil {
panic(err)
}
res := []struct {
Hash string `json:"c.hash"`
}{}
cq := neoism.CypherQuery{
Statement: `
MATCH (:Repository {path: {path}})-[:HAS_COMMIT]->(c:Commit {hash: {hash}})
RETURN c.hash
`,
Parameters: neoism.Props{
"hash": hash,
"path": path,
},
Result: &res,
}
if err = db.Cypher(&cq); err != nil {
panic(err)
}
// When reaching an existing commit in the database, stop the walk.
if size := len(res); size > 0 {
return false
}
// Else, add the commit to the database.
message := strings.Replace(commit.Message(), "\"", "'", -1)
// Parent info.
parentCount := commit.ParentCount()
var buffer bytes.Buffer
for i := uint(0); i < parentCount; i = i + 1 {
buffer.WriteString(commit.ParentId(i).String())
if i < parentCount-1 {
buffer.WriteString(" ")
}
}
parents := buffer.String()
// Author info.
authorSig := commit.Author()
authorName := authorSig.Name
authorEmail := authorSig.Email
authorTime := authorSig.When.Format("2006-01-02 15:04:05 +0000")
authorTimestamp := strconv.Itoa(int(authorSig.When.Unix()))
// Committer info.
committerSig := commit.Committer()
commitTime := committerSig.When.Format("2006-01-02 15:04:05 +0000")
commitTimestamp := strconv.Itoa(int(committerSig.When.Unix()))
// Add accoding info to the graph.
commitCq := neoism.CypherQuery{
Statement: `
MATCH (r:Repository {path: {path}})
CREATE (r)-[:HAS_COMMIT]->(c:Commit {
message: {message},
author_time: {author_time},
author_timestamp: toInt({author_timestamp}),
commit_time: {commit_time},
commit_timestamp: toInt({commit_timestamp}),
hash: {hash},
parents: split({parents}, ' ')})
MERGE (u:User:Author {email: {author_email}}) ON CREATE SET u.name = {author_name}
MERGE (u)-[:AUTHORED]->(c)
MERGE (c)-[:AUTHORED_BY]->(u)
MERGE (u)-[:CONTRIBUTED_TO]->(r)
WITH c
WHERE {parents} <> ''
FOREACH (parent_hash in split({parents}, ' ') |
MERGE (parent:Commit {hash: parent_hash})
MERGE (c)-[:HAS_PARENT]->(parent))
`,
Parameters: neoism.Props{
"path": path,
"hash": hash,
"message": message,
"author_name": authorName,
"author_email": authorEmail,
"author_time": authorTime,
"author_timestamp": authorTimestamp,
"commit_time": commitTime,
"commit_timestamp": commitTimestamp,
"parents": parents,
},
}
if err = db.Cypher(&commitCq); err != nil {
return false
}
return true
}