forked from easybuilders/easybuild-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.py
1774 lines (1446 loc) · 72 KB
/
github.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
##
# Copyright 2012-2019 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
Utility module for working with github
:author: Jens Timmerman (Ghent University)
:author: Kenneth Hoste (Ghent University)
:author: Toon Willems (Ghent University)
"""
import base64
import copy
import getpass
import glob
import os
import random
import re
import socket
import sys
import tempfile
import time
from datetime import datetime, timedelta
from distutils.version import LooseVersion
from easybuild.base import fancylogger
from easybuild.framework.easyconfig.easyconfig import EASYCONFIGS_ARCHIVE_DIR
from easybuild.framework.easyconfig.easyconfig import copy_easyconfigs, copy_patch_files, process_easyconfig
from easybuild.framework.easyconfig.parser import EasyConfigParser
from easybuild.tools.build_log import EasyBuildError, print_msg, print_warning
from easybuild.tools.config import build_option
from easybuild.tools.filetools import apply_patch, copy_dir, det_patched_files, download_file, extract_file
from easybuild.tools.filetools import mkdir, read_file, symlink, which, write_file
from easybuild.tools.py2vs3 import HTTPError, URLError, ascii_letters, urlopen
from easybuild.tools.systemtools import UNKNOWN, get_tool_version
from easybuild.tools.utilities import nub, only_if_module_is_available
_log = fancylogger.getLogger('github', fname=False)
try:
import keyring
HAVE_KEYRING = True
except ImportError as err:
_log.warning("Failed to import 'keyring' Python module: %s" % err)
HAVE_KEYRING = False
try:
from easybuild.base.rest import RestClient
HAVE_GITHUB_API = True
except ImportError as err:
_log.warning("Failed to import from 'easybuild.base.rest' Python module: %s" % err)
HAVE_GITHUB_API = False
try:
import git
from git import GitCommandError
except ImportError as err:
_log.warning("Failed to import 'git' Python module: %s", err)
GITHUB_URL = 'https://github.com'
GITHUB_API_URL = 'https://api.github.com'
GITHUB_DIR_TYPE = u'dir'
GITHUB_EB_MAIN = 'easybuilders'
GITHUB_EASYCONFIGS_REPO = 'easybuild-easyconfigs'
GITHUB_FILE_TYPE = u'file'
GITHUB_PR_STATE_OPEN = 'open'
GITHUB_PR_STATES = [GITHUB_PR_STATE_OPEN, 'closed', 'all']
GITHUB_PR_ORDER_CREATED = 'created'
GITHUB_PR_ORDERS = [GITHUB_PR_ORDER_CREATED, 'updated', 'popularity', 'long-running']
GITHUB_PR_DIRECTION_DESC = 'desc'
GITHUB_PR_DIRECTIONS = ['asc', GITHUB_PR_DIRECTION_DESC]
GITHUB_MAX_PER_PAGE = 100
GITHUB_MERGEABLE_STATE_CLEAN = 'clean'
GITHUB_PR = 'pull'
GITHUB_RAW = 'https://raw.githubusercontent.com'
GITHUB_STATE_CLOSED = 'closed'
HTTP_STATUS_OK = 200
HTTP_STATUS_CREATED = 201
HTTP_STATUS_NO_CONTENT = 204
KEYRING_GITHUB_TOKEN = 'github_token'
URL_SEPARATOR = '/'
VALID_CLOSE_PR_REASONS = {
'archived': 'uses an archived toolchain',
'inactive': 'no activity for > 6 months',
'obsolete': 'obsoleted by more recent PRs',
'retest': 'closing and reopening to trigger tests',
}
class Githubfs(object):
"""This class implements some higher level functionality on top of the Github api"""
def __init__(self, githubuser, reponame, branchname="master", username=None, password=None, token=None):
"""Construct a new githubfs object
:param githubuser: the github user's repo we want to use.
:param reponame: The name of the repository we want to use.
:param branchname: Then name of the branch to use (defaults to master)
:param username: (optional) your github username.
:param password: (optional) your github password.
:param token: (optional) a github api token.
"""
if token is None:
token = fetch_github_token(username)
self.log = fancylogger.getLogger(self.__class__.__name__, fname=False)
self.gh = RestClient(GITHUB_API_URL, username=username, password=password, token=token)
self.githubuser = githubuser
self.reponame = reponame
self.branchname = branchname
@staticmethod
def join(*args):
"""This method joins 'paths' inside a github repository"""
args = [x for x in args if x]
return URL_SEPARATOR.join(args)
def get_repo(self):
"""Returns the repo as a Github object (from agithub)"""
return self.gh.repos[self.githubuser][self.reponame]
def get_path(self, path):
"""returns the path as a Github object (from agithub)"""
endpoint = self.get_repo()['contents']
if path:
for subpath in path.split(URL_SEPARATOR):
endpoint = endpoint[subpath]
return endpoint
@staticmethod
def isdir(githubobj):
"""Check if this path points to a directory"""
if isinstance(githubobj, (list, tuple)):
return True
else:
try:
return githubobj['type'] == GITHUB_DIR_TYPE
except Exception:
return False
@staticmethod
def isfile(githubobj):
"""Check if this path points to a file"""
try:
return githubobj['type'] == GITHUB_FILE_TYPE
except Exception:
return False
def listdir(self, path):
"""List the contents of a directory"""
path = self.get_path(path)
listing = path.get(ref=self.branchname)
self.log.debug("listdir response: %s" % str(listing))
if listing[0] == 200:
return listing[1]
else:
self.log.warning("error: %s" % str(listing))
raise EasyBuildError("Invalid response from github (I/O error)")
def walk(self, top=None, topdown=True):
"""
Walk the github repo in an os.walk like fashion.
"""
isdir, listdir = self.isdir, self.listdir
# If this fails we blow up, since permissions on a github repo are recursive anyway.j
githubobjs = listdir(top)
# listdir works with None, but we want to show a decent 'root dir' name
dirs, nondirs = [], []
for githubobj in githubobjs:
if isdir(githubobj):
dirs.append(str(githubobj['name']))
else:
nondirs.append(str(githubobj['name']))
if topdown:
yield top, dirs, nondirs
for name in dirs:
new_path = self.join(top, name)
for x in self.walk(new_path, topdown):
yield x
if not topdown:
yield top, dirs, nondirs
def read(self, path, api=True):
"""Read the contents of a file and return it
Or, if api=False it will download the file and return the location of the downloaded file"""
# we don't need use the api for this, but can also use raw.github.com
# https://raw.github.com/easybuilders/easybuild/master/README.rst
if not api:
outfile = tempfile.mkstemp()[1]
url = '/'.join([GITHUB_RAW, self.githubuser, self.reponame, self.branchname, path])
download_file(os.path.basename(path), url, outfile)
return outfile
else:
obj = self.get_path(path).get(ref=self.branchname)[1]
if not self.isfile(obj):
raise GithubError("Error: not a valid file: %s" % str(obj))
return base64.b64decode(obj['content'])
class GithubError(Exception):
"""Error raised by the Githubfs"""
pass
def github_api_get_request(request_f, github_user=None, token=None, **kwargs):
"""
Helper method, for performing get requests to GitHub API.
:param request_f: function that should be called to compose request, providing a RestClient instance
:param github_user: GitHub user name (to try and obtain matching GitHub token if none is provided)
:param token: GitHub token to use
:return: tuple with return status and data
"""
if github_user is None:
github_user = build_option('github_user')
if token is None:
token = fetch_github_token(github_user)
url = request_f(RestClient(GITHUB_API_URL, username=github_user, token=token))
try:
status, data = url.get(**kwargs)
except socket.gaierror as err:
_log.warning("Error occurred while performing get request: %s", err)
status, data = 0, None
_log.debug("get request result for %s: status: %d, data: %s", url, status, data)
return (status, data)
def github_api_put_request(request_f, github_user=None, token=None, **kwargs):
"""
Helper method, for performing put requests to GitHub API.
:param request_f: function that should be called to compose request, providing a RestClient instance
:param github_user: GitHub user name (to try and obtain matching GitHub token if none is provided)
:param token: GitHub token to use
:return: tuple with return status and data
"""
if github_user is None:
github_user = build_option('github_user')
if token is None:
token = fetch_github_token(github_user)
url = request_f(RestClient(GITHUB_API_URL, username=github_user, token=token))
try:
status, data = url.put(**kwargs)
except socket.gaierror as err:
_log.warning("Error occurred while performing put request: %s", err)
status, data = 0, {'message': err}
if status == 200:
_log.info("Put request successful: %s", data['message'])
elif status in [405, 409]:
raise EasyBuildError("FAILED: %s", data['message'])
else:
raise EasyBuildError("FAILED: %s", data.get('message', "(unknown reason)"))
_log.debug("get request result for %s: status: %d, data: %s", url, status, data)
return (status, data)
def fetch_latest_commit_sha(repo, account, branch='master', github_user=None, token=None):
"""
Fetch latest SHA1 for a specified repository and branch.
:param repo: GitHub repository
:param account: GitHub account
:param branch: branch to fetch latest SHA1 for
:param github_user: name of GitHub user to use
:param token: GitHub token to use
:return: latest SHA1
"""
status, data = github_api_get_request(lambda x: x.repos[account][repo].branches,
github_user=github_user, token=token, per_page=GITHUB_MAX_PER_PAGE)
if status != HTTP_STATUS_OK:
raise EasyBuildError("Failed to get latest commit sha for branch %s from %s/%s (status: %d %s)",
branch, account, repo, status, data)
res = None
for entry in data:
if entry[u'name'] == branch:
res = entry['commit']['sha']
break
if res is None:
error_msg = "No branch with name %s found in repo %s/%s" % (branch, account, repo)
if len(data) >= GITHUB_MAX_PER_PAGE:
error_msg += "; only %d branches were checked (too many branches in %s/%s?)" % (len(data), account, repo)
raise EasyBuildError(error_msg + ': ' + ', '.join([x[u'name'] for x in data]))
return res
def download_repo(repo=GITHUB_EASYCONFIGS_REPO, branch='master', account=GITHUB_EB_MAIN, path=None, github_user=None):
"""
Download entire GitHub repo as a tar.gz archive, and extract it into specified path.
:param repo: repo to download
:param branch: branch to download
:param account: GitHub account to download repo from
:param path: path to extract to
:param github_user: name of GitHub user to use
"""
# make sure path exists, create it if necessary
if path is None:
path = tempfile.mkdtemp()
# add account subdir
path = os.path.join(path, account)
mkdir(path, parents=True)
extracted_dir_name = '%s-%s' % (repo, branch)
base_name = '%s.tar.gz' % branch
latest_commit_sha = fetch_latest_commit_sha(repo, account, branch, github_user=github_user)
expected_path = os.path.join(path, extracted_dir_name)
latest_sha_path = os.path.join(expected_path, 'latest-sha')
# check if directory already exists, don't download if 'latest-sha' file indicates that it's up to date
if os.path.exists(latest_sha_path):
sha = read_file(latest_sha_path).split('\n')[0].rstrip()
if latest_commit_sha == sha:
_log.debug("Not redownloading %s/%s as it already exists: %s" % (account, repo, expected_path))
return expected_path
url = URL_SEPARATOR.join([GITHUB_URL, account, repo, 'archive', base_name])
target_path = os.path.join(path, base_name)
_log.debug("downloading repo %s/%s as archive from %s to %s" % (account, repo, url, target_path))
download_file(base_name, url, target_path, forced=True)
_log.debug("%s downloaded to %s, extracting now" % (base_name, path))
extracted_path = os.path.join(extract_file(target_path, path, forced=True), extracted_dir_name)
# check if extracted_path exists
if not os.path.isdir(extracted_path):
raise EasyBuildError("%s should exist and contain the repo %s at branch %s", extracted_path, repo, branch)
write_file(latest_sha_path, latest_commit_sha, forced=True)
_log.debug("Repo %s at branch %s extracted into %s" % (repo, branch, extracted_path))
return extracted_path
def fetch_easyconfigs_from_pr(pr, path=None, github_user=None):
"""Fetch patched easyconfig files for a particular PR."""
if github_user is None:
github_user = build_option('github_user')
if path is None:
path = build_option('pr_path')
if path is None:
path = tempfile.mkdtemp()
else:
# make sure path exists, create it if necessary
mkdir(path, parents=True)
github_account = build_option('pr_target_account')
github_repo = GITHUB_EASYCONFIGS_REPO
_log.debug("Fetching easyconfigs from %s/%s PR #%s into %s", github_account, github_repo, pr, path)
pr_data, _ = fetch_pr_data(pr, github_account, github_repo, github_user)
pr_merged = pr_data['merged']
pr_closed = pr_data['state'] == GITHUB_STATE_CLOSED and not pr_merged
pr_target_branch = pr_data['base']['ref']
_log.info("Target branch for PR #%s: %s", pr, pr_target_branch)
# download target branch of PR so we can try and apply the PR patch on top of it
repo_target_branch = download_repo(repo=github_repo, account=github_account, branch=pr_target_branch,
github_user=github_user)
# determine list of changed files via diff
diff_fn = os.path.basename(pr_data['diff_url'])
diff_filepath = os.path.join(path, diff_fn)
download_file(diff_fn, pr_data['diff_url'], diff_filepath, forced=True)
diff_txt = read_file(diff_filepath)
_log.debug("Diff for PR #%s:\n%s", pr, diff_txt)
patched_files = det_patched_files(txt=diff_txt, omit_ab_prefix=True, github=True, filter_deleted=True)
_log.debug("List of patched files for PR #%s: %s", pr, patched_files)
final_path = None
# try to apply PR patch on top of target branch, unless the PR is closed or already merged
if pr_merged:
_log.info("PR is already merged, so using current version of PR target branch")
final_path = repo_target_branch
elif not pr_closed:
try:
_log.debug("Trying to apply PR patch %s to %s...", diff_filepath, repo_target_branch)
apply_patch(diff_filepath, repo_target_branch, use_git_am=True)
_log.info("Using %s which included PR patch to test PR #%s", repo_target_branch, pr)
final_path = repo_target_branch
except EasyBuildError as err:
_log.warning("Ignoring problem that occured when applying PR patch: %s", err)
if final_path is None:
if pr_closed:
print_warning("Using easyconfigs from closed PR #%s" % pr)
# obtain most recent version of patched files
for patched_file in patched_files:
# path to patch file, incl. subdir it is in
fn = os.path.sep.join(patched_file.split(os.path.sep)[-3:])
sha = pr_data['head']['sha']
full_url = URL_SEPARATOR.join([GITHUB_RAW, github_account, github_repo, sha, patched_file])
_log.info("Downloading %s from %s", fn, full_url)
download_file(fn, full_url, path=os.path.join(path, fn), forced=True)
final_path = path
# symlink directories into expected place if they're not there yet
if final_path != path:
dirpath = os.path.join(final_path, 'easybuild', 'easyconfigs')
for eb_dir in os.listdir(dirpath):
symlink(os.path.join(dirpath, eb_dir), os.path.join(path, os.path.basename(eb_dir)))
# sanity check: make sure all patched files are downloaded
ec_files = []
for patched_file in [f for f in patched_files if not f.startswith('test/')]:
fn = os.path.sep.join(patched_file.split(os.path.sep)[-3:])
full_path = os.path.join(path, fn)
if os.path.exists(full_path):
ec_files.append(full_path)
else:
raise EasyBuildError("Couldn't find path to patched file %s", full_path)
return ec_files
def create_gist(txt, fn, descr=None, github_user=None, github_token=None):
"""Create a gist with the provided text."""
if descr is None:
descr = "(none)"
if github_token is None:
github_token = fetch_github_token(github_user)
body = {
"description": descr,
"public": True,
"files": {
fn: {
"content": txt,
}
}
}
g = RestClient(GITHUB_API_URL, username=github_user, token=github_token)
status, data = g.gists.post(body=body)
if status != HTTP_STATUS_CREATED:
raise EasyBuildError("Failed to create gist; status %s, data: %s", status, data)
return data['html_url']
def delete_gist(gist_id, github_user=None, github_token=None):
"""Delete gist with specified ID."""
if github_token is None:
github_token = fetch_github_token(github_user)
gh = RestClient(GITHUB_API_URL, username=github_user, token=github_token)
status, data = gh.gists[gist_id].delete()
if status != HTTP_STATUS_NO_CONTENT:
raise EasyBuildError("Failed to delete gist with ID %s: status %s, data: %s", status, data)
def post_comment_in_issue(issue, txt, account=GITHUB_EB_MAIN, repo=GITHUB_EASYCONFIGS_REPO, github_user=None):
"""Post a comment in the specified PR."""
if not isinstance(issue, int):
try:
issue = int(issue)
except ValueError as err:
raise EasyBuildError("Failed to parse specified pull request number '%s' as an int: %s; ", issue, err)
dry_run = build_option('dry_run') or build_option('extended_dry_run')
msg = "Adding comment to %s issue #%s: '%s'" % (repo, issue, txt)
if dry_run:
msg = "[DRY RUN] " + msg
print_msg(msg, log=_log, prefix=False)
if not dry_run:
github_token = fetch_github_token(github_user)
g = RestClient(GITHUB_API_URL, username=github_user, token=github_token)
pr_url = g.repos[account][repo].issues[issue]
status, data = pr_url.comments.post(body={'body': txt})
if not status == HTTP_STATUS_CREATED:
raise EasyBuildError("Failed to create comment in PR %s#%d; status %s, data: %s", repo, issue, status, data)
def init_repo(path, repo_name, silent=False):
"""
Initialize a new Git repository at the specified location.
:param path: location where Git repository should be initialized
:param repo_name: name of Git repository
:param silent: keep quiet (don't print any messages)
"""
repo_path = os.path.join(path, repo_name)
# copy or init git working directory
git_working_dirs_path = build_option('git_working_dirs_path')
if git_working_dirs_path:
workdir = os.path.join(git_working_dirs_path, repo_name)
if os.path.exists(workdir):
print_msg("copying %s..." % workdir, silent=silent)
copy_dir(workdir, repo_path)
if not os.path.exists(repo_path):
mkdir(repo_path, parents=True)
try:
repo = git.Repo.init(repo_path)
except GitCommandError as err:
raise EasyBuildError("Failed to init git repo at %s: %s", repo_path, err)
_log.debug("temporary git working directory ready at %s", repo_path)
return repo
def setup_repo_from(git_repo, github_url, target_account, branch_name, silent=False):
"""
Set up repository by checking out specified branch from repository at specified URL.
:param git_repo: git.Repo instance
:param github_url: URL to GitHub repository
:param target_account: name of GitHub account that owns GitHub repository at specified URL
:param branch_name: name of branch to check out
:param silent: keep quiet (don't print any messages)
"""
_log.debug("Cloning from %s", github_url)
# salt to use for names of remotes/branches that are created
salt = ''.join(random.choice(ascii_letters) for _ in range(5))
remote_name = 'pr_target_account_%s_%s' % (target_account, salt)
origin = git_repo.create_remote(remote_name, github_url)
if not origin.exists():
raise EasyBuildError("%s does not exist?", github_url)
# git fetch
# can't use --depth to only fetch a shallow copy, since pushing to another repo from a shallow copy doesn't work
print_msg("fetching branch '%s' from %s..." % (branch_name, github_url), silent=silent)
try:
res = origin.fetch()
except GitCommandError as err:
raise EasyBuildError("Failed to fetch branch '%s' from %s: %s", branch_name, github_url, err)
if res:
if res[0].flags & res[0].ERROR:
raise EasyBuildError("Fetching branch '%s' from remote %s failed: %s", branch_name, origin, res[0].note)
else:
_log.debug("Fetched branch '%s' from remote %s (note: %s)", branch_name, origin, res[0].note)
else:
raise EasyBuildError("Fetching branch '%s' from remote %s failed: empty result", branch_name, origin)
# git checkout -b <branch>; git pull
if hasattr(origin.refs, branch_name):
origin_branch = getattr(origin.refs, branch_name)
else:
raise EasyBuildError("Branch '%s' not found at %s", branch_name, github_url)
_log.debug("Checking out branch '%s' from remote %s", branch_name, github_url)
try:
origin_branch.checkout(b=branch_name)
except GitCommandError as err:
alt_branch = '%s_%s' % (branch_name, salt)
_log.debug("Trying to work around checkout error ('%s') by using different branch name '%s'", err, alt_branch)
try:
origin_branch.checkout(b=alt_branch, force=True)
except GitCommandError as err:
raise EasyBuildError("Failed to check out branch '%s' from repo at %s: %s", alt_branch, github_url, err)
return remote_name
def setup_repo(git_repo, target_account, target_repo, branch_name, silent=False, git_only=False):
"""
Set up repository by checking out specified branch for specfied GitHub account/repository.
:param git_repo: git.Repo instance
:param target_account: name of GitHub account that owns GitHub repository
:param target_repo: name of GitHib repository
:param branch_name: name of branch to check out
:param silent: keep quiet (don't print any messages)
:param git_only: only use [email protected] repo URL, skip trying https://github.com first
"""
tmpl_github_urls = [
'[email protected]:%s/%s.git',
]
if not git_only:
tmpl_github_urls.insert(0, 'https://github.com/%s/%s.git')
res = None
errors = []
for tmpl_github_url in tmpl_github_urls:
github_url = tmpl_github_url % (target_account, target_repo)
try:
res = setup_repo_from(git_repo, github_url, target_account, branch_name, silent=silent)
break
except EasyBuildError as err:
errors.append("Checking out branch '%s' from %s failed: %s" % (branch_name, github_url, err))
if res:
return res
else:
raise EasyBuildError('\n'.join(errors))
@only_if_module_is_available('git', pkgname='GitPython')
def _easyconfigs_pr_common(paths, ecs, start_branch=None, pr_branch=None, start_account=None, commit_msg=None):
"""
Common code for new_pr and update_pr functions:
* check whether all supplied paths point to existing files
* create temporary clone of target git repository
* fetch/checkout specified starting branch
* copy files to right location
* stage/commit all files in PR branch
* push PR branch to GitHub (to account specified by --github-user)
:param paths: paths to categorized lists of files (easyconfigs, files to delete, patches)
:param ecs: list of parsed easyconfigs, incl. for dependencies (if robot is enabled)
:param start_branch: name of branch to use as base for PR
:param pr_branch: name of branch to push to GitHub
:param start_account: name of GitHub account to use as base for PR
:param commit_msg: commit message to use
"""
# we need files to create the PR with
non_existing_paths = []
ec_paths = []
if paths['easyconfigs']:
for path in paths['easyconfigs']:
if not os.path.exists(path):
non_existing_paths.append(path)
else:
ec_paths.append(path)
if non_existing_paths:
raise EasyBuildError("One or more non-existing paths specified: %s", ', '.join(non_existing_paths))
if not any(paths.values()):
raise EasyBuildError("No paths specified")
pr_target_repo = build_option('pr_target_repo')
# initialize repository
git_working_dir = tempfile.mkdtemp(prefix='git-working-dir')
git_repo = init_repo(git_working_dir, pr_target_repo)
repo_path = os.path.join(git_working_dir, pr_target_repo)
if pr_target_repo != GITHUB_EASYCONFIGS_REPO:
raise EasyBuildError("Don't know how to create/update a pull request to the %s repository", pr_target_repo)
if start_branch is None:
# if start branch is not specified, we're opening a new PR
# account to use is determined by active EasyBuild configuration (--github-org or --github-user)
target_account = build_option('github_org') or build_option('github_user')
# if branch to start from is specified, we're updating an existing PR
start_branch = build_option('pr_target_branch')
else:
# account to target is the one that owns the branch used to open PR
# (which may be different from account used to push update!)
target_account = start_account
# set up repository
setup_repo(git_repo, start_account, pr_target_repo, start_branch)
_log.debug("git status: %s", git_repo.git.status())
# copy easyconfig files to right place
target_dir = os.path.join(git_working_dir, pr_target_repo)
print_msg("copying easyconfigs to %s..." % target_dir)
file_info = copy_easyconfigs(ec_paths, target_dir)
# figure out commit message to use
if commit_msg:
cnt = len(file_info['paths_in_repo'])
_log.debug("Using specified commit message for all %d new/modified easyconfigs at once: %s", cnt, commit_msg)
elif all(file_info['new']) and not paths['files_to_delete']:
# automagically derive meaningful commit message if all easyconfig files are new
commit_msg = "adding easyconfigs: %s" % ', '.join(os.path.basename(p) for p in file_info['paths_in_repo'])
if paths['patch_files']:
commit_msg += " and patches: %s" % ', '.join(os.path.basename(p) for p in paths['patch_files'])
else:
raise EasyBuildError("A meaningful commit message must be specified via --pr-commit-msg when "
"modifying/deleting easyconfigs")
# figure out to which software name patches relate, and copy them to the right place
if paths['patch_files']:
patch_specs = det_patch_specs(paths['patch_files'], file_info, [target_dir])
print_msg("copying patch files to %s..." % target_dir)
patch_info = copy_patch_files(patch_specs, target_dir)
# determine path to files to delete (if any)
deleted_paths = []
for fn in paths['files_to_delete']:
fullpath = os.path.join(repo_path, fn)
if os.path.exists(fullpath):
deleted_paths.append(fullpath)
else:
# if no existing relative path is specified, assume just the easyconfig file name is provided
hits = glob.glob(os.path.join(repo_path, 'easybuild', 'easyconfigs', '*', '*', fn))
if len(hits) == 1:
deleted_paths.append(hits[0])
else:
raise EasyBuildError("Path doesn't exist or file to delete isn't found in target branch: %s", fn)
dep_info = {
'ecs': [],
'paths_in_repo': [],
'new': [],
}
# include missing easyconfigs for dependencies, if robot is enabled
if ecs is not None:
abs_paths = [os.path.realpath(os.path.abspath(path)) for path in ec_paths]
dep_paths = [ec['spec'] for ec in ecs if os.path.realpath(ec['spec']) not in abs_paths]
_log.info("Paths to easyconfigs for missing dependencies: %s", dep_paths)
all_dep_info = copy_easyconfigs(dep_paths, target_dir)
# only consider new easyconfig files for dependencies (not updated ones)
for idx in range(len(all_dep_info['ecs'])):
if all_dep_info['new'][idx]:
for key in dep_info:
dep_info[key].append(all_dep_info[key][idx])
# checkout target branch
if pr_branch is None:
if ec_paths:
label = file_info['ecs'][0].name + re.sub('[.-]', '', file_info['ecs'][0].version)
else:
label = ''.join(random.choice(ascii_letters) for _ in range(10))
pr_branch = '%s_new_pr_%s' % (time.strftime("%Y%m%d%H%M%S"), label)
# create branch to commit to and push;
# use force to avoid errors if branch already exists (OK since this is a local temporary copy of the repo)
git_repo.create_head(pr_branch, force=True).checkout()
_log.info("New branch '%s' created to commit files to", pr_branch)
# stage
_log.debug("Staging all %d new/modified easyconfigs", len(file_info['paths_in_repo']))
git_repo.index.add(file_info['paths_in_repo'])
git_repo.index.add(dep_info['paths_in_repo'])
if paths['patch_files']:
_log.debug("Staging all %d new/modified patch files", len(patch_info['paths_in_repo']))
git_repo.index.add(patch_info['paths_in_repo'])
# stage deleted files
if deleted_paths:
git_repo.index.remove(deleted_paths)
# overview of modifications
if build_option('extended_dry_run'):
print_msg("\nFull patch:\n", log=_log, prefix=False)
print_msg(git_repo.git.diff(cached=True) + '\n', log=_log, prefix=False)
diff_stat = git_repo.git.diff(cached=True, stat=True)
if not diff_stat:
raise EasyBuildError("No changed files found when comparing to current develop branch. "
"Refused to make empty pull request.")
# commit
git_repo.index.commit(commit_msg)
# push to GitHub
github_url = '[email protected]:%s/%s.git' % (target_account, pr_target_repo)
salt = ''.join(random.choice(ascii_letters) for _ in range(5))
remote_name = 'github_%s_%s' % (target_account, salt)
dry_run = build_option('dry_run') or build_option('extended_dry_run')
push_branch_msg = "pushing branch '%s' to remote '%s' (%s)" % (pr_branch, remote_name, github_url)
if dry_run:
print_msg(push_branch_msg + ' [DRY RUN]', log=_log)
else:
print_msg(push_branch_msg, log=_log)
try:
my_remote = git_repo.create_remote(remote_name, github_url)
res = my_remote.push(pr_branch)
except GitCommandError as err:
raise EasyBuildError("Failed to push branch '%s' to GitHub (%s): %s", pr_branch, github_url, err)
if res:
if res[0].ERROR & res[0].flags:
raise EasyBuildError("Pushing branch '%s' to remote %s (%s) failed: %s",
pr_branch, my_remote, github_url, res[0].summary)
else:
_log.debug("Pushed branch %s to remote %s (%s): %s", pr_branch, my_remote, github_url, res[0].summary)
else:
raise EasyBuildError("Pushing branch '%s' to remote %s (%s) failed: empty result",
pr_branch, my_remote, github_url)
return file_info, deleted_paths, git_repo, pr_branch, diff_stat
def is_patch_for(patch_name, ec):
"""Check whether specified patch matches any patch in the provided EasyConfig instance."""
res = False
patches = copy.copy(ec['patches'])
for ext in ec['exts_list']:
if isinstance(ext, (list, tuple)) and len(ext) == 3 and isinstance(ext[2], dict):
ext_options = ext[2]
patches.extend(ext_options.get('patches', []))
for patch in patches:
if isinstance(patch, (tuple, list)):
patch = patch[0]
if patch == patch_name:
res = True
break
return res
def det_patch_specs(patch_paths, file_info, ec_dirs):
""" Determine software names for patch files """
print_msg("determining software names for patch files...")
patch_specs = []
for patch_path in patch_paths:
soft_name = None
patch_file = os.path.basename(patch_path)
# consider patch lists of easyconfigs being provided
for ec in file_info['ecs']:
if is_patch_for(patch_file, ec):
soft_name = ec['name']
break
if soft_name:
patch_specs.append((patch_path, soft_name))
else:
# fall back on scanning all eb files for patches
print("Matching easyconfig for %s not found on the first try:" % patch_path)
print("scanning all easyconfigs to determine where patch file belongs (this may take a while)...")
soft_name = find_software_name_for_patch(patch_file, ec_dirs)
if soft_name:
patch_specs.append((patch_path, soft_name))
else:
# still nothing found
raise EasyBuildError("Failed to determine software name to which patch file %s relates", patch_path)
return patch_specs
def find_software_name_for_patch(patch_name, ec_dirs):
"""
Scan all easyconfigs in the robot path(s) to determine which software a patch file belongs to
:param patch_name: name of the patch file
:param ecs_dirs: list of directories to consider when looking for easyconfigs
:return: name of the software that this patch file belongs to (if found)
"""
soft_name = None
all_ecs = []
for ec_dir in ec_dirs:
for (dirpath, _, filenames) in os.walk(ec_dir):
for fn in filenames:
if fn != 'TEMPLATE.eb' and not fn.endswith('.py'):
path = os.path.join(dirpath, fn)
rawtxt = read_file(path)
if 'patches' in rawtxt:
all_ecs.append(path)
nr_of_ecs = len(all_ecs)
for idx, path in enumerate(all_ecs):
if soft_name:
break
rawtxt = read_file(path)
try:
ecs = process_easyconfig(path, validate=False)
for ec in ecs:
if is_patch_for(patch_name, ec['ec']):
soft_name = ec['ec']['name']
break
except EasyBuildError as err:
_log.debug("Ignoring easyconfig %s that fails to parse: %s", path, err)
sys.stdout.write('\r%s of %s easyconfigs checked' % (idx+1, nr_of_ecs))
sys.stdout.flush()
sys.stdout.write('\n')
return soft_name
def check_pr_eligible_to_merge(pr_data):
"""
Check whether PR is eligible for merging.
:param pr_data: PR data obtained through GitHub API
:return: boolean value indicates whether PR is eligible
"""
res = True
def not_eligible(msg):
"""Helper function to warn about PR not being eligible for merging"""
print_msg("%s => not eligible for merging!" % msg, stderr=True, prefix=False)
return False
target = '%s/%s' % (pr_data['base']['repo']['owner']['login'], pr_data['base']['repo']['name'])
print_msg("Checking eligibility of %s PR #%s for merging..." % (target, pr_data['number']), prefix=False)
# check target branch, must be 'develop'
msg_tmpl = "* targets develop branch: %s"
if pr_data['base']['ref'] == 'develop':
print_msg(msg_tmpl % 'OK', prefix=False)
else:
res = not_eligible(msg_tmpl % "FAILED; found '%s'" % pr_data['base']['ref'])
# check test suite result, Travis must give green light
msg_tmpl = "* test suite passes: %s"
if pr_data['status_last_commit'] == 'success':
print_msg(msg_tmpl % 'OK', prefix=False)
elif pr_data['status_last_commit'] == 'pending':
res = not_eligible(msg_tmpl % "pending...")
elif pr_data['status_last_commit'] in ['error', 'failure']:
res = not_eligible(msg_tmpl % "FAILED")
else:
res = not_eligible(msg_tmpl % "(result unknown)")
if pr_data['base']['repo']['name'] == GITHUB_EASYCONFIGS_REPO:
# check for successful test report (checked in reverse order)
msg_tmpl = "* last test report is successful: %s"
test_report_regex = re.compile(r"^Test report by @\S+")
test_report_found = False
for comment in pr_data['issue_comments'][::-1]:
comment = comment['body']
if test_report_regex.search(comment):
if 'SUCCESS' in comment:
print_msg(msg_tmpl % 'OK', prefix=False)
test_report_found = True
break
elif 'FAILED' in comment:
res = not_eligible(msg_tmpl % 'FAILED')
test_report_found = True
break
else:
print_warning("Failed to determine outcome of test report for comment:\n%s" % comment)
if not test_report_found:
res = not_eligible(msg_tmpl % "(no test reports found)")
# check for approved review
approved_review_by = []
for review in pr_data['reviews']:
if review['state'] == 'APPROVED':
approved_review_by.append(review['user']['login'])
msg_tmpl = "* approved review: %s"
if approved_review_by:
print_msg(msg_tmpl % 'OK (by %s)' % ', '.join(approved_review_by), prefix=False)
else:
res = not_eligible(msg_tmpl % 'MISSING')
# check whether a milestone is set
msg_tmpl = "* milestone is set: %s"
if pr_data['milestone']: