forked from spack/spack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage.py
More file actions
3020 lines (2481 loc) · 117 KB
/
package.py
File metadata and controls
3020 lines (2481 loc) · 117 KB
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 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""This is where most of the action happens in Spack.
The spack package class structure is based strongly on Homebrew
(http://brew.sh/), mainly because Homebrew makes it very easy to create
packages.
"""
import base64
import collections
import contextlib
import copy
import functools
import glob
import hashlib
import inspect
import os
import re
import shutil
import sys
import textwrap
import time
import traceback
import types
from typing import Any, Callable, Dict, List, Optional # novm
import six
import llnl.util.filesystem as fsys
import llnl.util.tty as tty
from llnl.util.lang import memoized
from llnl.util.link_tree import LinkTree
import spack.compilers
import spack.config
import spack.dependency
import spack.directives
import spack.directory_layout
import spack.environment
import spack.error
import spack.fetch_strategy as fs
import spack.hooks
import spack.mirror
import spack.mixins
import spack.multimethod
import spack.paths
import spack.repo
import spack.store
import spack.url
import spack.util.environment
import spack.util.web
from spack.filesystem_view import YamlFilesystemView
from spack.install_test import TestFailure, TestSuite
from spack.installer import InstallError, PackageInstaller
from spack.stage import ResourceStage, Stage, StageComposite, stage_prefix
from spack.util.executable import ProcessError, which
from spack.util.package_hash import package_hash
from spack.util.path import win_exe_ext
from spack.util.prefix import Prefix
from spack.version import Version
"""Allowed URL schemes for spack packages."""
_ALLOWED_URL_SCHEMES = ["http", "https", "ftp", "file", "git"]
# Filename for the Spack build/install log.
_spack_build_logfile = 'spack-build-out.txt'
# Filename for the Spack build/install environment file.
_spack_build_envfile = 'spack-build-env.txt'
# Filename for the Spack build/install environment modifications file.
_spack_build_envmodsfile = 'spack-build-env-mods.txt'
# Filename of json with total build and phase times (seconds)
_spack_times_log = 'install_times.json'
# Filename for the Spack configure args file.
_spack_configure_argsfile = 'spack-configure-args.txt'
def preferred_version(pkg):
"""
Returns a sorted list of the preferred versions of the package.
Arguments:
pkg (Package): The package whose versions are to be assessed.
"""
# Here we sort first on the fact that a version is marked
# as preferred in the package, then on the fact that the
# version is not develop, then lexicographically
key_fn = lambda v: (pkg.versions[v].get('preferred', False),
not v.isdevelop(),
v)
return sorted(pkg.versions, key=key_fn).pop()
class InstallPhase(object):
"""Manages a single phase of the installation.
This descriptor stores at creation time the name of the method it should
search for execution. The method is retrieved at __get__ time, so that
it can be overridden by subclasses of whatever class declared the phases.
It also provides hooks to execute arbitrary callbacks before and after
the phase.
"""
def __init__(self, name):
self.name = name
self.run_before = []
self.run_after = []
def __get__(self, instance, owner):
# The caller is a class that is trying to customize
# my behavior adding something
if instance is None:
return self
# If instance is there the caller wants to execute the
# install phase, thus return a properly set wrapper
phase = getattr(instance, self.name)
@functools.wraps(phase)
def phase_wrapper(spec, prefix):
# Check instance attributes at the beginning of a phase
self._on_phase_start(instance)
# Execute phase pre-conditions,
# and give them the chance to fail
for callback in self.run_before:
callback(instance)
phase(spec, prefix)
# Execute phase sanity_checks,
# and give them the chance to fail
for callback in self.run_after:
callback(instance)
# Check instance attributes at the end of a phase
self._on_phase_exit(instance)
return phase_wrapper
def _on_phase_start(self, instance):
# If a phase has a matching stop_before_phase attribute,
# stop the installation process raising a StopPhase
if getattr(instance, 'stop_before_phase', None) == self.name:
from spack.build_environment import StopPhase
raise StopPhase('Stopping before \'{0}\' phase'.format(self.name))
def _on_phase_exit(self, instance):
# If a phase has a matching last_phase attribute,
# stop the installation process raising a StopPhase
if getattr(instance, 'last_phase', None) == self.name:
from spack.build_environment import StopPhase
raise StopPhase('Stopping at \'{0}\' phase'.format(self.name))
def copy(self):
try:
return copy.deepcopy(self)
except TypeError:
# This bug-fix was not back-ported in Python 2.6
# http://bugs.python.org/issue1515
other = InstallPhase(self.name)
other.run_before.extend(self.run_before)
other.run_after.extend(self.run_after)
return other
#: Registers which are the detectable packages, by repo and package name
#: Need a pass of package repositories to be filled.
detectable_packages = collections.defaultdict(list)
class DetectablePackageMeta(object):
"""Check if a package is detectable and add default implementations
for the detection function.
"""
def __init__(cls, name, bases, attr_dict):
if hasattr(cls, 'executables') and hasattr(cls, 'libraries'):
msg = "a package can have either an 'executables' or 'libraries' attribute"
msg += " [package '{0.name}' defines both]"
raise spack.error.SpackError(msg.format(cls))
# On windows, extend the list of regular expressions to look for
# filenames ending with ".exe"
# (in some cases these regular expressions include "$" to avoid
# pulling in filenames with unexpected suffixes, but this allows
# for example detecting "foo.exe" when the package writer specified
# that "foo" was a possible executable.
# If a package has the executables or libraries attribute then it's
# assumed to be detectable
if hasattr(cls, 'executables') or hasattr(cls, 'libraries'):
@property
def platform_executables(self):
def to_windows_exe(exe):
if exe.endswith('$'):
exe = exe.replace('$', '%s$' % win_exe_ext())
else:
exe += win_exe_ext()
return exe
plat_exe = []
if hasattr(self, 'executables'):
for exe in self.executables:
if sys.platform == 'win32':
exe = to_windows_exe(exe)
plat_exe.append(exe)
return plat_exe
@classmethod
def determine_spec_details(cls, prefix, objs_in_prefix):
"""Allow ``spack external find ...`` to locate installations.
Args:
prefix (str): the directory containing the executables
or libraries
objs_in_prefix (set): the executables or libraries that
match the regex
Returns:
The list of detected specs for this package
"""
objs_by_version = collections.defaultdict(list)
# The default filter function is the identity function for the
# list of executables
filter_fn = getattr(cls, 'filter_detected_exes',
lambda x, exes: exes)
objs_in_prefix = filter_fn(prefix, objs_in_prefix)
for obj in objs_in_prefix:
try:
version_str = cls.determine_version(obj)
if version_str:
objs_by_version[version_str].append(obj)
except Exception as e:
msg = ('An error occurred when trying to detect '
'the version of "{0}" [{1}]')
tty.debug(msg.format(obj, str(e)))
specs = []
for version_str, objs in objs_by_version.items():
variants = cls.determine_variants(objs, version_str)
# Normalize output to list
if not isinstance(variants, list):
variants = [variants]
for variant in variants:
if isinstance(variant, six.string_types):
variant = (variant, {})
variant_str, extra_attributes = variant
spec_str = '{0}@{1} {2}'.format(
cls.name, version_str, variant_str
)
# Pop a few reserved keys from extra attributes, since
# they have a different semantics
external_path = extra_attributes.pop('prefix', None)
external_modules = extra_attributes.pop(
'modules', None
)
try:
spec = spack.spec.Spec(
spec_str,
external_path=external_path,
external_modules=external_modules
)
except Exception as e:
msg = 'Parsing failed [spec_str="{0}", error={1}]'
tty.debug(msg.format(spec_str, str(e)))
else:
specs.append(spack.spec.Spec.from_detection(
spec, extra_attributes=extra_attributes
))
return sorted(specs)
@classmethod
def determine_variants(cls, objs, version_str):
return ''
# Register the class as a detectable package
detectable_packages[cls.namespace].append(cls.name)
# Attach function implementations to the detectable class
default = False
if not hasattr(cls, 'determine_spec_details'):
default = True
cls.determine_spec_details = determine_spec_details
if default and not hasattr(cls, 'determine_version'):
msg = ('the package "{0}" in the "{1}" repo needs to define'
' the "determine_version" method to be detectable')
NotImplementedError(msg.format(cls.name, cls.namespace))
if default and not hasattr(cls, 'determine_variants'):
cls.determine_variants = determine_variants
# This function should not be overridden by subclasses,
# as it is not designed for bespoke pkg detection but rather
# on a per-platform basis
if 'platform_executables' in cls.__dict__.keys():
raise PackageError("Packages should not override platform_executables")
cls.platform_executables = platform_executables
super(DetectablePackageMeta, cls).__init__(name, bases, attr_dict)
class PackageMeta(
DetectablePackageMeta,
spack.directives.DirectiveMeta,
spack.mixins.PackageMixinsMeta,
spack.multimethod.MultiMethodMeta
):
"""
Package metaclass for supporting directives (e.g., depends_on) and phases
"""
phase_fmt = '_InstallPhase_{0}'
# These are accessed only through getattr, by name
_InstallPhase_run_before = {} # type: Dict[str, List[Callable]]
_InstallPhase_run_after = {} # type: Dict[str, List[Callable]]
def __new__(cls, name, bases, attr_dict):
"""
Instance creation is preceded by phase attribute transformations.
Conveniently transforms attributes to permit extensible phases by
iterating over the attribute 'phases' and creating / updating private
InstallPhase attributes in the class that will be initialized in
__init__.
"""
if 'phases' in attr_dict:
# Turn the strings in 'phases' into InstallPhase instances
# and add them as private attributes
_InstallPhase_phases = [PackageMeta.phase_fmt.format(x) for x in attr_dict['phases']] # NOQA: ignore=E501
for phase_name, callback_name in zip(_InstallPhase_phases, attr_dict['phases']): # NOQA: ignore=E501
attr_dict[phase_name] = InstallPhase(callback_name)
attr_dict['_InstallPhase_phases'] = _InstallPhase_phases
def _flush_callbacks(check_name):
# Name of the attribute I am going to check it exists
check_attr = PackageMeta.phase_fmt.format(check_name)
checks = getattr(cls, check_attr)
if checks:
for phase_name, funcs in checks.items():
phase_attr = PackageMeta.phase_fmt.format(phase_name)
try:
# Search for the phase in the attribute dictionary
phase = attr_dict[phase_attr]
except KeyError:
# If it is not there it's in the bases
# and we added a check. We need to copy
# and extend
for base in bases:
phase = getattr(base, phase_attr, None)
if phase is not None:
break
phase = attr_dict[phase_attr] = phase.copy()
getattr(phase, check_name).extend(funcs)
# Clear the attribute for the next class
setattr(cls, check_attr, {})
_flush_callbacks('run_before')
_flush_callbacks('run_after')
# Reset names for packages that inherit from another
# package with a different name
attr_dict['_name'] = None
return super(PackageMeta, cls).__new__(cls, name, bases, attr_dict)
@staticmethod
def register_callback(check_type, *phases):
def _decorator(func):
attr_name = PackageMeta.phase_fmt.format(check_type)
check_list = getattr(PackageMeta, attr_name)
for item in phases:
checks = check_list.setdefault(item, [])
checks.append(func)
setattr(PackageMeta, attr_name, check_list)
return func
return _decorator
@property
def package_dir(self):
"""Directory where the package.py file lives."""
return os.path.abspath(os.path.dirname(self.module.__file__))
@property
def module(self):
"""Module object (not just the name) that this package is defined in.
We use this to add variables to package modules. This makes
install() methods easier to write (e.g., can call configure())
"""
return __import__(self.__module__, fromlist=[self.__name__])
@property
def namespace(self):
"""Spack namespace for the package, which identifies its repo."""
return spack.repo.namespace_from_fullname(self.__module__)
@property
def fullname(self):
"""Name of this package, including the namespace"""
return '%s.%s' % (self.namespace, self.name)
@property
def fullnames(self):
"""
Fullnames for this package and any packages from which it inherits.
"""
fullnames = []
for cls in inspect.getmro(self):
namespace = getattr(cls, 'namespace', None)
if namespace:
fullnames.append('%s.%s' % (namespace, self.name))
if namespace == 'builtin':
# builtin packages cannot inherit from other repos
break
return fullnames
@property
def name(self):
"""The name of this package.
The name of a package is the name of its Python module, without
the containing module names.
"""
if self._name is None:
self._name = self.module.__name__
if '.' in self._name:
self._name = self._name[self._name.rindex('.') + 1:]
return self._name
def run_before(*phases):
"""Registers a method of a package to be run before a given phase"""
return PackageMeta.register_callback('run_before', *phases)
def run_after(*phases):
"""Registers a method of a package to be run after a given phase"""
return PackageMeta.register_callback('run_after', *phases)
def on_package_attributes(**attr_dict):
"""Decorator: executes instance function only if object has attr valuses.
Executes the decorated method only if at the moment of calling the
instance has attributes that are equal to certain values.
Args:
attr_dict (dict): dictionary mapping attribute names to their
required values
"""
def _execute_under_condition(func):
@functools.wraps(func)
def _wrapper(instance, *args, **kwargs):
# If all the attributes have the value we require, then execute
has_all_attributes = all(
[hasattr(instance, key) for key in attr_dict]
)
if has_all_attributes:
has_the_right_values = all(
[getattr(instance, key) == value for key, value in attr_dict.items()] # NOQA: ignore=E501
)
if has_the_right_values:
func(instance, *args, **kwargs)
return _wrapper
return _execute_under_condition
class PackageViewMixin(object):
"""This collects all functionality related to adding installed Spack
package to views. Packages can customize how they are added to views by
overriding these functions.
"""
def view_source(self):
"""The source root directory that will be added to the view: files are
added such that their path relative to the view destination matches
their path relative to the view source.
"""
return self.spec.prefix
def view_destination(self, view):
"""The target root directory: each file is added relative to this
directory.
"""
return view.get_projection_for_spec(self.spec)
def view_file_conflicts(self, view, merge_map):
"""Report any files which prevent adding this package to the view. The
default implementation looks for any files which already exist.
Alternative implementations may allow some of the files to exist in
the view (in this case they would be omitted from the results).
"""
return set(dst for dst in merge_map.values() if os.path.lexists(dst))
def add_files_to_view(self, view, merge_map, skip_if_exists=True):
"""Given a map of package files to destination paths in the view, add
the files to the view. By default this adds all files. Alternative
implementations may skip some files, for example if other packages
linked into the view already include the file.
Args:
view (spack.filesystem_view.FilesystemView): the view that's updated
merge_map (dict): maps absolute source paths to absolute dest paths for
all files in from this package.
skip_if_exists (bool): when True, don't link files in view when they
already exist. When False, always link files, without checking
if they already exist.
"""
if skip_if_exists:
for src, dst in merge_map.items():
if not os.path.lexists(dst):
view.link(src, dst, spec=self.spec)
else:
for src, dst in merge_map.items():
view.link(src, dst, spec=self.spec)
def remove_files_from_view(self, view, merge_map):
"""Given a map of package files to files currently linked in the view,
remove the files from the view. The default implementation removes all
files. Alternative implementations may not remove all files. For
example if two packages include the same file, it should only be
removed when both packages are removed.
"""
view.remove_files(merge_map.values())
def test_log_pathname(test_stage, spec):
"""Build the pathname of the test log file
Args:
test_stage (str): path to the test stage directory
spec (spack.spec.Spec): instance of the spec under test
Returns:
(str): the pathname of the test log file
"""
return os.path.join(test_stage,
'test-{0}-out.txt'.format(TestSuite.test_pkg_id(spec)))
class PackageBase(six.with_metaclass(PackageMeta, PackageViewMixin, object)):
"""This is the superclass for all spack packages.
***The Package class***
At its core, a package consists of a set of software to be installed.
A package may focus on a piece of software and its associated software
dependencies or it may simply be a set, or bundle, of software. The
former requires defining how to fetch, verify (via, e.g., sha256), build,
and install that software and the packages it depends on, so that
dependencies can be installed along with the package itself. The latter,
sometimes referred to as a ``no-source`` package, requires only defining
the packages to be built.
Packages are written in pure Python.
There are two main parts of a Spack package:
1. **The package class**. Classes contain ``directives``, which are
special functions, that add metadata (versions, patches,
dependencies, and other information) to packages (see
``directives.py``). Directives provide the constraints that are
used as input to the concretizer.
2. **Package instances**. Once instantiated, a package is
essentially a software installer. Spack calls methods like
``do_install()`` on the ``Package`` object, and it uses those to
drive user-implemented methods like ``patch()``, ``install()``, and
other build steps. To install software, an instantiated package
needs a *concrete* spec, which guides the behavior of the various
install methods.
Packages are imported from repos (see ``repo.py``).
**Package DSL**
Look in ``lib/spack/docs`` or check https://spack.readthedocs.io for
the full documentation of the package domain-specific language. That
used to be partially documented here, but as it grew, the docs here
became increasingly out of date.
**Package Lifecycle**
A package's lifecycle over a run of Spack looks something like this:
.. code-block:: python
p = Package() # Done for you by spack
p.do_fetch() # downloads tarball from a URL (or VCS)
p.do_stage() # expands tarball in a temp directory
p.do_patch() # applies patches to expanded source
p.do_install() # calls package's install() function
p.do_uninstall() # removes install directory
although packages that do not have code have nothing to fetch so omit
``p.do_fetch()``.
There are also some other commands that clean the build area:
.. code-block:: python
p.do_clean() # removes the stage directory entirely
p.do_restage() # removes the build directory and
# re-expands the archive.
The convention used here is that a ``do_*`` function is intended to be
called internally by Spack commands (in ``spack.cmd``). These aren't for
package writers to override, and doing so may break the functionality
of the Package class.
Package creators have a lot of freedom, and they could technically
override anything in this class. That is not usually required.
For most use cases. Package creators typically just add attributes
like ``homepage`` and, for a code-based package, ``url``, or functions
such as ``install()``.
There are many custom ``Package`` subclasses in the
``spack.build_systems`` package that make things even easier for
specific build systems.
"""
#
# These are default values for instance variables.
#
#: A list or set of build time test functions to be called when tests
#: are executed or 'None' if there are no such test functions.
build_time_test_callbacks = None # type: Optional[List[str]]
#: By default, packages are not virtual
#: Virtual packages override this attribute
virtual = False
#: Most Spack packages are used to install source or binary code while
#: those that do not can be used to install a set of other Spack packages.
has_code = True
#: A list or set of install time test functions to be called when tests
#: are executed or 'None' if there are no such test functions.
install_time_test_callbacks = None # type: Optional[List[str]]
#: By default we build in parallel. Subclasses can override this.
parallel = True
#: By default do not run tests within package's install()
run_tests = False
# FIXME: this is a bad object-oriented design, should be moved to Clang.
#: By default do not setup mockup XCode on macOS with Clang
use_xcode = False
#: Most packages are NOT extendable. Set to True if you want extensions.
extendable = False
#: When True, add RPATHs for the entire DAG. When False, add RPATHs only
#: for immediate dependencies.
transitive_rpaths = True
#: List of prefix-relative file paths (or a single path). If these do
#: not exist after install, or if they exist but are not files,
#: sanity checks fail.
sanity_check_is_file = [] # type: List[str]
#: List of prefix-relative directory paths (or a single path). If
#: these do not exist after install, or if they exist but are not
#: directories, sanity checks will fail.
sanity_check_is_dir = [] # type: List[str]
#: List of glob expressions. Each expression must either be
#: absolute or relative to the package source path.
#: Matching artifacts found at the end of the build process will be
#: copied in the same directory tree as _spack_build_logfile and
#: _spack_build_envfile.
archive_files = [] # type: List[str]
#: Boolean. Set to ``True`` for packages that require a manual download.
#: This is currently used by package sanity tests and generation of a
#: more meaningful fetch failure error.
manual_download = False
#: Set of additional options used when fetching package versions.
fetch_options = {} # type: Dict[str, Any]
#
# Set default licensing information
#
#: Boolean. If set to ``True``, this software requires a license.
#: If set to ``False``, all of the ``license_*`` attributes will
#: be ignored. Defaults to ``False``.
license_required = False
#: String. Contains the symbol used by the license manager to denote
#: a comment. Defaults to ``#``.
license_comment = '#'
#: List of strings. These are files that the software searches for when
#: looking for a license. All file paths must be relative to the
#: installation directory. More complex packages like Intel may require
#: multiple licenses for individual components. Defaults to the empty list.
license_files = [] # type: List[str]
#: List of strings. Environment variables that can be set to tell the
#: software where to look for a license if it is not in the usual location.
#: Defaults to the empty list.
license_vars = [] # type: List[str]
#: String. A URL pointing to license setup instructions for the software.
#: Defaults to the empty string.
license_url = ''
#: Verbosity level, preserved across installs.
_verbose = None
#: index of patches by sha256 sum, built lazily
_patches_by_hash = None
#: Package homepage where users can find more information about the package
homepage = None # type: str
#: Default list URL (place to find available versions)
list_url = None # type: str
#: Link depth to which list_url should be searched for new versions
list_depth = 0
#: List of strings which contains GitHub usernames of package maintainers.
#: Do not include @ here in order not to unnecessarily ping the users.
maintainers = [] # type: List[str]
#: List of attributes to be excluded from a package's hash.
metadata_attrs = [
"homepage",
"url",
"urls",
"list_url",
"extendable",
"parallel",
"make_jobs",
"maintainers",
"tags",
]
#: Boolean. If set to ``True``, the smoke/install test requires a compiler.
#: This is currently used by smoke tests to ensure a compiler is available
#: to build a custom test code.
test_requires_compiler = False
#: List of test failures encountered during a smoke/install test run.
test_failures = None
#: TestSuite instance used to manage smoke/install tests for one or more
#: specs.
test_suite = None
def __init__(self, spec):
# this determines how the package should be built.
self.spec = spec
# Allow custom staging paths for packages
self.path = None
# Keep track of whether or not this package was installed from
# a binary cache.
self.installed_from_binary_cache = False
# Ensure that only one of these two attributes are present
if getattr(self, 'url', None) and getattr(self, 'urls', None):
msg = "a package can have either a 'url' or a 'urls' attribute"
msg += " [package '{0.name}' defines both]"
raise ValueError(msg.format(self))
# init internal variables
self._stage = None
self._fetcher = None
# Set up timing variables
self._fetch_time = 0.0
if self.is_extension:
spack.repo.get(self.extendee_spec)._check_extendable()
super(PackageBase, self).__init__()
@property
def installed_upstream(self):
if not hasattr(self, '_installed_upstream'):
upstream, record = spack.store.db.query_by_spec_hash(
self.spec.dag_hash())
self._installed_upstream = upstream
return self._installed_upstream
@classmethod
def possible_dependencies(
cls, transitive=True, expand_virtuals=True, deptype='all',
visited=None, missing=None, virtuals=None):
"""Return dict of possible dependencies of this package.
Args:
transitive (bool or None): return all transitive dependencies if
True, only direct dependencies if False (default True)..
expand_virtuals (bool or None): expand virtual dependencies into
all possible implementations (default True)
deptype (str or tuple or None): dependency types to consider
visited (dict or None): dict of names of dependencies visited so
far, mapped to their immediate dependencies' names.
missing (dict or None): dict to populate with packages and their
*missing* dependencies.
virtuals (set): if provided, populate with virtuals seen so far.
Returns:
(dict): dictionary mapping dependency names to *their*
immediate dependencies
Each item in the returned dictionary maps a (potentially
transitive) dependency of this package to its possible
*immediate* dependencies. If ``expand_virtuals`` is ``False``,
virtual package names wil be inserted as keys mapped to empty
sets of dependencies. Virtuals, if not expanded, are treated as
though they have no immediate dependencies.
Missing dependencies by default are ignored, but if a
missing dict is provided, it will be populated with package names
mapped to any dependencies they have that are in no
repositories. This is only populated if transitive is True.
Note: the returned dict *includes* the package itself.
"""
deptype = spack.dependency.canonical_deptype(deptype)
visited = {} if visited is None else visited
missing = {} if missing is None else missing
visited.setdefault(cls.name, set())
for name, conditions in cls.dependencies.items():
# check whether this dependency could be of the type asked for
types = [dep.type for cond, dep in conditions.items()]
types = set.union(*types)
if not any(d in types for d in deptype):
continue
# expand virtuals if enabled, otherwise just stop at virtuals
if spack.repo.path.is_virtual(name):
if virtuals is not None:
virtuals.add(name)
if expand_virtuals:
providers = spack.repo.path.providers_for(name)
dep_names = [spec.name for spec in providers]
else:
visited.setdefault(cls.name, set()).add(name)
visited.setdefault(name, set())
continue
else:
dep_names = [name]
# add the dependency names to the visited dict
visited.setdefault(cls.name, set()).update(set(dep_names))
# recursively traverse dependencies
for dep_name in dep_names:
if dep_name in visited:
continue
visited.setdefault(dep_name, set())
# skip the rest if not transitive
if not transitive:
continue
try:
dep_cls = spack.repo.path.get_pkg_class(dep_name)
except spack.repo.UnknownPackageError:
# log unknown packages
missing.setdefault(cls.name, set()).add(dep_name)
continue
dep_cls.possible_dependencies(
transitive, expand_virtuals, deptype, visited, missing,
virtuals)
return visited
def enum_constraints(self, visited=None):
"""Return transitive dependency constraints on this package."""
if visited is None:
visited = set()
visited.add(self.name)
names = []
clauses = []
for name in self.dependencies:
if name not in visited and not spack.spec.Spec(name).virtual:
pkg = spack.repo.get(name)
dvis, dnames, dclauses = pkg.enum_constraints(visited)
visited |= dvis
names.extend(dnames)
clauses.extend(dclauses)
return visited
# package_dir and module are *class* properties (see PackageMeta),
# but to make them work on instances we need these defs as well.
@property
def package_dir(self):
"""Directory where the package.py file lives."""
return type(self).package_dir
@property
def module(self):
"""Module object that this package is defined in."""
return type(self).module
@property
def namespace(self):
"""Spack namespace for the package, which identifies its repo."""
return type(self).namespace
@property
def fullname(self):
"""Name of this package, including namespace: namespace.name."""
return type(self).fullname
@property
def fullnames(self):
return type(self).fullnames
@property
def name(self):
"""Name of this package (the module without parent modules)."""
return type(self).name
@property
def global_license_dir(self):
"""Returns the directory where global license files for all
packages are stored."""
return os.path.join(spack.paths.prefix, 'etc', 'spack', 'licenses')
@property
def global_license_file(self):
"""Returns the path where a global license file for this
particular package should be stored."""
if not self.license_files:
return
return os.path.join(self.global_license_dir, self.name,
os.path.basename(self.license_files[0]))
@property
def version(self):
if not self.spec.versions.concrete:
raise ValueError("Version requested for a package that"
" does not have a concrete version.")
return self.spec.versions[0]
@memoized
def version_urls(self):
"""OrderedDict of explicitly defined URLs for versions of this package.
Return:
An OrderedDict (version -> URL) different versions of this
package, sorted by version.
A version's URL only appears in the result if it has an an
explicitly defined ``url`` argument. So, this list may be empty
if a package only defines ``url`` at the top level.
"""
version_urls = collections.OrderedDict()
for v, args in sorted(self.versions.items()):
if 'url' in args:
version_urls[v] = args['url']
return version_urls
def nearest_url(self, version):
"""Finds the URL with the "closest" version to ``version``.
This uses the following precedence order:
1. Find the next lowest or equal version with a URL.
2. If no lower URL, return the next *higher* URL.
3. If no higher URL, return None.
"""
version_urls = self.version_urls()
if version in version_urls:
return version_urls[version]
last_url = None
for v, u in self.version_urls().items():