-
Notifications
You must be signed in to change notification settings - Fork 22
/
autoncore.py
1942 lines (1756 loc) · 70.4 KB
/
autoncore.py
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
#!/usr/bin/python
#
# Copyright 2012-2013 Ontology Engineering Group, Universidad Politecnica de Madrid, Spain
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @author Ahmad Alobaid
#
# try:
# from OnToology.models import *
# # from models import *
# except:
# from djangoperpmod import *
# # from models import *
# from OnToology.models import *
from github import Github
from datetime import datetime
from subprocess import call
import string
import random
import time
import sys
import traceback
from io import StringIO ## for Python 3
try:
print("importing OnToology...")
import OnToology
print("Success")
except:
print("Importing djangoperpmode")
import djangoperpmod
print("Imported it")
print("autonecore continue")
from OnToology import settings
from OnToology.models import *
import io
import configparser as ConfigParser
from OnToology.__init__ import *
import Integrator
import shutil
import logging
from urllib.parse import quote
use_database = True
#ToolUser = 'OnToologyUser'
ToolUser = os.environ['github_username']
ToolEmail = os.environ['github_email']
parent_folder = None
publish_dir = os.environ['publish_dir']
home = os.environ['github_repos_dir'] # e.g. home = 'blahblah/temp/'
verification_log_fname = 'verification.log'
sleeping_time = 7
refresh_sleeping_secs = 10 # because github takes time to refresh
ontology_formats = ['.rdf', '.owl', '.ttl']
g = None
log_file_dir = None # '&1'#which is stdout #sys.stdout#by default
tools_conf = {
'ar2dtool': {'folder_name': 'diagrams', 'type': 'png'},
'widoco': {'folder_name': 'documentation'},
'oops': {'folder_name': 'evaluation'},
'owl2jsonld': {'folder_name': 'context'}
}
def prepare_logger(user, ext='.log_new'):
sec = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(9)])
l = os.path.join(home, 'log', user + sec + ext)
f = open(l, 'w')
f.close()
logging.basicConfig(filename=l, format='%(asctime)s %(levelname)s: %(message)s', level=logging.DEBUG)
return l
def dolog(msg):
print("dolog> "+msg)
logging.critical(msg)
def init_g():
global g
username = os.environ['github_username']
password = os.environ['github_password']
if settings.DEBUG == True:
print("init_g> debug")
from OnToology.mock import mock_dict
if 'mock_id' in os.environ and os.environ['mock_id'].strip() != "":
print("init_g> mock_id in environ: ")
mock_id = os.environ['mock_id']
m = mock_dict[mock_id]
print("init_g> mock: ")
# import pprint
# pp = pprint.PrettyPrinter(indent=1)
# pp.pprint(m)
print(m.keys())
g = Github(username, password, mock=m)
else:
print("init_g> mock_id is not in environ")
g = Github(username, password)
else:
g = Github(username, password)
print("init_g> No mock id")
return g
def git_magic(target_repo, user, changed_filesss, branch, raise_exp=False):
"""
:param target_repo: user/reponame
:param user: user email
:param changed_filesss: list of changed files
:param branch: the branch of the changed
:return:
"""
global g
global parent_folder
global log_file_dir
print("\n\n\n In gitmagic print")
print("printing test_conf from magic")
print(settings.test_conf)
logger_fname = prepare_logger(user)
parent_folder = user
if not settings.test_conf['local']:
prepare_log(user)
dolog('############################### magic #############################')
dolog("1> number of users: %d" % len(OUser.objects.all()))
dolog('target_repo: <%s>' % target_repo)
dolog("branch: %s" % branch)
drepo = Repo.objects.get(url=target_repo)
drepo.state = 'Preparing'
drepo.save()
dolog("have the repo now")
drepo.clear_ontology_status_pairs()
dolog("cleared")
dolog("2> number of users: %d" % len(OUser.objects.all()))
dolog("looking for user: <%s> " % (str(user)))
ouser = OUser.objects.get(email=user)
dolog("got the ouser")
orun = ORun(user=ouser, repo=drepo, branch=branch)
orun.save()
dolog("created the orun")
otask = OTask(name='Preparation', finished=False, success=False, description="", orun=orun)
dolog("otask is init")
otask.save()
dolog("otask is saved")
otask.description = 'Getting changed files'
dolog("created the otask")
# orun.tasks.add(otask)
# orun.save()
dolog("added the task to run")
try:
for ftov in changed_filesss:
if ftov[-4:] in ontology_formats:
if ftov[:len('OnToology/')] != 'OnToology/': # This is to solve bug #265
dolog("update ontology status")
dolog("ontology: "+ftov)
drepo.update_ontology_status(ontology=ftov, status='pending')
dolog("ontology status is updated")
# so the tool user can takeover and do stuff
dolog("pre block")
g = init_g()
if not settings.test_conf['local'] or settings.test_conf['fork'] or settings.test_conf[
'clone']: # in case it is not test or test with fork option
dolog('will fork the repo')
drepo.state = 'forking repo'
otask.description += 'fork the repo'
otask.save()
forked_repo = fork_repo(target_repo)
cloning_url = forked_repo.ssh_url
time.sleep(refresh_sleeping_secs)
dolog('repo forked: '+str(cloning_url))
drepo.progress = 10.0
drepo.save()
else:
print("no fork")
if not settings.test_conf['local'] or settings.test_conf['clone']:
drepo.state = 'cloning repo'
drepo.save()
otask.description = 'Clone the repo'
otask.save()
clone_repo(cloning_url, user, branch=branch)
dolog('repo cloned')
drepo.progress = 20.0
files_to_verify = []
if log_file_dir is None:
prepare_log(user)
otask.success = True
otask.save()
except Exception as e:
dolog("Exception: "+str(e))
traceback.print_exc()
otask.success = False
otask.finished = True
otask.description = str(e)
otask.save()
drepo.state = 'Ready'
drepo.notes+= str(e)
drepo.progress = 100
drepo.save()
if raise_exp:
raise Exception(str(e))
return
otask.finished = True
otask.save()
drepo.state = 'Tools'
drepo.save()
try:
Integrator.tools_execution(changed_files=changed_filesss, base_dir=os.path.join(home, user), logfile=log_file_dir,
target_repo=target_repo, g_local=g, dolog_fname=logger_fname,
change_status=change_status, repo=drepo, orun=orun)
except Exception as e:
dolog("Exception: " + str(e))
traceback.print_exc()
# otask.success = False
# otask.finished = True
# otask.description = str(e)
# otask.save()
drepo.state = 'Ready'
drepo.notes += str(e)
drepo.progress = 100
drepo.save()
if raise_exp:
raise Exception(str(e))
return
otask = OTask(name="Postprocessing", description="trying", success=False, finished=False, orun=orun)
otask.save()
# orun.tasks.add(otask)
# orun.save()
try:
otask.description = "verifying changed files"
otask.save()
files_to_verify = [c for c in changed_filesss if c[-4:] in ontology_formats]
for c in changed_filesss:
if c[:-4] in ontology_formats:
print("file to verify: " + c)
else:
print("c: %s c-4: %s" % (c, c[-4:]))
otask.description = "preparing the repo after the processing"
otask.save()
# After the loop
dolog("number of files to verify %d" % (len(files_to_verify)))
if len(files_to_verify) == 0:
print("files: " + str(files_to_verify))
drepo.state = 'Ready'
drepo.notes = ''
drepo.progress = 100
drepo.save()
return
# if not test or test with push
if not settings.test_conf['local'] or settings.test_conf['push']:
dolog("will commit the changed")
commit_changes()
dolog('changes committed')
else:
dolog('No push for testing')
otask.description = "Removing old pull requests"
otask.save()
# remove_old_pull_requests(target_repo)
otask.description = "Generating pull request"
otask.save()
if settings.test_conf['pull']:
print("pull is true")
else:
print("pull is false")
if not settings.test_conf['local'] or settings.test_conf['pull']:
drepo.state = 'creating a pull request'
drepo.save()
try:
remove_old_pull_requests(target_repo)
time.sleep(5)
r = send_pull_request(target_repo, ToolUser, branch)
if r['status']:
dolog('pull request is sent')
drepo.notes = ''
drepo.state = 'Ready'
drepo.save()
else:
dolog('Error generating the pull request')
drepo.notes = r['error']
drepo.state = 'Ready'
drepo.save()
raise Exception(r['error'])
except Exception as e:
print("exception: " + str(e))
traceback.print_exc()
exception_if_exists = str(e)
dolog('We have not been able to create the pull request. Please contact us to analyze the issue. ' + exception_if_exists)
drepo.notes = 'We have not been able to create the pull request. Please contact us to analyze the issue.'
drepo.progress = 100
drepo.state = 'Ready'
drepo.save()
otask.success = False
otask.finished = True
otask.save()
if raise_exp:
raise Exception(str(e))
return
else:
dolog("No pull for testing 11")
print('No pull for testing 11')
drepo.state = 'Ready'
drepo.save()
drepo.progress = 100
drepo.save()
otask.success = True
otask.save()
except Exception as e:
print("exception: "+str(e))
traceback.print_exc()
otask.success = False
otask.description = str(e)
otask.save()
otask.finished = True
otask.save()
if raise_exp:
raise Exception(str(e))
otask.finished = True
otask.save()
def update_file(target_repo, path, message, content, branch=None, g_local=None):
"""
Update the file on GitHub
:param target_repo:
:param path:
:param message:
:param content:
:param branch:
:param g_local:
:return:
"""
global g
if g_local is None:
gg = init_g()
# if g is None:
# gg = init_g()
# else:
# gg = g
print("update_file> get g from init_g")
else:
gg = g_local
print("update_file> g local")
print("*****\n\n\n\n\n\n\nupdate_file> gg: "+str(gg))
print("vget user: "+str(gg.get_user()))
print("\n\n\nupdate_file> *** branch: "+str(branch))
print("path: "+path)
clean_path = path
if path[0] == '/':
clean_path = clean_path[1:]
# username = os.environ['github_username']
# password = os.environ['github_password']
# g = Github(username, password)
repo = gg.get_repo(target_repo)
if branch is None:
sha = repo.get_contents(path).sha
dolog('update_file> default branch with file sha: %s' % str(sha))
else:
print("update_file> get_contents: ")
cont = repo.get_contents(path, branch)
print(cont)
sha = cont.sha
dolog('branch %s with file %s sha: %s' % (branch, clean_path, str(sha)))
apath = clean_path.strip()
# dolog("username: " + username)
dolog('will update the file <%s> on repo <%s> with the content <%s>, sha <%s> and message <%s>' %
(apath, target_repo, content, sha, message))
dolog("repo.update_file('%s', '%s', \"\"\"%s\"\"\" , '%s' )" % (apath, message, content, sha))
for i in range(3):
try:
if branch is None:
repo.update_file(apath, message, content, sha)
else:
repo.update_file(apath, message, content, sha, branch=branch)
dolog('file updated')
return
except:
dolog('chance #%d file update' % i)
time.sleep(3)
dolog('after x chances, still could not update ')
# so if there is a problem it will raise an exception which will be captured by the calling function
repo.update_file(apath, message, content, sha)
def verify_tools_generation(ver_file_comp, repo=None):
# AR2DTool
if ver_file_comp['ar2dtool_enable']:
target_file = os.path.join(get_abs_path(get_target_home()),
ver_file_comp['file'],
tools_conf['ar2dtool']['folder_name'],
Integrator.ar2dtool.ar2dtool_config_types[0][:-5],
get_file_from_path(ver_file_comp['file']) +
"." + tools_conf['ar2dtool']['type'] +
'.graphml')
file_exists = os.path.isfile(target_file)
if repo is not None and not file_exists:
repo.state += ' The Diagram of the file %s is not generated ' % \
(ver_file_comp['file'])
repo.save()
if settings.test_conf['local']:
assert file_exists, 'the file %s is not generated' % (target_file)
elif not file_exists:
dolog('The Diagram of the file %s is not generated ' %
(ver_file_comp['file']))
# Widoco
if ver_file_comp['widoco_enable']:
target_file = os.path.join(get_abs_path(get_target_home()), ver_file_comp['file'],
tools_conf['widoco']['folder_name'],
'index.html')
file_exists = os.path.isfile(target_file)
if repo is not None and not file_exists:
repo.state += ' The Documentation of the file %s if not generated ' % (
ver_file_comp['file'])
repo.save()
if settings.test_conf['local']:
assert file_exists, 'the file %s is not generated' % (target_file)
elif not file_exists:
dolog('The Documentation of the file %s if not generated ' %
(ver_file_comp['file']))
# OOPS
if ver_file_comp['oops_enable']:
target_file = os.path.join(get_abs_path(get_target_home()), ver_file_comp['file'],
tools_conf['oops']['folder_name'],
'oopsEval.html')
file_exists = os.path.isfile(target_file)
if repo is not None and not file_exists:
repo.state += ' The Evaluation report of the file %s if not generated ' % (
ver_file_comp['file'])
repo.save()
if settings.test_conf['local']:
assert file_exists, 'the file %s is not generated' % (target_file)
elif not file_exists:
dolog('The Evaluation report of the file %s if not generated ' %
(ver_file_comp['file']))
# owl2jsonld
if ver_file_comp['owl2jsonld_enable']:
target_file = os.path.join(get_abs_path(get_target_home()),
ver_file_comp['file'],
tools_conf['owl2jsonld']['folder_name'],
'context.jsonld')
file_exists = os.path.isfile(target_file)
if repo is not None and not file_exists:
repo.state += ' The Context documentation of the file %s if not generated ' % (
ver_file_comp['file'])
repo.save()
if settings.test_conf['local']:
assert file_exists, 'the file %s is not generated' % (target_file)
elif not file_exists:
dolog('The Context documentation of the file %s if not generated ' %
(ver_file_comp['file']))
if 'not generated' in repo.state:
repo = g.get_repo(repo.url)
for iss in repo.get_issues():
if 'OnToology error notification' in iss.title:
iss.edit(state='closed')
repo.create_issue('OnToology error notification', repo.state)
def get_ontologies_from_a_submodule(path, url):
"""
:param path: local path within the repository
:param url: url of the repository
:return: list of detected ontologies
"""
global g
ontologies = []
print("get_ontologies_from_a_submodule: path=%s and url=%s" % (path, url))
try:
target_repo = ("/".join(url.split('/')[-2:])).strip()[:-4]
repo = g.get_repo(target_repo)
sha = repo.get_commits()[0].sha
files = repo.get_git_tree(sha=sha, recursive=True).tree
ontoology_home_name = 'OnToology'
for f in files:
if f.path[:len(ontoology_home_name)] != ontoology_home_name:
if f.type == 'blob':
for ontfot in ontology_formats:
if f.path[-len(ontfot):] == ontfot:
print("get_ontologies_from_a_submodule f.path: %s" % f.path)
ontologies.append(os.path.join(path, f.path))
break
except Exception as e:
print("get_ontologies_from_a_submodule exception: " + str(e))
return ontologies
def get_ontologies_from_submodules_tree(tree, repo):
"""
:param tree: a github tree
:param repo: a repo object from GitHub
:return: a list of detected ontologies
"""
ontologies = []
submodule_tree_elements = [f for f in tree if f.path == '.gitmodules']
if len(submodule_tree_elements) == 1:
config_parser = ConfigParser.ConfigParser()
subm_tree_ele = submodule_tree_elements[0]
print("tree ele: ")
print(subm_tree_ele)
print("path: ")
print(subm_tree_ele.path)
file_content = repo.get_contents(subm_tree_ele.path).decoded_content
print("file_content")
file_content = file_content.decode('utf-8')
print(file_content)
### GOBACK
#
# config = ConfigParser.ConfigParser()
# print("config raw parser")
# if from_string:
# config_obj = config.read_string(conf_file_abs)
#
# file_content = repo.get_contents(p).decoded_content
# print("type: "+str(type(file_content)))
# # file_content = str(file_content)
# file_content = file_content.decode('utf-8')
# print("file_content: " + file_content)
# # buffile = StringIO(file_content)
# print("will get the config")
# confs = get_auton_config(file_content, from_string=True)
# print("gotten confs: " + str(confs))
# o = {}
# # o['ontology'] = get_parent_path(cpath.path)[len(get_target_home()):]
# o['ontology'] = get_parent_path(p)[len(get_target_home()):]
# for c in confs:
# #tool = c.replace('_enable', '')
# tool = c
# o[tool] = confs[c]
# ontologies.append(o)
file_content = file_content.replace('\t', '') # because it was containing \t
config_obj = config_parser.read_string(file_content)
# config_parser.readfp(io.BytesIO(file_content))
sections = config_parser.sections()
for sec in sections:
p = config_parser.get(sec, "path")
u = config_parser.get(sec, "url")
ontologies += get_ontologies_from_a_submodule(path=p, url=u)
return ontologies
def get_ontologies_in_online_repo(target_repo):
global g
ontologies = []
try:
g = init_g()
print("asking for repo: <%s>" % target_repo)
repo = g.get_repo(target_repo)
print("asking for commits")
sha = repo.get_commits()[0].sha
print("asking for files")
files = repo.get_git_tree(sha=sha, recursive=True).tree
ontoology_home_name = 'OnToology'
for f in files:
if f.path[:len(ontoology_home_name)] != ontoology_home_name:
if f.type == 'blob':
for ontfot in ontology_formats:
if f.path[-len(ontfot):] == ontfot:
ontologies.append(f.path)
break
ontologies += get_ontologies_from_submodules_tree(files, repo)
except Exception as e:
print("get_ontologies_in_online_repo exception: " + str(e))
traceback.print_exc()
return ontologies
def prepare_log(user):
global log_file_dir
global default_stderr
global default_stdout
file_dir = build_file_structure(user + '.log', 'log', home)
f = open(file_dir, 'w')
log_file_dir = file_dir
return f
def is_organization(target_repo):
return g.get_repo(target_repo).organization is not None
def has_access_to_repo(target_repo):
global g
id = g.get_user().id
if is_organization(target_repo):
try:
collaborators = g.get_repo(target_repo).get_collaborators()
for coll in collaborators:
if id == coll.id:
return True
return False
except:
return False
return True
def delete_repo(local_repo):
global g
if g is None:
init_g()
try:
g.get_repo(local_repo).delete()
dolog('repo deleted ')
except:
dolog('the repo doesn\'t exists [not an error]')
def fork_repo(target_repo):
"""
:param target_repo: username/reponame
:return: forked repo (e.g. OnToologyUser/reponame)
"""
# the wait time to give github sometime so the repo can be forked
# successfully
# time.sleep(sleeping_time)
gg = init_g()
repo = gg.get_repo(target_repo)
user = gg.get_user()
dolog("To fork repo: "+target_repo)
try:
gg.get_repo("%s/%s" % (user.name,repo.name)).delete()
dolog("deleted %s/%s" % (user.name,repo.name))
except:
dolog("did not delete %s/%s" % (user.name,repo.name))
for i in range(1,3):
try:
gg.get_repo("%s/%s-%d" % (user.name,repo.name,i)).delete()
dolog("deleted %s/%s-%d" % (user.name,repo.name,i))
except:
dolog("did not delete %s/%s-%d" % (user.name,repo.name,i))
time.sleep(sleeping_time)
forked_repo = user.create_fork(repo)
dolog("forked repo")
dolog('forked to: ' + forked_repo.name)
return forked_repo
def clone_repo(cloning_url, parent_folder, dosleep=True, branch=None):
"""
:param cloning_url:
:param parent_folder: just the name of the new direct folder name to be created if it does not exists
:param dosleep:
:param branch:
:return: the abs path
"""
if branch is None:
raise Exception("clone_repo> branch is not passed")
global g
if g is None:
init_g()
dolog('home: %s' % (home))
dolog('parent_folder: %s' % (parent_folder))
# dolog('logfile: %s' % (log_file_dir))
if dosleep:
# the wait time to give github sometime so the repo can be cloned
time.sleep(sleeping_time)
try:
# comm = "rm" + " -Rf " + home + parent_folder
comm = "rm" + " -Rf " + os.path.join(home, parent_folder)
# if not settings.test_conf['local']:
# comm += ' >> "' + log_file_dir + '"'
dolog(comm)
call(comm, shell=True)
except Exception as e:
dolog('rm failed: ' + str(e))
# comm = "git" + " clone" + " " + cloning_repo + " " + home + parent_folder
comm = "git clone "+"--single-branch --branch "+branch+" --recurse-submodules " + cloning_url + " " + os.path.join(home, parent_folder)
# if not settings.test_conf['local']:
# comm += ' >> "' + log_file_dir + '"'
dolog(comm)
# print("comm: %s" % comm)
call(comm, shell=True)
# dolog(comm)
# call(comm, shell=True)
# comm = "chmod -R 777 " + home + parent_folder
# if not settings.TEST:
# comm += ' >> "' + log_file_dir + '"'
# dolog(comm)
# call(comm, shell=True)
# return home + parent_folder
return os.path.join(home, parent_folder)
def commit_changes():
global g
if g is None:
init_g()
# gu = 'git config user.email "ontoology' + '@delicias.dia.fi.upm.es";'
gu = 'git config user.email "%s" ; ' % ToolEmail
gu += 'git config user.name "%s" ;' % (ToolUser)
# comm = "cd " + home + parent_folder + ";" + gu + " git add . "
comm = "cd " + os.path.join(home, parent_folder) + ";" + gu + " git add . "
if not settings.test_conf['local']:
comm += ' >> "' + log_file_dir + '"'
dolog(comm)
if settings.test_conf['push'] or not settings.test_conf['local']:
call(comm, shell=True)
# comm = "cd " + home + parent_folder + ";" + \
comm = "cd " + os.path.join(home, parent_folder) + ";" + \
gu + " git commit -m 'automated change' "
if not settings.test_conf['local']:
comm += ' >> "' + log_file_dir + '"'
dolog(comm)
if settings.test_conf['push'] or not settings.test_conf['local']:
call(comm, shell=True)
gup = "git config push.default matching;"
# comm = "cd " + home + parent_folder + ";" + gu + gup + " git push "
comm = "cd " + os.path.join(home, parent_folder) + ";" + gu + gup + " git push "
if not settings.test_conf['local']:
comm += ' >> "' + log_file_dir + '"'
dolog(comm)
if settings.test_conf['push'] or not settings.test_conf['local']:
call(comm, shell=True)
def refresh_repo(target_repo):
global g
if g is None:
init_g()
local_repo = target_repo.split('/')[-1]
g.get_user().get_repo(local_repo).delete()
g.get_user().create_fork(target_repo)
def remove_old_pull_requests(target_repo):
global g
if g is None:
init_g()
title = 'OnToology update'
for p in g.get_repo(target_repo).get_pulls():
try:
if p.title == title:
p.edit(state="closed")
except Exception as e:
print("Exception removing an old pull request: " + str(e))
dolog("Exception removing an old pull request: " + str(e))
def send_pull_request(target_repo, username, branch):
title = 'OnToology update'
body = title
err = ""
time.sleep(sleeping_time)
repo = g.get_repo(target_repo)
try:
repo.create_pull(head=username + ':%s' % branch, base='%s' % branch, title=title, body=body)
return {'status': True, 'msg': 'pull request created successfully'}
except Exception as e:
err = str(e)
dolog('pull request error: ' + err)
if 'No commits between' in err:
dolog('pull request detecting no commits')
r = Repo.objects.get(url=target_repo)
r.notes = 'No difference to generate the pull request, make a change in the repo so the pull request can be generated.'
r.save()
return {'status': False, 'error': err}
def webhook_access(client_id, redirect_url, isprivate):
if isprivate:
scope = 'repo'
else:
scope = 'public_repo'
# scope = 'admin:org_hook'
# scope+=',admin:org,admin:public_key,admin:repo_hook,gist,notifications,delete_repo,repo_deployment,
# repo,public_repo,user,admin:public_key'
sec = ''.join([random.choice(string.ascii_letters + string.digits)
for _ in range(9)])
return "https://github.com/login/oauth/authorize?client_id=" + client_id + "&redirect_uri=" + \
redirect_url + "&scope=" + scope + "&state=" + sec, sec
def get_user_github_email(username):
try:
return g.get_user(username).email
except:
return None
def remove_webhook(target_repo, notification_url):
global g
if g is None:
init_g()
# for some reason adding the below two prints solves the problem for removing the webhook, strange but true
print("target_repo: " + str(target_repo))
print("notification url: " + str(notification_url))
for hook in g.get_repo(target_repo).get_hooks():
try:
if hook.config["url"] == notification_url:
hook.delete()
break
except Exception as e:
print("error removing the webhook: %s" % (str(e)))
time.sleep(2)
sys.stdout.flush()
sys.stderr.flush()
def add_webhook(target_repo, notification_url, newg=None):
global g
if newg is None:
if g is None:
init_g()
newg = g
name = "web"
active = True
events = ["push"]
config = {
"url": notification_url,
"content_type": "form"
}
try:
newg.get_repo(target_repo).create_hook(name, config, events, active)
return {'status': True}
except Exception as e:
return {'status': False, 'error': str(e)} # e.data}
def add_collaborator(target_repo, user, newg=None):
global g
if newg is None:
if g is None:
g = init_g()
newg = g
try:
print("in try")
u = newg.get_user()
print(u)
print("user name: "+str(u.name))
print("email: "+str(u.email))
print("adding collaborator from user: %s " % str(newg.get_user().name))
print("goring for the first")
if u.name is None or u.email is None:
print("no email or name")
return {'status': False, 'error': 'Make sure you have your name and email public and not empty on GitHub'}
if newg.get_repo(target_repo).has_in_collaborators(user):
print("collaborator already there")
return {'status': True, 'msg': 'this user is already a collaborator'}
else:
print("going to collaborator\n\n")
invitation = newg.get_repo(target_repo).add_to_collaborators(user)
print("got a reply")
print(invitation)
if invitation is None:
print("no invitation is created")
return {'status': False, 'error': 'Invitation is not generated'}
else:
print("invitation exists")
try:
print("go to init")
init_g()
print("try to acceept invitation")
# username = os.environ['github_username']
# password = os.environ['github_password']
# g_ontoology_user = Github(username, password)
# g_ontoology_user.get_user().accept_invitation(invitation)
g.get_user().accept_invitation(invitation)
print("invitation accepted: " + str(invitation))
return {'status': True, 'msg': 'added as a new collaborator'}
except Exception as e:
print("exception: " + str(e))
print("invitation not accepted or invalid: " + str(invitation))
traceback.print_exc()
return {'status': False, 'error': 'Could not accept the invitation for becoming a collaborator'}
except Exception as e:
print("add_collaborator> Exception: "+str(e))
traceback.print_exc()
return {'status': False, 'error': str(e)} # e.data}
def previsual(useremail, target_repo, branch):
"""
:param useremail: email of the repo owner
:param target_repo: owner/reponame
:param branch: e.g., master
:return: error, orun
"""
from Integrator.previsual import start_previsual
prepare_logger(useremail+"-prev-")
dolog("starting previsual function with ontology: %s" % target_repo)
orun = None
otask = None
try:
dolog("previsual> trying the previsual")
users = OUser.objects.filter(email=useremail)
if len(users) != 1:
error_msg = "%s is invalid email" % useremail
dolog("previsual> " + error_msg)
return error_msg, None
user = users[0]
repo = None
repos = Repo.objects.filter(ousers=user, url=target_repo)
# for r in user.repos.all():
# if target_repo == r.url:
# found = True
# repo = r
# break
if len(repos) > 0:
repo = repos[0]
orun = ORun(user=user, repo=repo, branch=branch)
orun.save()
dolog("previsual> created the orun")
otask = OTask(name='Cloning the repo', finished=False, success=False, description="prepaaring the previsualization", orun=orun)
dolog("previsual> otask is init")
otask.save()
dolog("previsual> repo is found and now generating previsualization")
repo.state = 'Generating Previsualization'
repo.notes = ''
# repo.previsual_page_available = True
repo.save()
# prepare_log(user.email)
# cloning_repo should look like 'git@github.com:AutonUser/target.git'
cloning_repo = 'git@github.com:%s.git' % target_repo
sec = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(4)])
folder_name = 'prevclone-' + sec
if not settings.test_conf['local'] or settings.test_conf['clone']:
otask.description = "Cloning the repo"
otask.save()
clone_repo(cloning_repo, folder_name, dosleep=True, branch=branch)
otask.description = "Cloning is complete"
otask.save()
else:
otask.description="Skip cloning"
otask.save()
otask.success=True
otask.finished=True
otask.save()
otask = OTask(name='Previsualization', finished=False, success=False, description="preparing the previsualization", orun=orun)
otask.save()
repo_dir = os.path.join(home, folder_name)
dolog("previsual> will call start previsual")
otask.description = "Generating the previsualization"
otask.save()
msg = start_previsual(repo_dir, target_repo)
if msg == "": # no errors
dolog("previsual> completed successfully")
otask.description="The previsualization is generated without errors"
otask.success=True
otask.finished=True
otask.save()
repo.state = 'Ready'
repo.save()
dolog("previsual> test state: %s" % repo.state)
return "", orun
else:
repo.notes = msg
repo.state = 'Ready'
repo.save()
otask.description="Error generating the previsualization: "+msg
otask.success=False
otask.finished=True
otask.save()
return msg, orun
else: # not found
# repo.state = 'Ready'
# repo.save()
error_msg = 'You should add the repo while you are logged in before the revisual renewal'
dolog("previsual> " + error_msg)
# otask.description = "The repo is not found or does not belog to this user"
# otask.save()
return error_msg, None
except Exception as e:
dolog("autoncore.previsual exception: <%s>" % str(e))
dolog(traceback.format_exc())
if otask is not None: