-
Notifications
You must be signed in to change notification settings - Fork 27
/
shared_setup.py
1794 lines (1483 loc) · 72.5 KB
/
shared_setup.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 2011-2024 Ghent University
#
# This file is part of vsc-install,
# 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),
# the 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/hpcugent/vsc-install
#
# vsc-install is free software: you can redistribute it and/or modify
# it under the terms of the GNU Library General Public License as
# published by the Free Software Foundation, either version 2 of
# the License, or (at your option) any later version.
#
# vsc-install 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 Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with vsc-install. If not, see <http://www.gnu.org/licenses/>.
#
"""
Shared module for vsc software setup
@author: Stijn De Weirdt (Ghent University)
@author: Andy Georges (Ghent University)
"""
import sys
import glob
import hashlib
import inspect
import json
import os
import shutil
import traceback
import re
import builtins
MAX_SETUPTOOLS_VERSION_PY39 = '54.0'
MAX_SETUPTOOLS_VERSION_PY36 = '42.0'
if sys.version_info.major == 3 and sys.version_info.minor > 6:
# Must run before importing setuptools
dmod = sys.modules.get('distutils', None)
if dmod is not None and 'setuptools/_distutils' not in dmod.__file__:
print(f'WARN: distutils already loaded with unexpected path.')
print(" If you get this, set 'SETUPTOOLS_USE_DISTUTILS=local' or check the setuptools version >= 53.0")
# only for sys.version_info.minor == 9 (rhel9 setup)
MAX_SETUPTOOLS_VERSION = MAX_SETUPTOOLS_VERSION_PY39
sud = os.environ.get('SETUPTOOLS_USE_DISTUTILS', None)
if sud is None:
os.environ['SETUPTOOLS_USE_DISTUTILS'] = 'local'
elif sud != 'local':
print(f"WARN: Found SETUPTOOLS_USE_DISTUTILS in environ with value '{sud}', only tested with 'local'")
else:
MAX_SETUPTOOLS_VERSION = MAX_SETUPTOOLS_VERSION_PY36
import setuptools
import setuptools.dist
import setuptools.command.test
from distutils import log # also for setuptools
from pathlib import Path
from setuptools import Command
from setuptools.command.test import test as TestCommand
from setuptools.command.test import ScanningLoader
from setuptools.command.bdist_rpm import bdist_rpm as orig_bdist_rpm
from setuptools.command.build_py import build_py
from setuptools.command.egg_info import egg_info
from setuptools.command.install_scripts import install_scripts
# egg_info uses sdist directly through manifest_maker
from setuptools.command.sdist import sdist
from unittest import TestSuite
have_xmlrunner = None
try:
import xmlrunner
have_xmlrunner = True
except ImportError:
have_xmlrunner = False
# Test that these are matched by a .gitignore pattern
GITIGNORE_PATTERNS = ['.pyc', '.pyo', '~']
# .gitnore needs to contain these exactly
GITIGNORE_EXACT_PATTERNS = ['.eggs*']
# private class variables to communicate
# between VscScanningLoader and VscTestCommand
# stored in builtins because the (Vsc)TestCommand.run_tests
# reloads and cleans up the modules
if not hasattr(builtins, '__target'):
setattr(builtins, '__target', {})
if not hasattr(builtins, '__test_filter'):
setattr(builtins, '__test_filter', {
'module': None,
'function': None,
'allowmods': [],
})
# Keep this for legacy reasons, setuptools didn't used to be a requirement
has_setuptools = True
# redo log info / warn / error so it shows loglevel in log message
# distutils log does not support formatters
# don't do it twice
if log.Log.__name__ != 'NewLog':
# make a map between level and names
log_levels = {getattr(log, x): x for x in dir(log) if x == x.upper()}
OrigLog = log.Log
class NewLog(OrigLog):
"""Logging class to prefix the message with a human readable log level"""
def __init__(self, *args, **kwargs):
self._orig_log = OrigLog._log
# make copy
self._log_levels = {}
self._log_levels.update(log_levels)
OrigLog.__init__(self, *args, **kwargs)
# pylint: disable=arguments-differ
def _log(self, level, msg, args):
"""Prefix the message with human readable level"""
newmsg = f"{self._log_levels.get(level, 'UNKNOWN')}: {msg}"
try:
return self._orig_log(self, level, newmsg, args)
except Exception:
print(newmsg % args)
return None
log.Log = NewLog
log._global_log = NewLog()
for lvl in log_levels.values():
name = lvl.lower()
setattr(log, name, getattr(log._global_log, name))
log.set_verbosity(log.DEBUG)
# available authors
ag = ('Andy Georges', 'andy.georges@ugent.be')
asg = ('Álvaro Simón García', 'alvaro.simongarcia@UGent.be')
eh = ('Ewan Higgs', 'Ewan.Higgs@UGent.be')
jt = ('Jens Timmerman', 'jens.timmerman@ugent.be')
kh = ('Kenneth Hoste', 'kenneth.hoste@ugent.be')
kw = ('Kenneth Waegeman', 'Kenneth.Waegeman@UGent.be')
lm = ('Luis Fernando Munoz Meji?as', 'luis.munoz@ugent.be')
sdw = ('Stijn De Weirdt', 'stijn.deweirdt@ugent.be')
wdp = ('Wouter Depypere', 'wouter.depypere@ugent.be')
wp = ('Ward Poelmans', 'ward.poelmans@vub.be')
sm = ('Samuel Moors', 'samuel.moors@vub.be')
bh = ('Balazs Hajgato', 'Balazs.Hajgato@UGent.be')
ad = ('Alex Domingo', 'alex.domingo.toro@vub.be')
# available remotes
GIT_REMOTES = [
('github.ugent.be', 'hpcugent'),
('github.com', 'hpcugent'),
('github.com', 'vub-hpc'),
('dev.azure.com', 'VUB-ICT'),
]
# Regexp used to remove suffixes from scripts when installing(/packaging)
REGEXP_REMOVE_SUFFIX = re.compile(r'(\.(?:py|sh|pl))$')
# We do need all setup files to be included in the source dir
# if we ever want to install the package elsewhere.
EXTRA_SDIST_FILES = ['setup.py']
# Put unittests under this directory
DEFAULT_TEST_SUITE = 'test'
DEFAULT_LIB_DIR = 'lib'
URL_GH_HPCUGENT = 'https://github.com/hpcugent/%(name)s'
URL_GHUGENT_HPCUGENT = 'https://github.ugent.be/hpcugent/%(name)s'
RELOAD_VSC_MODS = False
VERSION = '0.21.2'
log.info('This is (based on) vsc.install.shared_setup %s', VERSION)
log.info('(using setuptools version %s located at %s)', setuptools.__version__, setuptools.__file__)
# list of non-vsc packages that do not need python- prefix for correct rpm dependencies
# vsc packages should be handled with clusterbuildrpm
# dependencies starting with python- are also not re-prefixed
NO_PREFIX_PYTHON_BDIST_RPM = ['pbs_python']
# Hardcode map of python dependency prefix to their rpm python- flavour prefix
PYTHON_BDIST_RPM_PREFIX_MAP = {
'pycrypto': 'python%s-crypto',
'psycopg2': 'python%s-psycopg2',
'python-ldap': 'python%s-ldap',
}
SHEBANG_BIN_BASH = "#!/bin/bash"
SHEBANG_ENV_PYTHON = '#!/usr/bin/env python'
SHEBANG_NOENV_PYTHON = '#!/usr/bin/python-noenv'
SHEBANG_PYTHON_E = '#!/usr/bin/python -E'
SHEBANG_STRIPPED_ENV_PYTHON = '#!/usr/bin/python-stripped-env'
# to be inserted in sdist version of shared_setup
NEW_SHARED_SETUP_HEADER_TEMPLATE = """
# Inserted %s
# Based on shared_setup version %s
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '%s'))
"""
NEW_SHARED_SETUP = 'shared_setup_dist_only'
EXTERNAL_DIR = 'external_dist_only'
# location of README file
README = 'README.md'
# location of LICENSE file
LICENSE = 'LICENSE'
# key = short name, value tuple
# md5sum of LICENSE file
# classifier (see https://pypi.python.org/pypi?%3Aaction=list_classifiers)
# LGPLv2+ and LGPLv2 have same text, we assume always to use the + one
# GPLv2 and GPLv2+ have same text, we assume always to use the regular one
KNOWN_LICENSES = {
# 'LGPLv2': ('? same text as LGPLv2+', 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)'),
'LGPLv2+': (
'5f30f0716dfdd0d91eb439ebec522ec2',
'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)',
),
'GPLv2': ('b234ee4d69f5fce4486a80fdaf4a4263', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)'),
# 'GPLv2+': ('? same text as GPLv2', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)'),
'ARR': ('4c917d76bb092659fa923f457c72d033', 'License :: Other/Proprietary License'),
}
# a whitelist of licenses that allow pushing to pypi during vsc_release
PYPI_LICENSES = ['LGPLv2+', 'GPLv2']
# environment variable name to set when building rpms from vsc-install managed repos
# indicates the python version it is being build for
VSC_RPM_PYTHON = 'VSC_RPM_PYTHON'
def _fvs(msg=None):
"""
Find the most relevant vsc_setup (sub)class
vsc_setup class attributes cannot use self.__class__ in their methods
This is the almost next best thing.
It will allow to do some subclassing, but probably not of any internal test-related method.
This will go horribly wrong when too many subclasses are created, but why would you do that...
msg is a message prefix
"""
if msg is None:
msg = ''
else:
msg += ': '
# Passing parent as argument does not make a difference for the TEST_LOADER setting
parent = vsc_setup
pname = parent.__name__
subclasses = parent.__subclasses__()
if len(subclasses) > 1:
log.warn("%sMore than one %s subclass found (%s), returning the first one",
msg,
pname,
[x.__name__ for x in subclasses])
klass = parent
if subclasses:
klass = subclasses[0]
log.debug("%sFound %s subclass %s", msg, pname, klass.__name__)
else:
log.debug("%sFound no subclasses, returning %s", msg, pname)
return klass
def _read(source, read_lines=False):
"""read a file, either in full or as a list (read_lines=True)"""
text = Path(source).read_text(encoding='utf8')
if read_lines:
return text.splitlines()
return text
# for sufficiently recent version of setuptools, we can hijack the 'get_egg_cache_dir' method
# to control the .eggs directory being used
if hasattr(setuptools.dist.Distribution, 'get_egg_cache_dir'):
setuptools.dist.Distribution._orig_get_egg_cache_dir = setuptools.dist.Distribution.get_egg_cache_dir
# monkey patch setuptools to use different .eggs directory depending on Python version being used
def get_egg_cache_dir_pyver(self):
egg_cache_dir = self._orig_get_egg_cache_dir()
# the original get_egg_cache_dir creates the .eggs directory if it doesn't exist yet,
# but we want to have it versioned, so we rename it
egg_cache_dir_pyver = f'{egg_cache_dir}.py{sys.version_info[0]}{sys.version_info[1]}'
try:
if not os.path.exists(egg_cache_dir_pyver):
os.rename(egg_cache_dir, egg_cache_dir_pyver)
except OSError as err:
raise OSError(f"Failed to rename {egg_cache_dir} to {egg_cache_dir_pyver}: {err}") from err
return egg_cache_dir_pyver
setuptools.dist.Distribution.get_egg_cache_dir = get_egg_cache_dir_pyver
else:
# old workaround is not needed anymore, this code was still around in 53
print('ERROR: no get_egg_cache_dir found in setuptools.dist.Distribution')
# fetch_build_egg was updated in setuptools 42 to use 'from setuptools.installer import fetch_build_egg'
# however, that one has logic to use pip
# reverting this code to the pre-42 behaviour
if hasattr(setuptools.dist.Distribution, 'fetch_build_egg'):
setuptools.dist.Distribution._orig_fetch_build_egg = setuptools.dist.Distribution.fetch_build_egg
# verbatim copy of 41.6.0-1.el8 setuptools.dist code
def fetch_build_egg_pyver(self, req):
"""Fetch an egg needed for building"""
from setuptools.command.easy_install import easy_install
dist = self.__class__({'script_args': ['easy_install']})
opts = dist.get_option_dict('easy_install')
opts.clear()
opts.update(
(k, v)
for k, v in self.get_option_dict('easy_install').items()
if k in (
# don't use any other settings
'find_links', 'site_dirs', 'index_url',
'optimize', 'site_dirs', 'allow_hosts',
))
if self.dependency_links:
links = self.dependency_links[:]
if 'find_links' in opts:
links = opts['find_links'][1] + links
opts['find_links'] = ('setup', links)
install_dir = self.get_egg_cache_dir()
cmd = easy_install(
dist, args=["x"], install_dir=install_dir,
exclude_scripts=True,
always_copy=False, build_directory=None, editable=False,
upgrade=False, multi_version=True, no_report=True, user=False
)
cmd.ensure_finalized()
return cmd.easy_install(req)
setuptools.dist.Distribution.fetch_build_egg = fetch_build_egg_pyver
else:
print('ERROR: no fetch_build_egg found in setuptools.dist.Distribution')
class vsc_setup():
"""
Store these Constants in a separate class instead of creating them at runtime,
so shared setup can setup another package that uses shared setup.
This vsc_setup class is mainly here to define a scope, and keep the data from
files_in_packages cashed a bit
"""
def __init__(self):
"""Setup the given package"""
# determine the base directory of the repository
# set it via REPO_BASE_DIR (mainly to support non-"python setup" usage/hacks)
_repo_base_dir_env = os.environ.get('REPO_BASE_DIR', None)
if _repo_base_dir_env:
self.REPO_BASE_DIR = _repo_base_dir_env
log.warn('run_tests from base dir set though environment %s', self.REPO_BASE_DIR)
else:
# we will assume that the tests are called from
# a 'setup.py' like file in the basedirectory
# (but could be called anything, as long as it is in the basedir)
_setup_py = os.path.abspath(sys.argv[0])
self.REPO_BASE_DIR = os.path.dirname(_setup_py)
log.info('run_tests from base dir %s (using executable %s)', self.REPO_BASE_DIR, _setup_py)
self.REPO_LIB_DIR = os.path.join(self.REPO_BASE_DIR, DEFAULT_LIB_DIR)
self.REPO_SCRIPTS_DIR = os.path.join(self.REPO_BASE_DIR, 'bin')
self.REPO_TEST_DIR = os.path.join(self.REPO_BASE_DIR, DEFAULT_TEST_SUITE)
self.package_files = self.files_in_packages()
self.private_repo = False
@staticmethod
def release_on_pypi(lic):
"""Given license lic, can/will we release on PyPI"""
return lic in PYPI_LICENSES
def get_name_url(self, filename=None, version=None, license_name=None):
"""
Determine name and url of project
url has to be either homepage or hpcugent remote repository (typically upstream)
"""
if filename is None:
git_config = os.path.join(self.REPO_BASE_DIR, '.git', 'config')
pkg_info = os.path.join(self.REPO_BASE_DIR, 'PKG-INFO')
if os.path.isfile(pkg_info):
# e.g. from sdist
filename = pkg_info
elif os.path.isfile(git_config):
filename = git_config
if filename is None:
raise ValueError('no file to get name from')
if not os.path.isfile(filename):
raise ValueError(f'cannot find file {filename} to get name from')
txt = _read(filename)
# First ones are from PKG-INFO
# second one is .git/config
# multiline search
# github pattern for hpcugent, not fork
git_remote_patterns = [f'{remote}.*?[:/]{value}' for remote, value in GIT_REMOTES]
git_domain_pattern = f"(?:{'|'.join(git_remote_patterns)})"
all_patterns = {
'name': [
r'^Name:\s*(.*?)\s*$',
r'^\s*url\s*=.*/([^/]*?)(?:\.git)?\s*$',
],
'url': [
r'^Home-page:\s*(.*?)\s*$',
rf'^\s*url\s*=\s*((?:https?|ssh).*?{git_domain_pattern}/.*?)(?:\.git)?\s*$',
rf'^\s*url\s*=\s*(git[:@].*?{git_domain_pattern}/.*?)(?:\.git)?\s*$',
],
'download_url': [
r'^Download-URL:\s*(.*?)\s*$',
],
}
res = {}
for pat_name, patterns in all_patterns.items():
for pat in patterns:
reg = re.search(pat, txt[:10240], re.M)
if reg:
res[pat_name] = reg.group(1)
log.info('found match %s %s in %s', pat_name, res[pat_name], filename)
break
# handle git@server:user/project
reg = re.search(r'^git@(.*?):(.*)$', res.get('url', ''))
if reg:
res['url'] = f"https://{reg.group(1)}/{reg.group(2)}"
log.info('reg found: %s', reg.groups())
self.private_repo = True
if 'url' not in res:
allowed_remotes = ', '.join([f'{remote}/{value}' for remote, value in GIT_REMOTES])
raise KeyError(f"Missing url in git config {res}. (Missing mandatory remote? {allowed_remotes})")
# handle git://server/user/project
reg = re.search(r'^(git|ssh)://', res.get('url', ''))
if reg:
res['url'] = f"https://{res['url'][len(reg.group(0)):]}"
log.info('reg found: %s', reg.groups())
self.private_repo = True
if 'download_url' not in res:
if _fvs('get_name_url').release_on_pypi(license_name):
# no external download url
# force to None
res['download_url'] = None
elif 'github' in res.get('url', '') and version is not None:
res['download_url'] = f"{res['url']}/archive/{version}.tar.gz"
else:
# other remotes have no external download url
res['download_url'] = None
if len(res) != 3:
raise ValueError(f"Cannot determine name, url and download url from filename {filename}: got {res}")
else:
keepers = {}
for keep_name, value in res.items():
if value is None:
log.info('Removing None %s', keep_name)
else:
keepers[keep_name] = value
log.info('get_name_url returns %s', keepers)
return keepers
def rel_gitignore(self, paths, base_dir=None):
"""
A list of paths, return list of relative paths to REPO_BASE_DIR,
filter with primitive gitignore
This raises an error when there is a .git directory but no .gitignore
"""
if not base_dir:
base_dir = self.REPO_BASE_DIR
res = [os.path.relpath(p, base_dir) for p in paths]
# primitive gitignore
gitignore = os.path.join(base_dir, '.gitignore')
if os.path.isfile(gitignore):
all_patterns = [l for l in [l.strip() for l in _read(gitignore, read_lines=True)]
if l and not l.startswith('#')]
patterns = [l.replace('*', '.*') for l in all_patterns if l.startswith('*')]
reg = re.compile('^('+'|'.join(patterns)+')$')
# check if we at least filter out .pyc files, since we're in a python project
if not all([reg.search(text) for text in [f'bla{pattern}' for pattern in GITIGNORE_PATTERNS]]):
raise ValueError(f"{base_dir}/.gitignore does not contain these patterns: {GITIGNORE_PATTERNS}")
if not all(l in all_patterns for l in GITIGNORE_EXACT_PATTERNS):
raise ValueError(
f"{base_dir}/.gitignore does not contain all following patterns: {GITIGNORE_EXACT_PATTERNS}")
res = [f for f in res if not reg.search(f)]
elif os.path.isdir(os.path.join(base_dir, '.git')):
raise ValueError(f"No .gitignore in git repo: {base_dir}")
return res
def files_in_packages(self, excluded_pkgs=None):
"""
Gather all __init__ files provided by the lib/ subdir
filenames are relative to the REPO_BASE_DIR
If a directory exists matching a package but with no __init__.py,
it is ignored unless the package (not the path!) is in the excluded_pkgs list
Return dict with key
packages: a dict with key the package and value all files in the package directory
modules: dict with key non=package module name and value the filename
"""
if excluded_pkgs is None:
excluded_pkgs = []
res = {'packages': {}, 'modules': {}}
offset = len(self.REPO_LIB_DIR.split(os.path.sep))
for root, _, files in os.walk(self.REPO_LIB_DIR):
package = '.'.join(root.split(os.path.sep)[offset:])
if '__init__.py' in files or package in excluded_pkgs:
# Force vsc shared packages/namespace
if '__init__.py' in files and (package == 'vsc' or package.startswith('vsc.')):
init = _read(os.path.join(root, '__init__.py'))
if not re.search(r'^import\s+pkg_resources\n{1,3}pkg_resources.declare_namespace\(__name__\)$',
init, re.M):
raise ValueError(f'vsc namespace packages do not allow non-shared namespace in dir {root}.'
'Fix with pkg_resources.declare_namespace')
res['packages'][package] = self.rel_gitignore([os.path.join(root, f) for f in files])
# this is a package, all .py files are modules
for mod_fn in res['packages'][package]:
if not mod_fn.endswith('.py') or mod_fn.endswith('__init__.py'):
continue
modname = os.path.basename(mod_fn)[:-len('.py')]
res['modules'][f"{package}.{modname}"] = mod_fn
return res
@staticmethod
def find_extra_sdist_files():
"""Looks for files to append to the FileList that is used by the egg_info."""
log.info("looking for extra dist files")
filelist = []
for fn in EXTRA_SDIST_FILES:
if os.path.isfile(fn):
filelist.append(fn)
else:
log.error("sdist add_defaults Failed to find %s. Exiting.", fn)
sys.exit(1)
return filelist
def remove_extra_bdist_rpm_files(self, pkgs=None):
"""For list of packages pkgs, make the function to exclude all conflicting files from rpm"""
if pkgs is None:
pkgs = getattr(builtins, '__target').get('excluded_pkgs_rpm', [])
res = []
for pkg in pkgs:
all_files = self.package_files['packages'].get(pkg, [])
# only add overlapping files, in this case the __init__ providing/extending the namespace
res.extend([f for f in all_files if os.path.basename(f) == '__init__.py'])
log.info('files to be removed from rpm: %s', res)
return res
class vsc_sdist(sdist):
"""
Upon sdist, add this vsc.install.shared_setup to the sdist
and modifed the shipped setup.py to be able to use this
"""
def __init__(self, *args, **kwargs):
sdist.__init__(self, *args, **kwargs)
self.setup = _fvs('vsc_sdist')()
def _recopy(self, base_dir, *paths):
"""
re-copy file with relative os.path.join(paths), to avoid soft/hardlinks
(code based on setuptools.command.sdist make_release_tree method)
returns the final destination and content of the file
"""
dest = os.path.join(base_dir, *paths)
log.info('recopying dest %s if hardlinked', dest)
if hasattr(os, 'link') and os.path.exists(dest):
# unlink and re-copy, since it might be hard-linked, and
# we don't want to change the source version
os.unlink(dest)
self.copy_file(os.path.join(self.setup.REPO_BASE_DIR, *paths), dest)
code = _read(dest)
return dest, code
def _write(self, dest, code):
"""write code to dest"""
Path(dest).write_text(code, encoding='utf8')
def _copy_setup_py(self, base_dir):
"""
re-copy setup.py, to avoid soft/hardlinks
(code based on setuptools.command.sdist make_release_tree method)
"""
return self._recopy(base_dir, 'setup.py')
def _mod_setup_py(self, dest, code):
"""
Modify the setup.py in the distribution directory
"""
# look for first line that does someting with vsc.install and shared_setup
reg = re.search(r'^.*vsc.install.*shared_setup.*$', code, re.M)
if not reg:
raise ValueError("No vsc.install shared_setup in setup.py?")
# insert sys.path hack
before = reg.start()
# no indentation
code = code[:before] + NEW_SHARED_SETUP_HEADER_TEMPLATE % (
NEW_SHARED_SETUP, VERSION, EXTERNAL_DIR) + code[before:]
# replace 'vsc.install.shared_setup' -> NEW_SHARED_SETUP
code = re.sub(r'vsc\.install\.shared_setup', NEW_SHARED_SETUP, code)
# replace 'from vsc.install import shared_setup' -> import NEW_SHARED_SETUP as shared_setup
code = re.sub(r'from\s+vsc.install\s+import\s+shared_setup',
f'import {NEW_SHARED_SETUP} as shared_setup',
code)
self._write(dest, code)
def _add_shared_setup(self, base_dir):
"""Create the new shared_setup in distribution directory"""
ext_dir = os.path.join(base_dir, EXTERNAL_DIR)
os.mkdir(ext_dir)
dest = os.path.join(ext_dir, f'{NEW_SHARED_SETUP}.py')
log.info('inserting shared_setup as %s', dest)
try:
source_code = inspect.getsource(sys.modules[__name__])
except Exception as err: # have no clue what exceptions inspect might throw
raise Exception(f"sdist requires access shared_setup source ({err})") from err
try:
self._write(dest, source_code)
except OSError as err:
raise OSError(f"Failed to write NEW_SHARED_SETUP source to dest ({err})") from err
def make_release_tree(self, base_dir, files):
"""
Create the files in subdir base_dir ready for packaging
After the normal make_release_tree ran, we insert shared_setup
and modify the to-be-packaged setup.py
"""
log.info("sdist make_release_tree original base_dir %s files %s", base_dir, files)
log.info("sdist from shared_setup %s current dir %s", __file__, os.getcwd())
if os.path.exists(base_dir):
# no autocleanup?
# can be a leftover of earlier crash/raised exception
raise ValueError(f"base_dir {base_dir} present. Please remove it")
sdist.make_release_tree(self, base_dir, files)
# have to make sure setup.py is not a symlink
dest, code = self._copy_setup_py(base_dir)
if __name__ == '__main__':
log.info('running shared_setup as main, not adding it to sdist')
else:
# use a new name, to avoid confusion with original
self._mod_setup_py(dest, code)
self._add_shared_setup(base_dir)
# Add mandatory files
for fn in [LICENSE, README]:
self.copy_file(os.path.join(self.setup.REPO_BASE_DIR, fn), os.path.join(base_dir, fn))
class vsc_sdist_rpm(vsc_sdist):
"""Manipulate the shebang in all scripts"""
def make_release_tree(self, base_dir, files):
_fvs('vsc_sdist_rpm').vsc_sdist.make_release_tree(self, base_dir, files)
if self.distribution.has_scripts():
# code based on sdist add_defaults
build_scripts = self.get_finalized_command('build_scripts')
scripts = build_scripts.get_source_files()
log.info("scripts to check for shebang %s", scripts)
# does not include newline
pyshebang_reg = re.compile(rf'\A{SHEBANG_ENV_PYTHON}.*$', re.M)
for fn in scripts:
# includes newline
first_line = _read(os.path.join(base_dir, fn), read_lines=True)[0]
if pyshebang_reg.search(first_line):
log.info("going to adapt shebang for script %s", fn)
dest, code = self._recopy(base_dir, fn)
code = pyshebang_reg.sub(SHEBANG_STRIPPED_ENV_PYTHON, code)
self._write(dest, code)
else:
log.info("no scripts to check for shebang")
class vsc_egg_info(egg_info):
"""Class to determine the set of files that should be included.
This amounts to including the default files, as determined by setuptools, extended with the
few extra files we need to add for installation purposes.
"""
# pylint: disable=arguments-differ
def finalize_options(self, *args, **kwargs):
"""Handle missing lib dir for scripts-only packages"""
# the egginfo data will be deleted as part of the cleanup
cleanup = []
setupper = _fvs('vsc_egg_info finalize_options')()
if not os.path.exists(setupper.REPO_LIB_DIR):
log.warn('vsc_egg_info create missing %s (will be removed later)', setupper.REPO_LIB_DIR)
os.mkdir(setupper.REPO_LIB_DIR)
cleanup.append(setupper.REPO_LIB_DIR)
egg_info.finalize_options(self, *args, **kwargs)
# cleanup any diretcories created
for directory in cleanup:
shutil.rmtree(directory)
def find_sources(self):
"""Default lookup."""
egg_info.find_sources(self)
self.filelist.extend(_fvs('vsc_egg_info find_sources').find_extra_sdist_files())
class vsc_bdist_rpm_egg_info(vsc_egg_info):
"""Class to determine the source files that should be present in an (S)RPM.
All __init__.py files that augment package packages should be installed by the
dependent package, so we need not install it here.
"""
def find_sources(self):
"""Finds the sources as default and then drop the cruft."""
_fvs('vsc_bdist_rpm_egg_info').vsc_egg_info.find_sources(self)
for fn in _fvs('vsc_bdist_rpm_egg_info for')().remove_extra_bdist_rpm_files():
log.debug(f"removing {fn} from source list")
if fn in self.filelist.files:
self.filelist.files.remove(fn)
class vsc_install_scripts(install_scripts):
"""Create the (fake) links for mympirun also remove .sh and .py extensions from the scripts."""
def __init__(self, *args):
install_scripts.__init__(self, *args)
self.original_outfiles = None
self.outfiles = None
def run(self):
# old-style class
install_scripts.run(self)
self.original_outfiles = self.get_outputs()[:] # make a copy
self.outfiles = [] # reset it
for script in self.original_outfiles:
# remove suffixes for .py and .sh
if REGEXP_REMOVE_SUFFIX.search(script):
newscript = REGEXP_REMOVE_SUFFIX.sub('', script)
shutil.move(script, newscript)
script = newscript
self.outfiles.append(script)
class vsc_build_py(build_py):
def find_package_modules(self, package, package_dir):
"""Extend build_by (not used for now)"""
result = build_py.find_package_modules(self, package, package_dir)
return result
class vsc_bdist_rpm(orig_bdist_rpm):
"""
Custom class to build the RPM, since the __init__.py cannot be included for the packages
that have package spread across all of the machine.
"""
def run(self):
log.info(f"vsc_bdist_rpm = {self.__dict__}")
klass = _fvs('vsc_bdist_rpm egg_info')
# changed to allow file removal
self.distribution.cmdclass['egg_info'] = klass.vsc_bdist_rpm_egg_info
# changed to allow modification of shebangs
self.distribution.cmdclass['sdist'] = klass.vsc_sdist_rpm
self.run_command('egg_info') # ensure distro name is up-to-date
orig_bdist_rpm.run(self)
@staticmethod
def filter_testsuites(testsuites):
"""(Recursive) filtering of (suites of) tests"""
test_filter = getattr(builtins, '__test_filter')['function']
res = type(testsuites)()
for ts in testsuites:
# ts is either a test or testsuite of more tests
if isinstance(ts, TestSuite):
res.addTest(_fvs('filter_testsuites').filter_testsuites(ts))
else:
if re.search(test_filter, ts._testMethodName):
res.addTest(ts)
return res
class VscScanningLoader(ScanningLoader):
"""The class to look for tests"""
# This class cannot be modified by subclassing and _fvs
TEST_LOADER_MODULE = __name__
def loadTestsFromModule(self, module, pattern=None): # pylint: disable=arguments-differ
"""
Support test module and function name based filtering
"""
try:
try:
# pattern is new, this can fail on some old setuptools
testsuites = ScanningLoader.loadTestsFromModule(self, module, pattern)
except TypeError as e:
log.warn('pattern argument not supported on this setuptools yet, ignoring')
log.warn(f'original exception {e} {traceback.format_exc()}')
try:
testsuites = ScanningLoader.loadTestsFromModule(self, module)
except Exception:
log.error('Failed to load tests from module %s', module)
raise
except AttributeError as err:
# This error is not that useful
log.error('Failed to load tests from module %s', module)
# Handle specific class of exception due to import failures of the tests
reg = re.search(r'object has no attribute \'(.*)\'', str(err))
if reg:
test_module = '.'.join([module.__name__, reg.group(1)])
try:
__import__(test_module)
except ImportError as e:
tpl = "Failed to import test module %s: %s (derived from original exception %s)"
raise ImportError(tpl % (test_module, e, err)) from e
raise
test_filter = getattr(builtins, '__test_filter')
res = testsuites
if test_filter['module'] is not None:
mname = module.__name__
if mname in test_filter['allowmods']:
# a parent name space
pass
elif re.search(test_filter['module'], mname):
if test_filter['function'] is not None:
res = _fvs('loadTestsFromModule').filter_testsuites(testsuites)
# add parents (and module itself)
pms = mname.split('.')
for pm_idx in range(len(pms)):
pm = '.'.join(pms[:pm_idx])
if pm not in test_filter['allowmods']:
test_filter['allowmods'].append(pm)
else:
res = type(testsuites)()
return res
class VscTestCommand(TestCommand):
"""
The cmdclass for testing
"""
# make 2 new 'python setup.py test' options available
user_options = TestCommand.user_options + [
('test-filterf=', 'f', "Regex filter on test function names"),
('test-filterm=', 'F', "Regex filter on test (sub)modules"),
('test-xmlrunner=', 'X', "use XMLTestRunner with value as output name (e.g. test-reports)"),
]
# You cannot use the _fvs here, so this cannot be modified by subclassing
TEST_LOADER = 'vsc.install.shared_setup:vsc_setup.VscScanningLoader'
def initialize_options(self):
"""
Add attributes for new commandline options and set test_loader
"""
TestCommand.initialize_options(self)
self.test_filterm = None
self.test_filterf = None
self.test_xmlrunner = None
self.setupper = _fvs('VscTestCommand initialize_options')()
self.test_loader = self.TEST_LOADER
log.info(f"test_loader set to {self.test_loader}")
def reload_modules(self, package, remove_only=False, own_modules=False):
"""
Cleanup and restore package because we use
vsc package tools very early.
So we need to make sure they are picked up from the paths as specified
in setup_sys_path, not to mix with installed and already loaded modules
If remove_only, only remove, not reload
If own_modules, only remove modules provided by this "repository"
"""
def candidate(modulename):
"""Select candidate modules to reload"""
module_in_package = modulename in (package,) or modulename.startswith(package+'.')
if own_modules:
is_own_module = modulename in self.setupper.files_in_packages()['modules']
else:
is_own_module = True
return module_in_package and is_own_module
reload_modules = []
# sort package first
loaded_modules = sorted(filter(candidate, sys.modules.keys()))
# remove package last
for mname in loaded_modules[::-1]:
if hasattr(sys.modules[mname], '__file__'):
# only actual modules, filo ordered
reload_modules.insert(0, mname)
del sys.modules[mname]
if not remove_only:
# reimport
for mname in reload_modules:
__import__(mname)
return reload_modules
def setup_sys_path(self):
"""
Prepare sys.path to be able to
use the modules provided by this package (assumeing they are in 'lib')
use any scripts as modules (for unittesting)
use the test modules as modules (for unittesting)
Returns a list of directories to cleanup
"""
cleanup = []
# make a lib dir to trick setup.py to package this properly
# and git ignore empty dirs, so recreate it if necessary
if not os.path.exists(self.setupper.REPO_LIB_DIR):
os.mkdir(self.setupper.REPO_LIB_DIR)
cleanup.append(self.setupper.REPO_LIB_DIR)
if os.path.isdir(self.setupper.REPO_TEST_DIR):
sys.path.insert(0, self.setupper.REPO_TEST_DIR)
else:
raise ValueError(
f"Can't find location of testsuite directory {DEFAULT_TEST_SUITE} in {self.setupper.REPO_BASE_DIR}")
# insert REPO_BASE_DIR, so import DEFAULT_TEST_SUITE works (and nothing else gets picked up)
sys.path.insert(0, self.setupper.REPO_BASE_DIR)
# make sure we can import the script as a module
if os.path.isdir(self.setupper.REPO_SCRIPTS_DIR):
sys.path.insert(0, self.setupper.REPO_SCRIPTS_DIR)