summaryrefslogtreecommitdiff
path: root/lib/spack/spack/repo.py
blob: c4aa991b5d95845149c21cad5ea3cee2b62a20fe (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
# Copyright 2013-2024 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)

import abc
import collections.abc
import contextlib
import difflib
import errno
import functools
import importlib
import importlib.machinery
import importlib.util
import inspect
import itertools
import os
import os.path
import random
import re
import shutil
import stat
import string
import sys
import traceback
import types
import uuid
from typing import Any, Dict, List, Tuple, Union

import llnl.path
import llnl.util.filesystem as fs
import llnl.util.lang
import llnl.util.tty as tty
from llnl.util.filesystem import working_dir

import spack.caches
import spack.config
import spack.error
import spack.patch
import spack.provider_index
import spack.spec
import spack.tag
import spack.util.file_cache
import spack.util.git
import spack.util.naming as nm
import spack.util.path
import spack.util.spack_yaml as syaml

#: Package modules are imported as spack.pkg.<repo-namespace>.<pkg-name>
ROOT_PYTHON_NAMESPACE = "spack.pkg"


def python_package_for_repo(namespace):
    """Returns the full namespace of a repository, given its relative one

    For instance:

        python_package_for_repo('builtin') == 'spack.pkg.builtin'

    Args:
        namespace (str): repo namespace
    """
    return "{0}.{1}".format(ROOT_PYTHON_NAMESPACE, namespace)


def namespace_from_fullname(fullname):
    """Return the repository namespace only for the full module name.

    For instance:

        namespace_from_fullname('spack.pkg.builtin.hdf5') == 'builtin'

    Args:
        fullname (str): full name for the Python module
    """
    namespace, dot, module = fullname.rpartition(".")
    prefix_and_dot = "{0}.".format(ROOT_PYTHON_NAMESPACE)
    if namespace.startswith(prefix_and_dot):
        namespace = namespace[len(prefix_and_dot) :]
    return namespace


class _PrependFileLoader(importlib.machinery.SourceFileLoader):
    def __init__(self, fullname, path, prepend=None):
        super(_PrependFileLoader, self).__init__(fullname, path)
        self.prepend = prepend

    def path_stats(self, path):
        stats = super(_PrependFileLoader, self).path_stats(path)
        if self.prepend:
            stats["size"] += len(self.prepend) + 1
        return stats

    def get_data(self, path):
        data = super(_PrependFileLoader, self).get_data(path)
        if path != self.path or self.prepend is None:
            return data
        else:
            return self.prepend.encode() + b"\n" + data


class RepoLoader(_PrependFileLoader):
    """Loads a Python module associated with a package in specific repository"""

    #: Code in ``_package_prepend`` is prepended to imported packages.
    #:
    #: Spack packages are expected to call `from spack.package import *`
    #: themselves, but we are allowing a deprecation period before breaking
    #: external repos that don't do this yet.
    _package_prepend = "from spack.package import *"

    def __init__(self, fullname, repo, package_name):
        self.repo = repo
        self.package_name = package_name
        self.package_py = repo.filename_for_package_name(package_name)
        self.fullname = fullname
        super().__init__(self.fullname, self.package_py, prepend=self._package_prepend)


class SpackNamespaceLoader:
    def create_module(self, spec):
        return SpackNamespace(spec.name)

    def exec_module(self, module):
        module.__loader__ = self


class ReposFinder:
    """MetaPathFinder class that loads a Python module corresponding to a Spack package

    Return a loader based on the inspection of the current global repository list.
    """

    def find_spec(self, fullname, python_path, target=None):
        # "target" is not None only when calling importlib.reload()
        if target is not None:
            raise RuntimeError('cannot reload module "{0}"'.format(fullname))

        # Preferred API from https://peps.python.org/pep-0451/
        if not fullname.startswith(ROOT_PYTHON_NAMESPACE):
            return None

        loader = self.compute_loader(fullname)
        if loader is None:
            return None
        return importlib.util.spec_from_loader(fullname, loader)

    def compute_loader(self, fullname):
        # namespaces are added to repo, and package modules are leaves.
        namespace, dot, module_name = fullname.rpartition(".")

        # If it's a module in some repo, or if it is the repo's
        # namespace, let the repo handle it.
        for repo in PATH.repos:
            # We are using the namespace of the repo and the repo contains the package
            if namespace == repo.full_namespace:
                # With 2 nested conditionals we can call "repo.real_name" only once
                package_name = repo.real_name(module_name)
                if package_name:
                    return RepoLoader(fullname, repo, package_name)

            # We are importing a full namespace like 'spack.pkg.builtin'
            if fullname == repo.full_namespace:
                return SpackNamespaceLoader()

        # No repo provides the namespace, but it is a valid prefix of
        # something in the RepoPath.
        if PATH.by_namespace.is_prefix(fullname):
            return SpackNamespaceLoader()

        return None


#
# These names describe how repos should be laid out in the filesystem.
#
repo_config_name = "repo.yaml"  # Top-level filename for repo config.
repo_index_name = "index.yaml"  # Top-level filename for repository index.
packages_dir_name = "packages"  # Top-level repo directory containing pkgs.
package_file_name = "package.py"  # Filename for packages in a repository.

#: Guaranteed unused default value for some functions.
NOT_PROVIDED = object()


def packages_path():
    """Get the test repo if it is active, otherwise the builtin repo."""
    try:
        return spack.repo.PATH.get_repo("builtin.mock").packages_path
    except spack.repo.UnknownNamespaceError:
        return spack.repo.PATH.get_repo("builtin").packages_path


class GitExe:
    # Wrapper around Executable for git to set working directory for all
    # invocations.
    #
    # Not using -C as that is not supported for git < 1.8.5.
    def __init__(self):
        self._git_cmd = spack.util.git.git(required=True)

    def __call__(self, *args, **kwargs):
        with working_dir(packages_path()):
            return self._git_cmd(*args, **kwargs)


def list_packages(rev):
    """List all packages associated with the given revision"""
    git = GitExe()

    # git ls-tree does not support ... merge-base syntax, so do it manually
    if rev.endswith("..."):
        ref = rev.replace("...", "")
        rev = git("merge-base", ref, "HEAD", output=str).strip()

    output = git("ls-tree", "-r", "--name-only", rev, output=str)

    # recursively list the packages directory
    package_paths = [
        line.split(os.sep) for line in output.split("\n") if line.endswith("package.py")
    ]

    # take the directory names with one-level-deep package files
    package_names = sorted(set([line[0] for line in package_paths if len(line) == 2]))

    return package_names


def diff_packages(rev1, rev2):
    """Compute packages lists for the two revisions and return a tuple
    containing all the packages in rev1 but not in rev2 and all the
    packages in rev2 but not in rev1."""
    p1 = set(list_packages(rev1))
    p2 = set(list_packages(rev2))
    return p1.difference(p2), p2.difference(p1)


def get_all_package_diffs(type, rev1="HEAD^1", rev2="HEAD"):
    """Show packages changed, added, or removed (or any combination of those)
       since a commit.

    Arguments:

        type (str): String containing one or more of 'A', 'B', 'C'
        rev1 (str): Revision to compare against, default is 'HEAD^'
        rev2 (str): Revision to compare to rev1, default is 'HEAD'

    Returns:

        A set contain names of affected packages.
    """
    lower_type = type.lower()
    if not re.match("^[arc]*$", lower_type):
        tty.die(
            "Invald change type: '%s'." % type,
            "Can contain only A (added), R (removed), or C (changed)",
        )

    removed, added = diff_packages(rev1, rev2)

    git = GitExe()
    out = git("diff", "--relative", "--name-only", rev1, rev2, output=str).strip()

    lines = [] if not out else re.split(r"\s+", out)
    changed = set()
    for path in lines:
        pkg_name, _, _ = path.partition(os.sep)
        if pkg_name not in added and pkg_name not in removed:
            changed.add(pkg_name)

    packages = set()
    if "a" in lower_type:
        packages |= added
    if "r" in lower_type:
        packages |= removed
    if "c" in lower_type:
        packages |= changed

    return packages


def add_package_to_git_stage(packages):
    """add a package to the git stage with `git add`"""
    git = GitExe()

    for pkg_name in packages:
        filename = spack.repo.PATH.filename_for_package_name(pkg_name)
        if not os.path.isfile(filename):
            tty.die("No such package: %s.  Path does not exist:" % pkg_name, filename)

        git("add", filename)


def autospec(function):
    """Decorator that automatically converts the first argument of a
    function to a Spec.
    """

    @functools.wraps(function)
    def converter(self, spec_like, *args, **kwargs):
        if not isinstance(spec_like, spack.spec.Spec):
            spec_like = spack.spec.Spec(spec_like)
        return function(self, spec_like, *args, **kwargs)

    return converter


def is_package_file(filename):
    """Determine whether we are in a package file from a repo."""
    # Package files are named `package.py` and are not in lib/spack/spack
    # We have to remove the file extension because it can be .py and can be
    # .pyc depending on context, and can differ between the files
    import spack.package_base  # break cycle

    filename_noext = os.path.splitext(filename)[0]
    packagebase_filename_noext = os.path.splitext(inspect.getfile(spack.package_base.PackageBase))[
        0
    ]
    return (
        filename_noext != packagebase_filename_noext
        and os.path.basename(filename_noext) == "package"
    )


class SpackNamespace(types.ModuleType):
    """Allow lazy loading of modules."""

    def __init__(self, namespace):
        super().__init__(namespace)
        self.__file__ = "(spack namespace)"
        self.__path__ = []
        self.__name__ = namespace
        self.__package__ = namespace
        self.__modules = {}

    def __getattr__(self, name):
        """Getattr lazily loads modules if they're not already loaded."""
        submodule = self.__package__ + "." + name
        try:
            setattr(self, name, __import__(submodule))
        except ImportError:
            msg = "'{0}' object has no attribute {1}"
            raise AttributeError(msg.format(type(self), name))
        return getattr(self, name)


class FastPackageChecker(collections.abc.Mapping):
    """Cache that maps package names to the stats obtained on the
    'package.py' files associated with them.

    For each repository a cache is maintained at class level, and shared among
    all instances referring to it. Update of the global cache is done lazily
    during instance initialization.
    """

    #: Global cache, reused by every instance
    _paths_cache: Dict[str, Dict[str, os.stat_result]] = {}

    def __init__(self, packages_path):
        # The path of the repository managed by this instance
        self.packages_path = packages_path

        # If the cache we need is not there yet, then build it appropriately
        if packages_path not in self._paths_cache:
            self._paths_cache[packages_path] = self._create_new_cache()

        #: Reference to the appropriate entry in the global cache
        self._packages_to_stats = self._paths_cache[packages_path]

    def invalidate(self):
        """Regenerate cache for this checker."""
        self._paths_cache[self.packages_path] = self._create_new_cache()
        self._packages_to_stats = self._paths_cache[self.packages_path]

    def _create_new_cache(self) -> Dict[str, os.stat_result]:
        """Create a new cache for packages in a repo.

        The implementation here should try to minimize filesystem
        calls.  At the moment, it is O(number of packages) and makes
        about one stat call per package.  This is reasonably fast, and
        avoids actually importing packages in Spack, which is slow.
        """
        # Create a dictionary that will store the mapping between a
        # package name and its stat info
        cache: Dict[str, os.stat_result] = {}
        for pkg_name in os.listdir(self.packages_path):
            # Skip non-directories in the package root.
            pkg_dir = os.path.join(self.packages_path, pkg_name)

            # Warn about invalid names that look like packages.
            if not nm.valid_module_name(pkg_name):
                if not pkg_name.startswith(".") and pkg_name != "repo.yaml":
                    tty.warn(
                        'Skipping package at {0}. "{1}" is not '
                        "a valid Spack module name.".format(pkg_dir, pkg_name)
                    )
                continue

            # Construct the file name from the directory
            pkg_file = os.path.join(self.packages_path, pkg_name, package_file_name)

            # Use stat here to avoid lots of calls to the filesystem.
            try:
                sinfo = os.stat(pkg_file)
            except OSError as e:
                if e.errno == errno.ENOENT:
                    # No package.py file here.
                    continue
                elif e.errno == errno.EACCES:
                    tty.warn("Can't read package file %s." % pkg_file)
                    continue
                raise e

            # If it's not a file, skip it.
            if stat.S_ISDIR(sinfo.st_mode):
                continue

            # If it is a file, then save the stats under the
            # appropriate key
            cache[pkg_name] = sinfo

        return cache

    def last_mtime(self):
        return max(sinfo.st_mtime for sinfo in self._packages_to_stats.values())

    def modified_since(self, since: float) -> List[str]:
        return [name for name, sinfo in self._packages_to_stats.items() if sinfo.st_mtime > since]

    def __getitem__(self, item):
        return self._packages_to_stats[item]

    def __iter__(self):
        return iter(self._packages_to_stats)

    def __len__(self):
        return len(self._packages_to_stats)


class Indexer(metaclass=abc.ABCMeta):
    """Adaptor for indexes that need to be generated when repos are updated."""

    def __init__(self, repository):
        self.repository = repository
        self.index = None

    def create(self):
        self.index = self._create()

    @abc.abstractmethod
    def _create(self):
        """Create an empty index and return it."""

    def needs_update(self, pkg):
        """Whether an update is needed when the package file hasn't changed.

        Returns:
            (bool): ``True`` if this package needs its index
                updated, ``False`` otherwise.

        We already automatically update indexes when package files
        change, but other files (like patches) may change underneath the
        package file. This method can be used to check additional
        package-specific files whenever they're loaded, to tell the
        RepoIndex to update the index *just* for that package.

        """
        return False

    @abc.abstractmethod
    def read(self, stream):
        """Read this index from a provided file object."""

    @abc.abstractmethod
    def update(self, pkg_fullname):
        """Update the index in memory with information about a package."""

    @abc.abstractmethod
    def write(self, stream):
        """Write the index to a file object."""


class TagIndexer(Indexer):
    """Lifecycle methods for a TagIndex on a Repo."""

    def _create(self):
        return spack.tag.TagIndex(self.repository)

    def read(self, stream):
        self.index = spack.tag.TagIndex.from_json(stream, self.repository)

    def update(self, pkg_fullname):
        self.index.update_package(pkg_fullname)

    def write(self, stream):
        self.index.to_json(stream)


class ProviderIndexer(Indexer):
    """Lifecycle methods for virtual package providers."""

    def _create(self):
        return spack.provider_index.ProviderIndex(repository=self.repository)

    def read(self, stream):
        self.index = spack.provider_index.ProviderIndex.from_json(stream, self.repository)

    def update(self, pkg_fullname):
        name = pkg_fullname.split(".")[-1]
        is_virtual = (
            not self.repository.exists(name) or self.repository.get_pkg_class(name).virtual
        )
        if is_virtual:
            return
        self.index.remove_provider(pkg_fullname)
        self.index.update(pkg_fullname)

    def write(self, stream):
        self.index.to_json(stream)


class PatchIndexer(Indexer):
    """Lifecycle methods for patch cache."""

    def _create(self):
        return spack.patch.PatchCache(repository=self.repository)

    def needs_update(self):
        # TODO: patches can change under a package and we should handle
        # TODO: it, but we currently punt. This should be refactored to
        # TODO: check whether patches changed each time a package loads,
        # TODO: tell the RepoIndex to reindex them.
        return False

    def read(self, stream):
        self.index = spack.patch.PatchCache.from_json(stream, repository=self.repository)

    def write(self, stream):
        self.index.to_json(stream)

    def update(self, pkg_fullname):
        self.index.update_package(pkg_fullname)


class RepoIndex:
    """Container class that manages a set of Indexers for a Repo.

    This class is responsible for checking packages in a repository for
    updates (using ``FastPackageChecker``) and for regenerating indexes
    when they're needed.

    ``Indexers`` should be added to the ``RepoIndex`` using
    ``add_indexer(name, indexer)``, and they should support the interface
    defined by ``Indexer``, so that the ``RepoIndex`` can read, generate,
    and update stored indices.

    Generated indexes are accessed by name via ``__getitem__()``."""

    def __init__(
        self,
        package_checker: FastPackageChecker,
        namespace: str,
        cache: spack.util.file_cache.FileCache,
    ):
        self.checker = package_checker
        self.packages_path = self.checker.packages_path
        if sys.platform == "win32":
            self.packages_path = llnl.path.convert_to_posix_path(self.packages_path)
        self.namespace = namespace

        self.indexers: Dict[str, Indexer] = {}
        self.indexes: Dict[str, Any] = {}
        self.cache = cache

    def add_indexer(self, name: str, indexer: Indexer):
        """Add an indexer to the repo index.

        Arguments:
            name: name of this indexer
            indexer: object implementing the ``Indexer`` interface"""
        self.indexers[name] = indexer

    def __getitem__(self, name):
        """Get the index with the specified name, reindexing if needed."""
        indexer = self.indexers.get(name)
        if not indexer:
            raise KeyError("no such index: %s" % name)

        if name not in self.indexes:
            self._build_all_indexes()

        return self.indexes[name]

    def _build_all_indexes(self):
        """Build all the indexes at once.

        We regenerate *all* indexes whenever *any* index needs an update,
        because the main bottleneck here is loading all the packages.  It
        can take tens of seconds to regenerate sequentially, and we'd
        rather only pay that cost once rather than on several
        invocations."""
        for name, indexer in self.indexers.items():
            self.indexes[name] = self._build_index(name, indexer)

    def _build_index(self, name: str, indexer: Indexer):
        """Determine which packages need an update, and update indexes."""

        # Filename of the provider index cache (we assume they're all json)
        cache_filename = f"{name}/{self.namespace}-index.json"

        # Compute which packages needs to be updated in the cache
        index_mtime = self.cache.mtime(cache_filename)
        needs_update = self.checker.modified_since(index_mtime)

        index_existed = self.cache.init_entry(cache_filename)
        if index_existed and not needs_update:
            # If the index exists and doesn't need an update, read it
            with self.cache.read_transaction(cache_filename) as f:
                indexer.read(f)

        else:
            # Otherwise update it and rewrite the cache file
            with self.cache.write_transaction(cache_filename) as (old, new):
                indexer.read(old) if old else indexer.create()

                # Compute which packages needs to be updated **again** in case someone updated them
                # while we waited for the lock
                new_index_mtime = self.cache.mtime(cache_filename)
                if new_index_mtime != index_mtime:
                    needs_update = self.checker.modified_since(new_index_mtime)

                for pkg_name in needs_update:
                    indexer.update(f"{self.namespace}.{pkg_name}")

                indexer.write(new)

        return indexer.index


class RepoPath:
    """A RepoPath is a list of repos that function as one.

    It functions exactly like a Repo, but it operates on the combined
    results of the Repos in its list instead of on a single package
    repository.

    Args:
        repos (list): list Repo objects or paths to put in this RepoPath
    """

    def __init__(self, *repos, **kwargs):
        cache = kwargs.get("cache", spack.caches.MISC_CACHE)
        self.repos = []
        self.by_namespace = nm.NamespaceTrie()

        self._provider_index = None
        self._patch_index = None
        self._tag_index = None

        # Add each repo to this path.
        for repo in repos:
            try:
                if isinstance(repo, str):
                    repo = Repo(repo, cache=cache)
                self.put_last(repo)
            except RepoError as e:
                tty.warn(
                    "Failed to initialize repository: '%s'." % repo,
                    e.message,
                    "To remove the bad repository, run this command:",
                    "    spack repo rm %s" % repo,
                )

    def put_first(self, repo):
        """Add repo first in the search path."""
        if isinstance(repo, RepoPath):
            for r in reversed(repo.repos):
                self.put_first(r)
            return

        self.repos.insert(0, repo)
        self.by_namespace[repo.full_namespace] = repo

    def put_last(self, repo):
        """Add repo last in the search path."""
        if isinstance(repo, RepoPath):
            for r in repo.repos:
                self.put_last(r)
            return

        self.repos.append(repo)

        # don't mask any higher-precedence repos with same namespace
        if repo.full_namespace not in self.by_namespace:
            self.by_namespace[repo.full_namespace] = repo

    def remove(self, repo):
        """Remove a repo from the search path."""
        if repo in self.repos:
            self.repos.remove(repo)

    def get_repo(self, namespace, default=NOT_PROVIDED):
        """Get a repository by namespace.

        Arguments:

            namespace:

                Look up this namespace in the RepoPath, and return it if found.

        Optional Arguments:

            default:

                If default is provided, return it when the namespace
                isn't found.  If not, raise an UnknownNamespaceError.
        """
        full_namespace = python_package_for_repo(namespace)
        if full_namespace not in self.by_namespace:
            if default == NOT_PROVIDED:
                raise UnknownNamespaceError(namespace)
            return default
        return self.by_namespace[full_namespace]

    def first_repo(self):
        """Get the first repo in precedence order."""
        return self.repos[0] if self.repos else None

    @llnl.util.lang.memoized
    def _all_package_names(self, include_virtuals):
        """Return all unique package names in all repositories."""
        all_pkgs = set()
        for repo in self.repos:
            for name in repo.all_package_names(include_virtuals):
                all_pkgs.add(name)
        return sorted(all_pkgs, key=lambda n: n.lower())

    def all_package_names(self, include_virtuals=False):
        return self._all_package_names(include_virtuals)

    def package_path(self, name):
        """Get path to package.py file for this repo."""
        return self.repo_for_pkg(name).package_path(name)

    def all_package_paths(self):
        for name in self.all_package_names():
            yield self.package_path(name)

    def packages_with_tags(self, *tags, full=False):
        """Returns a list of packages matching any of the tags in input.

        Args:
            full: if True the package names in the output are fully-qualified
        """
        r = set()
        for repo in self.repos:
            current = repo.packages_with_tags(*tags)
            if full:
                current = [f"{repo.namespace}.{x}" for x in current]
            r |= set(current)
        return sorted(r)

    def all_package_classes(self):
        for name in self.all_package_names():
            yield self.get_pkg_class(name)

    @property
    def provider_index(self):
        """Merged ProviderIndex from all Repos in the RepoPath."""
        if self._provider_index is None:
            self._provider_index = spack.provider_index.ProviderIndex(repository=self)
            for repo in reversed(self.repos):
                self._provider_index.merge(repo.provider_index)

        return self._provider_index

    @property
    def tag_index(self):
        """Merged TagIndex from all Repos in the RepoPath."""
        if self._tag_index is None:
            self._tag_index = spack.tag.TagIndex(repository=self)
            for repo in reversed(self.repos):
                self._tag_index.merge(repo.tag_index)

        return self._tag_index

    @property
    def patch_index(self):
        """Merged PatchIndex from all Repos in the RepoPath."""
        if self._patch_index is None:
            self._patch_index = spack.patch.PatchCache(repository=self)
            for repo in reversed(self.repos):
                self._patch_index.update(repo.patch_index)

        return self._patch_index

    @autospec
    def providers_for(self, vpkg_spec):
        providers = self.provider_index.providers_for(vpkg_spec)
        if not providers:
            raise UnknownPackageError(vpkg_spec.fullname)
        return providers

    @autospec
    def extensions_for(self, extendee_spec):
        return [
            pkg_cls(spack.spec.Spec(pkg_cls.name))
            for pkg_cls in self.all_package_classes()
            if pkg_cls(spack.spec.Spec(pkg_cls.name)).extends(extendee_spec)
        ]

    def last_mtime(self):
        """Time a package file in this repo was last updated."""
        return max(repo.last_mtime() for repo in self.repos)

    def repo_for_pkg(self, spec):
        """Given a spec, get the repository for its package."""
        # We don't @_autospec this function b/c it's called very frequently
        # and we want to avoid parsing str's into Specs unnecessarily.
        if isinstance(spec, spack.spec.Spec):
            namespace = spec.namespace
            name = spec.name
        else:
            # handle strings directly for speed instead of @_autospec'ing
            namespace, _, name = spec.rpartition(".")

        # If the spec already has a namespace, then return the
        # corresponding repo if we know about it.
        if namespace:
            fullspace = python_package_for_repo(namespace)
            if fullspace not in self.by_namespace:
                raise UnknownNamespaceError(namespace, name=name)
            return self.by_namespace[fullspace]

        # If there's no namespace, search in the RepoPath.
        for repo in self.repos:
            if name in repo:
                return repo

        # If the package isn't in any repo, return the one with
        # highest precedence.  This is for commands like `spack edit`
        # that can operate on packages that don't exist yet.
        return self.first_repo()

    def get(self, spec):
        """Returns the package associated with the supplied spec."""
        msg = "RepoPath.get can only be called on concrete specs"
        assert isinstance(spec, spack.spec.Spec) and spec.concrete, msg
        return self.repo_for_pkg(spec).get(spec)

    def get_pkg_class(self, pkg_name):
        """Find a class for the spec's package and return the class object."""
        return self.repo_for_pkg(pkg_name).get_pkg_class(pkg_name)

    @autospec
    def dump_provenance(self, spec, path):
        """Dump provenance information for a spec to a particular path.

        This dumps the package file and any associated patch files.
        Raises UnknownPackageError if not found.
        """
        return self.repo_for_pkg(spec).dump_provenance(spec, path)

    def dirname_for_package_name(self, pkg_name):
        return self.repo_for_pkg(pkg_name).dirname_for_package_name(pkg_name)

    def filename_for_package_name(self, pkg_name):
        return self.repo_for_pkg(pkg_name).filename_for_package_name(pkg_name)

    def exists(self, pkg_name):
        """Whether package with the give name exists in the path's repos.

        Note that virtual packages do not "exist".
        """
        return any(repo.exists(pkg_name) for repo in self.repos)

    def _have_name(self, pkg_name):
        have_name = pkg_name is not None
        if have_name and not isinstance(pkg_name, str):
            raise ValueError("is_virtual(): expected package name, got %s" % type(pkg_name))
        return have_name

    def is_virtual(self, pkg_name):
        """Return True if the package with this name is virtual, False otherwise.

        This function use the provider index. If calling from a code block that
        is used to construct the provider index use the ``is_virtual_safe`` function.

        Args:
            pkg_name (str): name of the package we want to check
        """
        have_name = self._have_name(pkg_name)
        return have_name and pkg_name in self.provider_index

    def is_virtual_safe(self, pkg_name):
        """Return True if the package with this name is virtual, False otherwise.

        This function doesn't use the provider index.

        Args:
            pkg_name (str): name of the package we want to check
        """
        have_name = self._have_name(pkg_name)
        return have_name and (not self.exists(pkg_name) or self.get_pkg_class(pkg_name).virtual)

    def __contains__(self, pkg_name):
        return self.exists(pkg_name)


class Repo:
    """Class representing a package repository in the filesystem.

    Each package repository must have a top-level configuration file
    called `repo.yaml`.

    Currently, `repo.yaml` this must define:

    `namespace`:
        A Python namespace where the repository's packages should live.

    """

    def __init__(self, root, cache=None):
        """Instantiate a package repository from a filesystem path.

        Args:
            root: the root directory of the repository
        """
        # Root directory, containing _repo.yaml and package dirs
        # Allow roots to by spack-relative by starting with '$spack'
        self.root = spack.util.path.canonicalize_path(root)

        # check and raise BadRepoError on fail.
        def check(condition, msg):
            if not condition:
                raise BadRepoError(msg)

        # Validate repository layout.
        self.config_file = os.path.join(self.root, repo_config_name)
        check(os.path.isfile(self.config_file), "No %s found in '%s'" % (repo_config_name, root))

        # Read configuration and validate namespace
        config = self._read_config()
        check(
            "namespace" in config,
            "%s must define a namespace." % os.path.join(root, repo_config_name),
        )

        self.namespace = config["namespace"]
        check(
            re.match(r"[a-zA-Z][a-zA-Z0-9_.]+", self.namespace),
            ("Invalid namespace '%s' in repo '%s'. " % (self.namespace, self.root))
            + "Namespaces must be valid python identifiers separated by '.'",
        )

        # Set up 'full_namespace' to include the super-namespace
        self.full_namespace = python_package_for_repo(self.namespace)

        # Keep name components around for checking prefixes.
        self._names = self.full_namespace.split(".")

        packages_dir = config.get("subdirectory", packages_dir_name)
        self.packages_path = os.path.join(self.root, packages_dir)
        check(
            os.path.isdir(self.packages_path),
            "No directory '%s' found in '%s'" % (packages_dir, root),
        )

        # These are internal cache variables.
        self._modules = {}
        self._classes = {}
        self._instances = {}

        # Maps that goes from package name to corresponding file stat
        self._fast_package_checker = None

        # Indexes for this repository, computed lazily
        self._repo_index = None
        self._cache = cache or spack.caches.MISC_CACHE

    def real_name(self, import_name):
        """Allow users to import Spack packages using Python identifiers.

        A python identifier might map to many different Spack package
        names due to hyphen/underscore ambiguity.

        Easy example:
            num3proxy   -> 3proxy

        Ambiguous:
            foo_bar -> foo_bar, foo-bar

        More ambiguous:
            foo_bar_baz -> foo_bar_baz, foo-bar-baz, foo_bar-baz, foo-bar_baz
        """
        if import_name in self:
            return import_name

        options = nm.possible_spack_module_names(import_name)
        options.remove(import_name)
        for name in options:
            if name in self:
                return name
        return None

    def is_prefix(self, fullname):
        """True if fullname is a prefix of this Repo's namespace."""
        parts = fullname.split(".")
        return self._names[: len(parts)] == parts

    def _read_config(self):
        """Check for a YAML config file in this db's root directory."""
        try:
            with open(self.config_file) as reponame_file:
                yaml_data = syaml.load(reponame_file)

                if (
                    not yaml_data
                    or "repo" not in yaml_data
                    or not isinstance(yaml_data["repo"], dict)
                ):
                    tty.die("Invalid %s in repository %s" % (repo_config_name, self.root))

                return yaml_data["repo"]

        except IOError:
            tty.die("Error reading %s when opening %s" % (self.config_file, self.root))

    def get(self, spec):
        """Returns the package associated with the supplied spec."""
        msg = "Repo.get can only be called on concrete specs"
        assert isinstance(spec, spack.spec.Spec) and spec.concrete, msg
        # NOTE: we only check whether the package is None here, not whether it
        # actually exists, because we have to load it anyway, and that ends up
        # checking for existence. We avoid constructing FastPackageChecker,
        # which will stat all packages.
        if spec.name is None:
            raise UnknownPackageError(None, self)

        if spec.namespace and spec.namespace != self.namespace:
            raise UnknownPackageError(spec.name, self.namespace)

        package_class = self.get_pkg_class(spec.name)
        try:
            return package_class(spec)
        except spack.error.SpackError:
            # pass these through as their error messages will be fine.
            raise
        except Exception as e:
            tty.debug(e)

            # Make sure other errors in constructors hit the error
            # handler by wrapping them
            if spack.config.get("config:debug"):
                sys.excepthook(*sys.exc_info())
            raise FailedConstructorError(spec.fullname, *sys.exc_info())

    @autospec
    def dump_provenance(self, spec, path):
        """Dump provenance information for a spec to a particular path.

        This dumps the package file and any associated patch files.
        Raises UnknownPackageError if not found.
        """
        if spec.namespace and spec.namespace != self.namespace:
            raise UnknownPackageError(
                "Repository %s does not contain package %s." % (self.namespace, spec.fullname)
            )

        package_path = self.filename_for_package_name(spec.name)
        if not os.path.exists(package_path):
            # Spec has no files (e.g., package, patches) to copy
            tty.debug(f"{spec.name} does not have a package to dump")
            return

        # Install patch files needed by the (concrete) package.
        fs.mkdirp(path)
        if spec.concrete:
            for patch in itertools.chain.from_iterable(spec.package.patches.values()):
                if patch.path:
                    if os.path.exists(patch.path):
                        fs.install(patch.path, path)
                    else:
                        tty.warn("Patch file did not exist: %s" % patch.path)

        # Install the package.py file itself.
        fs.install(self.filename_for_package_name(spec.name), path)

    def purge(self):
        """Clear entire package instance cache."""
        self._instances.clear()

    @property
    def index(self):
        """Construct the index for this repo lazily."""
        if self._repo_index is None:
            self._repo_index = RepoIndex(self._pkg_checker, self.namespace, cache=self._cache)
            self._repo_index.add_indexer("providers", ProviderIndexer(self))
            self._repo_index.add_indexer("tags", TagIndexer(self))
            self._repo_index.add_indexer("patches", PatchIndexer(self))
        return self._repo_index

    @property
    def provider_index(self):
        """A provider index with names *specific* to this repo."""
        return self.index["providers"]

    @property
    def tag_index(self):
        """Index of tags and which packages they're defined on."""
        return self.index["tags"]

    @property
    def patch_index(self):
        """Index of patches and packages they're defined on."""
        return self.index["patches"]

    @autospec
    def providers_for(self, vpkg_spec):
        providers = self.provider_index.providers_for(vpkg_spec)
        if not providers:
            raise UnknownPackageError(vpkg_spec.fullname)
        return providers

    @autospec
    def extensions_for(self, extendee_spec):
        return [
            pkg_cls(spack.spec.Spec(pkg_cls.name))
            for pkg_cls in self.all_package_classes()
            if pkg_cls(spack.spec.Spec(pkg_cls.name)).extends(extendee_spec)
        ]

    def dirname_for_package_name(self, pkg_name):
        """Get the directory name for a particular package.  This is the
        directory that contains its package.py file."""
        _, unqualified_name = self.partition_package_name(pkg_name)
        return os.path.join(self.packages_path, unqualified_name)

    def filename_for_package_name(self, pkg_name):
        """Get the filename for the module we should load for a particular
        package.  Packages for a Repo live in
        ``$root/<package_name>/package.py``

        This will return a proper package.py path even if the
        package doesn't exist yet, so callers will need to ensure
        the package exists before importing.
        """
        pkg_dir = self.dirname_for_package_name(pkg_name)
        return os.path.join(pkg_dir, package_file_name)

    @property
    def _pkg_checker(self):
        if self._fast_package_checker is None:
            self._fast_package_checker = FastPackageChecker(self.packages_path)
        return self._fast_package_checker

    def all_package_names(self, include_virtuals=False):
        """Returns a sorted list of all package names in the Repo."""
        names = sorted(self._pkg_checker.keys())
        if include_virtuals:
            return names
        return [x for x in names if not self.is_virtual(x)]

    def package_path(self, name):
        """Get path to package.py file for this repo."""
        return os.path.join(self.packages_path, name, package_file_name)

    def all_package_paths(self):
        for name in self.all_package_names():
            yield self.package_path(name)

    def packages_with_tags(self, *tags):
        v = set(self.all_package_names())
        index = self.tag_index

        for t in tags:
            t = t.lower()
            v &= set(index[t])

        return sorted(v)

    def all_package_classes(self):
        """Iterator over all package *classes* in the repository.

        Use this with care, because loading packages is slow.
        """
        for name in self.all_package_names():
            yield self.get_pkg_class(name)

    def exists(self, pkg_name):
        """Whether a package with the supplied name exists."""
        if pkg_name is None:
            return False

        # if the FastPackageChecker is already constructed, use it
        if self._fast_package_checker:
            return pkg_name in self._pkg_checker

        # if not, check for the package.py file
        path = self.filename_for_package_name(pkg_name)
        return os.path.exists(path)

    def last_mtime(self):
        """Time a package file in this repo was last updated."""
        return self._pkg_checker.last_mtime()

    def is_virtual(self, pkg_name):
        """Return True if the package with this name is virtual, False otherwise.

        This function use the provider index. If calling from a code block that
        is used to construct the provider index use the ``is_virtual_safe`` function.

        Args:
            pkg_name (str): name of the package we want to check
        """
        return pkg_name in self.provider_index

    def is_virtual_safe(self, pkg_name):
        """Return True if the package with this name is virtual, False otherwise.

        This function doesn't use the provider index.

        Args:
            pkg_name (str): name of the package we want to check
        """
        return not self.exists(pkg_name) or self.get_pkg_class(pkg_name).virtual

    def get_pkg_class(self, pkg_name):
        """Get the class for the package out of its module.

        First loads (or fetches from cache) a module for the
        package. Then extracts the package class from the module
        according to Spack's naming convention.
        """
        namespace, pkg_name = self.partition_package_name(pkg_name)
        class_name = nm.mod_to_class(pkg_name)
        fullname = f"{self.full_namespace}.{pkg_name}"

        try:
            module = importlib.import_module(fullname)
        except ImportError:
            raise UnknownPackageError(fullname)
        except Exception as e:
            msg = f"cannot load package '{pkg_name}' from the '{self.namespace}' repository: {e}"
            raise RepoError(msg) from e

        cls = getattr(module, class_name)
        if not inspect.isclass(cls):
            tty.die(f"{pkg_name}.{class_name} is not a class")

        new_cfg_settings = (
            spack.config.get("packages").get(pkg_name, {}).get("package_attributes", {})
        )

        overridden_attrs = getattr(cls, "overridden_attrs", {})
        attrs_exclusively_from_config = getattr(cls, "attrs_exclusively_from_config", [])
        # Clear any prior changes to class attributes in case the config has
        # since changed
        for key, val in overridden_attrs.items():
            setattr(cls, key, val)
        for key in attrs_exclusively_from_config:
            delattr(cls, key)

        # Keep track of every class attribute that is overridden by the config:
        # if the config changes between calls to this method, we make sure to
        # restore the original config values (in case the new config no longer
        # sets attributes that it used to)
        new_overridden_attrs = {}
        new_attrs_exclusively_from_config = set()
        for key, val in new_cfg_settings.items():
            if hasattr(cls, key):
                new_overridden_attrs[key] = getattr(cls, key)
            else:
                new_attrs_exclusively_from_config.add(key)

            setattr(cls, key, val)
        if new_overridden_attrs:
            setattr(cls, "overridden_attrs", dict(new_overridden_attrs))
        elif hasattr(cls, "overridden_attrs"):
            delattr(cls, "overridden_attrs")
        if new_attrs_exclusively_from_config:
            setattr(cls, "attrs_exclusively_from_config", new_attrs_exclusively_from_config)
        elif hasattr(cls, "attrs_exclusively_from_config"):
            delattr(cls, "attrs_exclusively_from_config")

        return cls

    def partition_package_name(self, pkg_name: str) -> Tuple[str, str]:
        namespace, pkg_name = partition_package_name(pkg_name)
        if namespace and (namespace != self.namespace):
            raise InvalidNamespaceError(
                f"Invalid namespace for the '{self.namespace}' repo: {namespace}"
            )

        return namespace, pkg_name

    def __str__(self):
        return "[Repo '%s' at '%s']" % (self.namespace, self.root)

    def __repr__(self):
        return self.__str__()

    def __contains__(self, pkg_name):
        return self.exists(pkg_name)


RepoType = Union[Repo, RepoPath]


def partition_package_name(pkg_name: str) -> Tuple[str, str]:
    """Given a package name that might be fully-qualified, returns the namespace part,
    if present and the unqualified package name.

    If the package name is unqualified, the namespace is an empty string.

    Args:
        pkg_name: a package name, either unqualified like "llvl", or
            fully-qualified, like "builtin.llvm"
    """
    namespace, _, pkg_name = pkg_name.rpartition(".")
    return namespace, pkg_name


def create_repo(root, namespace=None, subdir=packages_dir_name):
    """Create a new repository in root with the specified namespace.

    If the namespace is not provided, use basename of root.
    Return the canonicalized path and namespace of the created repository.
    """
    root = spack.util.path.canonicalize_path(root)
    if not namespace:
        namespace = os.path.basename(root)

    if not re.match(r"\w[\.\w-]*", namespace):
        raise InvalidNamespaceError("'%s' is not a valid namespace." % namespace)

    existed = False
    if os.path.exists(root):
        if os.path.isfile(root):
            raise BadRepoError("File %s already exists and is not a directory" % root)
        elif os.path.isdir(root):
            if not os.access(root, os.R_OK | os.W_OK):
                raise BadRepoError("Cannot create new repo in %s: cannot access directory." % root)
            if os.listdir(root):
                raise BadRepoError("Cannot create new repo in %s: directory is not empty." % root)
        existed = True

    full_path = os.path.realpath(root)
    parent = os.path.dirname(full_path)
    if not os.access(parent, os.R_OK | os.W_OK):
        raise BadRepoError("Cannot create repository in %s: can't access parent!" % root)

    try:
        config_path = os.path.join(root, repo_config_name)
        packages_path = os.path.join(root, subdir)

        fs.mkdirp(packages_path)
        with open(config_path, "w") as config:
            config.write("repo:\n")
            config.write(f"  namespace: '{namespace}'\n")
            if subdir != packages_dir_name:
                config.write(f"  subdirectory: '{subdir}'\n")

    except (IOError, OSError) as e:
        # try to clean up.
        if existed:
            shutil.rmtree(config_path, ignore_errors=True)
            shutil.rmtree(packages_path, ignore_errors=True)
        else:
            shutil.rmtree(root, ignore_errors=True)

        raise BadRepoError(
            "Failed to create new repository in %s." % root, "Caused by %s: %s" % (type(e), e)
        )

    return full_path, namespace


def create_or_construct(path, namespace=None):
    """Create a repository, or just return a Repo if it already exists."""
    if not os.path.exists(path):
        fs.mkdirp(path)
        create_repo(path, namespace)
    return Repo(path)


def _path(configuration=None):
    """Get the singleton RepoPath instance for Spack."""
    configuration = configuration or spack.config.CONFIG
    return create(configuration=configuration)


def create(configuration):
    """Create a RepoPath from a configuration object.

    Args:
        configuration (spack.config.Configuration): configuration object
    """
    repo_dirs = configuration.get("repos")
    if not repo_dirs:
        raise NoRepoConfiguredError("Spack configuration contains no package repositories.")
    return RepoPath(*repo_dirs)


#: Singleton repo path instance
PATH: Union[RepoPath, llnl.util.lang.Singleton] = llnl.util.lang.Singleton(_path)

# Add the finder to sys.meta_path
REPOS_FINDER = ReposFinder()
sys.meta_path.append(REPOS_FINDER)


def all_package_names(include_virtuals=False):
    """Convenience wrapper around ``spack.repo.all_package_names()``."""
    return PATH.all_package_names(include_virtuals)


@contextlib.contextmanager
def use_repositories(*paths_and_repos, **kwargs):
    """Use the repositories passed as arguments within the context manager.

    Args:
        *paths_and_repos: paths to the repositories to be used, or
            already constructed Repo objects
        override (bool): if True use only the repositories passed as input,
            if False add them to the top of the list of current repositories.
    Returns:
        Corresponding RepoPath object
    """
    global PATH
    # TODO (Python 2.7): remove this kwargs on deprecation of Python 2.7 support
    override = kwargs.get("override", True)
    paths = [getattr(x, "root", x) for x in paths_and_repos]
    scope_name = "use-repo-{}".format(uuid.uuid4())
    repos_key = "repos:" if override else "repos"
    spack.config.CONFIG.push_scope(
        spack.config.InternalConfigScope(name=scope_name, data={repos_key: paths})
    )
    PATH, saved = create(configuration=spack.config.CONFIG), PATH
    try:
        yield PATH
    finally:
        spack.config.CONFIG.remove_scope(scope_name=scope_name)
        PATH = saved


class MockRepositoryBuilder:
    """Build a mock repository in a directory"""

    def __init__(self, root_directory, namespace=None):
        namespace = namespace or "".join(random.choice(string.ascii_uppercase) for _ in range(10))
        self.root, self.namespace = create_repo(str(root_directory), namespace)

    def add_package(self, name, dependencies=None):
        """Create a mock package in the repository, using a Jinja2 template.

        Args:
            name (str): name of the new package
            dependencies (list): list of ("dep_spec", "dep_type", "condition") tuples.
                Both "dep_type" and "condition" can default to ``None`` in which case
                ``spack.dependency.default_deptype`` and ``spack.spec.Spec()`` are used.
        """
        dependencies = dependencies or []
        context = {"cls_name": spack.util.naming.mod_to_class(name), "dependencies": dependencies}
        template = spack.tengine.make_environment().get_template("mock-repository/package.pyt")
        text = template.render(context)
        package_py = self.recipe_filename(name)
        fs.mkdirp(os.path.dirname(package_py))
        with open(package_py, "w") as f:
            f.write(text)

    def remove(self, name):
        package_py = self.recipe_filename(name)
        shutil.rmtree(os.path.dirname(package_py))

    def recipe_filename(self, name):
        return os.path.join(self.root, "packages", name, "package.py")


class RepoError(spack.error.SpackError):
    """Superclass for repository-related errors."""


class NoRepoConfiguredError(RepoError):
    """Raised when there are no repositories configured."""


class InvalidNamespaceError(RepoError):
    """Raised when an invalid namespace is encountered."""


class BadRepoError(RepoError):
    """Raised when repo layout is invalid."""


class UnknownEntityError(RepoError):
    """Raised when we encounter a package spack doesn't have."""


class UnknownPackageError(UnknownEntityError):
    """Raised when we encounter a package spack doesn't have."""

    def __init__(self, name, repo=None):
        msg = "Attempting to retrieve anonymous package."
        long_msg = None
        if name:
            if repo:
                msg = "Package '{0}' not found in repository '{1.root}'"
                msg = msg.format(name, repo)
            else:
                msg = "Package '{0}' not found.".format(name)

            # Special handling for specs that may have been intended as
            # filenames: prompt the user to ask whether they intended to write
            # './<name>'.
            if name.endswith(".yaml"):
                long_msg = "Did you mean to specify a filename with './{0}'?"
                long_msg = long_msg.format(name)
            else:
                long_msg = "Use 'spack create' to create a new package."

                if not repo:
                    repo = spack.repo.PATH

                # We need to compare the base package name
                pkg_name = name.rsplit(".", 1)[-1]
                similar = difflib.get_close_matches(pkg_name, repo.all_package_names())

                if 1 <= len(similar) <= 5:
                    long_msg += "\n\nDid you mean one of the following packages?\n  "
                    long_msg += "\n  ".join(similar)

        super().__init__(msg, long_msg)
        self.name = name


class UnknownNamespaceError(UnknownEntityError):
    """Raised when we encounter an unknown namespace"""

    def __init__(self, namespace, name=None):
        msg, long_msg = "Unknown namespace: {}".format(namespace), None
        if name == "yaml":
            long_msg = "Did you mean to specify a filename with './{}.{}'?"
            long_msg = long_msg.format(namespace, name)
        super().__init__(msg, long_msg)


class FailedConstructorError(RepoError):
    """Raised when a package's class constructor fails."""

    def __init__(self, name, exc_type, exc_obj, exc_tb):
        super().__init__(
            "Class constructor failed for package '%s'." % name,
            "\nCaused by:\n"
            + ("%s: %s\n" % (exc_type.__name__, exc_obj))
            + "".join(traceback.format_tb(exc_tb)),
        )
        self.name = name