-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathghtorrent.rb
1995 lines (1683 loc) · 69.2 KB
/
ghtorrent.rb
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'sequel'
require 'ghtorrent/ghtime'
require 'ghtorrent/logging'
require 'ghtorrent/settings'
require 'ghtorrent/retriever'
require 'ghtorrent/persister'
require 'ghtorrent/geolocator'
require 'ghtorrent/refresher'
module GHTorrent
class Mirror
include GHTorrent::Logging
include GHTorrent::Settings
include GHTorrent::Retriever
include GHTorrent::Persister
include GHTorrent::Geolocator
include GHTorrent::Refresher
attr_reader :settings, :persister, :logger
def initialize(settings)
@settings = settings
@retry_on_error = Array.new
@retry_on_error << Mysql2::Error if defined? Mysql2::Error
@retry_on_error << SQLite3::Exception if defined? SQLite3::Exception
@retry_on_error << PG::Error if defined? PG::Error
end
def dispose
@db.disconnect unless @db.nil?
@persister.close unless @persister.nil?
end
# Get a connection to the database
def db
return @db unless @db.nil?
Sequel.single_threaded = true
@db = Sequel.connect(config(:sql_url), :encoding => 'utf8')
#@db.loggers << Logger.new(STDOUT)
if @db.tables.empty?
dir = File.join(File.dirname(__FILE__), 'migrations')
puts "Database empty, running migrations from #{dir}"
Sequel.extension :migration
Sequel::Migrator.apply(@db, dir)
end
@db
end
def persister
@persister ||= connect(config(:mirror_persister), @settings)
@persister
end
def stages
%w(ensure_commits ensure_topics ensure_languages ensure_pull_requests
ensure_issues ensure_watchers ensure_labels ensure_forks)
end
##
# Make sure a commit exists
#
def ensure_commit(repo, sha, user, comments = true)
ensure_repo(user, repo)
c = retrieve_commit(repo, sha, user)
if c.nil?
warn "Commit #{user}/#{repo} -> #{sha} does not exist"
return
end
stored = store_commit(c, repo, user)
ensure_parents(c, user, repo)
if not c['commit']['comment_count'].nil? \
and c['commit']['comment_count'] > 0
ensure_commit_comments(user, repo, sha) if comments
end
ensure_repo_commit(user, repo, sha)
stored
end
##
# Retrieve commits for a repository, starting from +sha+
# ==Parameters:
# [user] The user to whom the repo belongs.
# [repo] The repo to look for commits into.
# [sha] The first commit to start retrieving from. If nil, then retrieval
# starts from what the project considers as master branch.
# [return_retrieved] Should retrieved commits be returned? If not, memory is
# saved while processing them.
# [num_commits] Number of commit to retrieve
# [fork_all] Retrieve all commits even if a repo is a fork
def ensure_commits(user, repo, sha: nil, return_retrieved: false,
num_commits: -1, fork_all: false)
currepo = ensure_repo(user, repo)
unless currepo[:forked_from].nil? or fork_all
r = retrieve_repo(user, repo)
return if r.nil?
parent_owner = r['parent']['owner']['login']
parent_repo = r['parent']['name']
commits = ensure_fork_commits(user, repo, parent_owner, parent_repo)
return commits
end
num_retrieved = 0
commits = ['foo'] # Dummy entry for simplifying the loop below
commit_acc = []
commit_pages = 0
until commits.empty? or commit_pages >= config(:mirror_history_pages_back)
commits = retrieve_commits(repo, sha, user, 1)
commit_pages += 1
# This means that we retrieved the last commit page again
if commits.size == 1 and commits[0]['sha'] == sha
commits = []
end
retrieved = commits.map do |c|
sha = c['sha']
save{ensure_commit(repo, c['sha'], user)}
end
# Store retrieved commits to return, if client requested so
if return_retrieved
commit_acc = commit_acc << retrieved
end
num_retrieved += retrieved.size
if num_commits > 0 and num_retrieved >= num_commits
break
end
end
commit_acc.flatten.select{|x| !x.nil?}
end
##
# Get the parents for a specific commit. The commit must be first stored
# in the database.
def ensure_parents(commit, owner, repo)
commits = db[:commits]
parents = db[:commit_parents]
commit['parents'].map do |p|
save do
url = p['url'].split(/\//)
this = commits.first(:sha => commit['sha'])
parent = commits.first(:sha => url[7])
if parent.nil?
c = retrieve_commit(url[5], url[7], url[4])
if c.nil?
warn "Could not retrieve commit_parent #{url[4]}/#{url[5]} -> #{url[7]} to #{this[:sha]}"
next
end
parent = store_commit(c, repo, owner)
end
if parent.nil?
warn "Could not find #{url[4]}/#{url[5]} -> #{url[7]}, parent to commit #{this[:sha]}"
next
end
if parents.first(:commit_id => this[:id],
:parent_id => parent[:id]).nil?
parents.insert(:commit_id => this[:id],
:parent_id => parent[:id])
info "Added commit_parent #{parent[:sha]} to commit #{this[:sha]}"
else
debug "Parent #{parent[:sha]} for commit #{this[:sha]} exists"
end
parents.first(:commit_id => this[:id], :parent_id => parent[:id])
end
end.select{|x| !x.nil?}
end
##
# Make sure that a commit has been associated with the provided repo
# ==Parameters:
# [user] The user that owns the repo this commit has been submitted to
# [repo] The repo receiving the commit
# [sha] The commit SHA
def ensure_repo_commit(user, repo, sha)
project = ensure_repo(user, repo)
if project.nil?
warn "Repo #{user}/#{repo} does not exist"
return
end
commitid = db[:commits].first(:sha => sha)[:id]
exists = db[:project_commits].first(:project_id => project[:id],
:commit_id => commitid)
if exists.nil?
db[:project_commits].insert(
:project_id => project[:id],
:commit_id => commitid
)
info "Added commit_assoc #{sha} with #{user}/#{repo}"
db[:project_commits].first(:project_id => project[:id],
:commit_id => commitid)
else
debug "Association of commit #{sha} with repo #{user}/#{repo} exists"
exists
end
end
##
# Add (or update) an entry for a commit author. This method uses information
# in the JSON object returned by Github to add (or update) a user in the
# metadata database with a full user entry (both Git and Github details).
#
# ==Parameters:
# [githubuser] A hash containing the user's Github login
# [commituser] A hash containing the Git commit's user name and email
# == Returns:
# The (added/modified) user entry as a Hash.
def commit_user(githubuser, commituser)
users = db[:users]
name = commituser['name']
email = commituser['email'] #if is_valid_email(commituser['email'])
# Github user can be null when the commit email has not been associated
# with any account in Github.
login = githubuser['login'] unless githubuser.nil?
# web-flow is a special user reserved for web-based commits:
# https://api.github.com/users/web-flow
# We do not follow the process below as this user's email
# (noreply@github.com) clashes other existing users' emails.
if login == 'web-flow'
return ensure_user_byuname('web-flow')
end
return ensure_user("#{name}<#{email}>", false, false) if login.nil?
dbuser = users.first(:login => login)
byemail = users.first(:email => email)
if dbuser.nil?
# We do not have the user in the database yet
added = ensure_user(login, false, false)
if added.nil?
if byemail.nil?
# This means that the user's login has been associated with a
# Github user by the time the commit was done (and hence Github was
# able to associate the commit to an account), but afterwards the
# user has deleted his account (before GHTorrent processed it).
# On absense of something better to do, try to find the user by email
# and return a "fake" user entry.
warn "User account for user #{login} deleted from Github"
return ensure_user("#{name}<#{email}>", false, false)
else
# A commit user can be found by email but not
# by the user name he used to commit. This probably means that the
# user has probably changed his user name. Treat the user's by-email
# description as valid.
warn "Found user #{byemail[:login]} with same email #{email} as non existing user #{login}. Assigning user #{login} to #{byemail[:login]}"
return users.first(:login => byemail[:login])
end
else
if byemail.nil?
users.filter(:login => login).update(:name => name) if added[:name].nil?
users.filter(:login => login).update(:email => email) if added[:email].nil?
else
# There is a previous entry for the user, currently identified by
# email. This means that the user has updated their account and now
# Github is able to associate their commits with their git credentials.
# As the previous entry might have already associated records, just
# delete the new one and update the existing with any extra data.
info "Users #{login} and #{email} are the same. Attempting merge."
users.filter(:login => login).delete
users.filter(:email => email).update(
:login => login,
:name => if added[:name].nil? then byemail[:name] else added[:name] end,
:company => added[:company],
:location => added[:location],
:email => email,
:fake => false,
:deleted => false,
:type => user_type('USR'),
:long => added[:long],
:lat => added[:lat],
:country_code => added[:country_code],
:state => added[:state],
:city => added[:city],
:created_at => date(added[:created_at]),
:updated_at => date(Time.now))
end
end
else
users.filter(:login => login).update(:name => name) if dbuser[:name].nil?
users.filter(:login => login).update(:email => email) if dbuser[:email].nil?
end
users.first(:login => login)
end
##
# Ensure that a user exists, or fetch its latest state from Github
# ==Parameters:
# [user] The full email address in RFC 822 format or a login name to lookup
# the user by
# [followers] A boolean value indicating whether to retrieve the user's
# followers
# [orgs] A boolean value indicating whether to retrieve the organizations
# the user participates into
# ==Returns:
# If the user can be retrieved, it is returned as a Hash. Otherwise,
# the result is nil
def ensure_user(user, followers = true, orgs = true)
# Github only supports alpanums, dashes and square brackets in usernames.
# All other sympbols are treated as emails.
if not user.match(/^[\w\-\[\]]*$/)
begin
name, email = user.split("<")
email = email.split(">")[0]
name = name.strip unless name.nil?
email = email.strip unless email.nil?
rescue StandardError
warn "Not a valid email address: #{user}"
return
end
unless is_valid_email(email)
warn "Extracted email(#{email}) not valid for user #{user}"
end
u = ensure_user_byemail(email, name)
else
u = ensure_user_byuname(user)
ensure_user_followers(user) if followers
ensure_orgs(user) if orgs
end
return u
end
##
# Ensure that a user exists, or fetch its latest state from Github
# ==Parameters:
# user::
# The login name to lookup the user by
#
# == Returns:
# If the user can be retrieved, it is returned as a Hash. Otherwise,
# the result is nil
def ensure_user_byuname(user)
users = db[:users]
usr = users.first(:login => user)
if usr.nil?
u = retrieve_user_byusername(user)
if u.nil?
warn "User #{user} does not exist"
return
end
email = unless u['email'].nil?
if u['email'].strip == '' then
nil
else
u['email'].strip
end
end
geo = geolocate(location: u['location'])
users.insert(:login => u['login'],
:name => u['name'],
:company => u['company'],
:email => email,
:fake => false,
:deleted => false,
:type => user_type(u['type']),
:long => geo[:long],
:lat => geo[:lat],
:country_code => geo[:country_code],
:state => geo[:state],
:city => geo[:city],
:created_at => date(u['created_at']),
:updated_at => date(Time.now))
info "Added user #{user}"
if user_type(u['type']) == 'ORG'
info "User #{user} is an organization. Retrieving members"
ensure_org(u['login'], true)
end
users.first(:login => user)
else
debug "User #{user} exists"
usr
end
end
##
# Get all followers for a user. Since we do not know when the actual
# follow event took place, we set the created_at field to the timestamp
# of the method call.
#
# ==Parameters:
# [user] The user login to find followers by
def ensure_user_followers(followed)
curuser = ensure_user(followed, false, false)
followers = db.from(:followers, :users).\
where(Sequel.qualify('followers', 'follower_id') => Sequel.qualify('users', 'id')).\
where(Sequel.qualify('followers', 'user_id') => curuser[:id]).select(:login).all
retrieve_user_followers(followed).reduce([]) do |acc, x|
if followers.find {|y| y[:login] == x['login']}.nil?
acc << x
else
acc
end
end.map { |x| save{ensure_user_follower(followed, x['login']) }}.select{|x| !x.nil?}
end
##
# Make sure that a user follows another one
def ensure_user_follower(followed, follower, date_added = nil)
follower_user = ensure_user(follower, false, false)
followed_user = ensure_user(followed, false, false)
if followed_user.nil? or follower_user.nil?
warn "Could not find follower #{follower} or user #{followed}"
return
end
followers = db[:followers]
follower_id = follower_user[:id]
followed_id = followed_user[:id]
follower_exists = followers.first(:user_id => followed_id,
:follower_id => follower_id)
if follower_exists.nil?
added = if date_added.nil?
max(follower_user[:created_at], followed_user[:created_at])
else
date_added
end
retrieved = retrieve_user_follower(followed, follower)
if retrieved.nil?
warn "Could not retrieve follower #{follower} for #{followed}"
return
end
followers.insert(:user_id => followed_id,
:follower_id => follower_id,
:created_at => added)
info "Added follower #{follower} to #{followed}"
else
debug "Follower #{follower} for user #{followed} exists"
end
unless date_added.nil?
followers.filter(:user_id => followed_id, :follower_id => follower_id)
.update(:created_at => date(date_added))
info "Updated follower #{followed} -> #{follower}, created_at -> #{date(date_added)}"
end
followers.first(:user_id => followed_id, :follower_id => follower_id)
end
def ensure_user_following(user)
curuser = ensure_user(user, false, false)
following = db.from(:followers, :users).\
where(Sequel.qualify('followers', 'follower_id') => curuser[:id]).\
where(Sequel.qualify('followers', 'user_id') => Sequel.qualify('users','id')).\
select(:login).all
retrieve_user_following(user).reduce([]) do |acc, x|
if following.find {|y| y[:login] == x['follows']}.nil?
acc << x
else
acc
end
end.map { |x| save{ensure_user_follower(x['follows'], user) }}.select{|x| !x.nil?}
end
##
# Try to retrieve a user by email. Search the DB first, fall back to
# Github search API if unsuccessful.
#
# ==Parameters:
# [email] The email to lookup the user by
# [name] The user's name
# == Returns:
# If the user can be retrieved, it is returned as a Hash. Otherwise,
# the result is nil
def ensure_user_byemail(email, name)
users = db[:users]
usr = users.first(:email => email)
if usr.nil?
u = retrieve_user_byemail(email, name)
if u.nil? or u['login'].nil?
warn "Could not retrieve user #{email} through search API query"
login = (0...8).map { 65.+(rand(25)).chr }.join
users.insert(:email => email,
:name => name,
:login => login,
:fake => true,
:deleted => false,
:created_at => date(Time.now),
:updated_at => date(Time.now))
info "Added user fake #{login} -> #{email}"
users.first(:login => login)
else
in_db = users.first(:login => u['login'])
geo = geolocate(location: u['location'])
if in_db.nil?
users.insert(:login => u['login'],
:name => u['name'],
:company => u['company'],
:email => u['email'],
:long => geo[:long],
:lat => geo[:lat],
:country_code => geo[:country_code],
:state => geo[:state],
:city => geo[:city],
:fake => false,
:deleted => false,
:created_at => date(u['created_at']),
:updated_at => date(Time.now))
info "Added user #{u['login']} (#{email}) through search API query"
else
in_db.update(:name => u['name'],
:company => u['company'],
:email => u['email'],
:long => geo[:long],
:lat => geo[:lat],
:country_code => geo[:country_code],
:state => geo[:state],
:city => geo[:city],
:fake => false,
:deleted => false,
:created_at => date(u['created_at']),
:updated_at => date(Time.now))
debug "User #{u['login']} with email #{email} exists"
end
users.first(:login => u['login'])
end
else
debug "User with email #{email} exists"
usr
end
end
##
# Ensure that a repo exists, or fetch its latest state from Github
#
# ==Parameters:
# [user] The email or login name to which this repo belongs
# [repo] The repo name
#
# == Returns:
# If the repo can be retrieved, it is returned as a Hash. Otherwise,
# the result is nil
def ensure_repo(user, repo, recursive = false)
repos = db[:projects]
curuser = ensure_user(user, false, false)
if curuser.nil?
warn "Could not find user #{user}"
return
end
currepo = repos.first(:owner_id => curuser[:id], :name => repo)
unless currepo.nil?
debug "Repo #{user}/#{repo} exists"
return refresh_repo(user, repo, currepo)
end
r = retrieve_repo(user, repo, true)
if r.nil?
warn "Could not retrieve repo #{user}/#{repo}"
return
end
if r['owner']['login'] != curuser[:login]
info "Repo changed owner from #{curuser[:login]} to #{r['owner']['login']}"
user = r['owner']['login']
curuser = ensure_user(r['owner']['login'], false, false)
end
if r['name'] != repo
info "Repo changed name from #{repo} to #{r['name']}"
repo = r['name']
currepo = repos.first(:owner_id => curuser[:id], :name => repo)
return currepo unless currepo.nil?
end
repos.insert(:url => r['url'],
:owner_id => curuser[:id],
:name => r['name'],
:description => unless r['description'].nil? then r['description'][0..254] else nil end,
:language => r['language'],
:created_at => date(r['created_at']),
:updated_at => date(Time.now))
unless r['parent'].nil?
parent_owner = r['parent']['owner']['login']
parent_repo = r['parent']['name']
parent = ensure_repo(parent_owner, parent_repo)
if parent.nil?
warn "Could not find repo #{parent_owner}/#{parent_repo}, parent of: #{user}/#{repo}"
repos.filter(:owner_id => curuser[:id], :name => repo).update(:forked_from => -1)
else
repos.filter(:owner_id => curuser[:id], :name => repo).update(:forked_from => parent[:id])
info "Repo #{user}/#{repo} is a fork of #{parent_owner}/#{parent_repo}"
fork_commit = ensure_fork_point(user, repo)
if fork_commit.nil?
warn "Could not find fork point for #{user}/#{repo}, fork of #{parent_owner}/#{parent_repo}"
else
debug "#{user}/#{repo} was forked at #{fork_commit[:sha]} from #{parent_owner}/#{parent_repo}"
end
end
end
if recursive and not ensure_repo_recursive(user, repo)
warn "Could not retrieve #{user}/#{repo} recursively"
return nil
end
info "Added repo #{user}/#{repo}"
return repos.first(:owner_id => curuser[:id], :name => repo)
end
def ensure_repo_recursive(owner, repo)
stages.each do |x|
if send(x, owner, repo).nil?
warn "Stage #{x} returned nil, stopping recursive retrieval"
return false
end
end
true
end
# Get details about the languages used in the repository
def ensure_languages(owner, repo)
currepo = ensure_repo(owner, repo)
langs = retrieve_languages(owner, repo)
if langs.nil? or langs.empty?
warn "Could not find languages for repo #{owner}/#{repo}"
return
end
ts = Time.now
langs.keys.select{|x| x != 'etag'}.each do |lang|
db[:project_languages].insert(
:project_id => currepo[:id],
:language => lang.downcase,
:bytes => langs[lang],
:created_at => ts
)
info "Added project_language #{owner}/#{repo} -> #{lang} (#{langs[lang]} bytes)"
end
db[:project_languages].where(:project_id => currepo[:id]).where(:created_at => ts).all
end
# Fast path to project forking. Retrieve all commits page by page
# until we reach a commit that has been registered with the parent
# repository. Then, copy all remaining parent commits to this repo.
def ensure_fork_commits(owner, repo, parent_owner, parent_repo)
currepo = ensure_repo(owner, repo)
if currepo.nil?
warn "Could not find repo #{owner}/#{repo}"
return
end
parent = ensure_repo(parent_owner, parent_repo)
if parent.nil?
warn "Could not find repo #{parent_owner}/#{parent_repo}, parent of #{owner}/#{repo}"
return
end
strategy = case
when config(:fork_commits).match(/all/i)
:all
when config(:fork_commits).match(/fork_point/i)
:fork_point
when config(:fork_commits).match(/none/i)
:none
else
:fork_point
end
fork_commit = ensure_fork_point(owner, repo)
debug "Retrieving commits for fork #{owner}/#{repo}: strategy is #{strategy}"
return [] if strategy == :none
if strategy == :fork_point
if fork_commit.nil? or fork_commit.empty?
warn "Could not find fork commit for repo #{owner}/#{repo}. Will not retrieve commits."
return []
end
# Retrieve commits up to fork point (fork_commit strategy)
info "Retrieving commits for #{owner}/#{repo} until fork commit #{fork_commit[:sha]}"
master_branch = retrieve_default_branch(parent_owner, parent_repo)
return if master_branch.nil?
sha = master_branch
found = false
added_commits = []
while not found
commits = retrieve_commits(repo, sha, owner, 1)
# This means that we retrieved no commits
if commits.size == 0
break
end
# This means we retrieved the last page again
if commits.size == 1 and commits[0]['sha'] == sha
break
end
for c in commits
commit = ensure_commit(repo, c['sha'], owner)
sha = c['sha']
if c['sha'] == fork_commit[:sha]
found = true
break
else
added_commits << commit
end
end
end
return added_commits
end
if strategy == :all
shared_commit = db[:commits].first(:sha => fork_commit)
copied = 0
to_copy = db.from(:project_commits, :commits).\
where(Sequel.qualify('project_commits', 'commit_id') => Sequel.qualify('commits', 'id')).\
where(Sequel.qualify('project_commits', 'project_id') => parent[:id]).\
where('commits.created_at < ?', shared_commit[:created_at]).\
select(Sequel.qualify('commits','id'))
to_copy.each do |c|
copied += 1
begin
db[:project_commits].insert(
:project_id => currepo[:id],
:commit_id => c[:id]
)
debug "Copied commit #{c[:sha]} #{parent_owner}/#{parent_repo} -> #{owner}/#{repo} (#{copied} total)"
rescue StandardError => e
warn "Could not copy commit #{c[:sha]} #{parent_owner}/#{parent_repo} -> #{owner}/#{repo} : #{e.message}"
end
end
info "Finished copying commits from #{parent_owner}/#{parent_repo} -> #{owner}/#{repo}: #{copied} total"
return to_copy
end
end
# Retrieve and return the commit at which the provided fork was forked at
def ensure_fork_point(owner, repo)
fork = ensure_repo(owner, repo, false)
if fork[:forked_from].nil?
warn "Repo #{owner}/#{repo} is not a fork"
return nil
end
# Return commit if already specified
unless fork[:forked_commit_id].nil?
commit = db[:commits].where(:id => fork[:forked_commit_id]).first
return commit unless commit.nil?
end
parent = db.from(:projects, :users).\
where(Sequel.qualify('projects', 'owner_id') => Sequel.qualify('users', 'id')).\
where(Sequel.qualify('projects', 'id') => fork[:forked_from]).\
select(Sequel.qualify('users', 'login'), Sequel.qualify('projects','name')).first
if parent.nil?
warn "Unknown parent for repo #{owner}/#{repo}"
return nil
end
default_branch = retrieve_default_branch(parent[:login], parent[:name])
# Retrieve diff between parent and fork master branch
diff = retrieve_master_branch_diff(owner, repo, default_branch, parent[:login], parent[:name], default_branch)
if diff.nil? or diff.empty?
# Try a bit harder by refreshing the default branch
default_branch = retrieve_default_branch(parent[:login], parent[:name], true)
diff = retrieve_master_branch_diff(owner, repo, default_branch, parent[:login], parent[:name], default_branch)
end
if diff.nil? or diff.empty?
# This means that the are no common ancestors between the repos
# This can apparently happen when the parent repo was renamed or force-pushed
# example: https://github.com/openzipkin/zipkin/compare/master...aa1wi:master
warn "No common ancestor between #{parent[:login]}/#{parent[:name]} and #{owner}/#{repo}"
return nil
else
debug "Fork #{owner}/#{repo} is #{diff['ahead_by']} commits ahead and #{diff['behind_by']} commits behind #{parent[:login]}/#{parent[:name]}"
end
if diff['ahead_by'].to_i > 0
# This means that the fork has diverged, and we need to search through the fork
# commit graph for the earliest commit that is shared with the parent. GitHub's
# diff contains a list of divergent commits. We are sorting those by date
# and select the earliest one. We do date sort instead of graph walking as this
# would be prohibetively slow if the commits for the parent did not exist.
earliest_diverging = diff['commits'].sort_by{|x| x['commit']['author']['date']}.first
if earliest_diverging['parents'].nil?
# this means that the repo was forked from the from the parent repo's initial commit. thus, they both share an initial commit.
# example: https://api.github.com/repos/btakita/pain-point/compare/master...spent:master
likely_fork_point = ensure_commit(parent[:name], earliest_diverging['sha'], parent['login'])
else
# Make sure that all likely fork points exist for the parent project
# and select the latest of them.
# https://github.com/gousiosg/github-mirror/compare/master...pombredanne:master
likely_fork_point = earliest_diverging['parents'].\
map{ |x| ensure_commit(parent[:name], x['sha'], parent[:login])}.\
select{|x| !x.nil?}.\
sort_by { |x| x[:created_at]}.\
last
end
forked_sha = likely_fork_point[:sha]
else
# This means that the fork has not diverged.
forked_sha = diff['merge_base_commit']['sha']
end
forked_commit = ensure_commit(repo, forked_sha, owner);
debug "Fork commit for #{owner}/#{repo} is #{forked_sha}"
unless forked_commit.nil?
db[:projects].filter(:id => fork[:id]).update(:forked_commit_id => forked_commit[:id])
info "Repo #{owner}/#{repo} was forked at #{parent[:login]}/#{parent[:name]}:#{forked_sha}"
end
db[:commits].where(:sha => forked_sha).first
end
##
# Make sure that the organizations the user participates into exist
#
# ==Parameters:
# [user] The login name of the user to check the organizations for
#
def ensure_orgs(user)
retrieve_orgs(user).map{|o| save{ensure_participation(user, o['login'])}}.select{|x| !x.nil?}
end
##
# Make sure that a user participates to the provided organization
#
# ==Parameters:
# [user] The login name of the user to check the organizations for
# [org] The login name of the organization to check whether the user
# belongs in
#
def ensure_participation(user, organization, members = true)
org = ensure_org(organization, members)
if org.nil?
warn "Could not find organization #{organization}"
return
end
usr = ensure_user(user, false, false)
org_members = db[:organization_members]
participates = org_members.first(:user_id => usr[:id], :org_id => org[:id])
if participates.nil?
org_members.insert(:user_id => usr[:id],
:org_id => org[:id])
info "Added participation #{organization} -> #{user}"
org_members.first(:user_id => usr[:id], :org_id => org[:id])
else
debug "Participation #{organization} -> #{user} exists"
participates
end
end
##
# Make sure that an organization exists
#
# ==Parameters:
# [organization] The login name of the organization
#
def ensure_org(organization, members = true)
org = db[:users].first(:login => organization, :type => 'org')
if org.nil?
org = ensure_user(organization, false, false)
# Not an organization, don't go ahead
if org[:type] != 'ORG'
warn "User #{organization} is not an organization"
return nil
end
end
if members
retrieve_org_members(organization).map do |x|
ensure_participation(ensure_user(x['login'], false, false)[:login],
organization, false)
end
end
org
end
##
# Get all comments for a commit
#
# ==Parameters:
# [user] The login name of the organization
# [user] The repository containing the commit whose comments will be retrieved
# [sha] The commit sha to retrieve comments for
def ensure_commit_comments(user, repo, sha)
commit_id = db[:commits].first(:sha => sha)[:id]
stored_comments = db[:commit_comments].filter(:commit_id => commit_id)
commit_comments = retrieve_commit_comments(user, repo, sha)
not_saved = commit_comments.reduce([]) do |acc, x|
if stored_comments.find{|y| y[:comment_id] == x['id']}.nil?
acc << x
else
acc
end
end
not_saved.map{|x| save{ensure_commit_comment(user, repo, sha, x['id'])}}.select{|x| !x.nil?}
end
def ensure_commit_comment(owner, repo, sha, comment_id)
stored_comment = db[:commit_comments].first(:comment_id => comment_id)
if stored_comment.nil?
retrieved = retrieve_commit_comment(owner, repo, sha, comment_id)
if retrieved.nil?
warn "Could not retrieve commit_comment #{sha}->#{comment_id}"
return
end
commit = ensure_commit(repo, sha, owner, false)
if commit.nil?
warn "Could not ensure commit: #{sha} in repo: #{owner}/#{repo}"
return
end
user = ensure_user(retrieved['user']['login'], false, false)
if user.nil?
warn "Could not ensure user: #{retrieved['user']['login']}"
return
end
db[:commit_comments].insert(
:commit_id => commit[:id],
:user_id => user[:id],
:body => retrieved['body'][0..255],
:line => retrieved['line'],
:position => retrieved['position'],
:comment_id => retrieved['id'],