-
Notifications
You must be signed in to change notification settings - Fork 31
/
repository.py
779 lines (662 loc) · 29.6 KB
/
repository.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
"""
Ebuild repository, specific to gentoo ebuild trees.
"""
__all__ = ("UnconfiguredTree", "ConfiguredTree", "ProvidesRepo", "tree")
from functools import partial, wraps
from itertools import chain, filterfalse
import locale
from operator import attrgetter
import os
import stat
from random import shuffle
from sys import intern
from snakeoil import chksum, klass
from snakeoil.bash import iter_read_bash, read_dict
from snakeoil.containers import InvertedContains
from snakeoil.data_source import local_source
from snakeoil.fileutils import readlines
from snakeoil.mappings import ImmutableDict
from snakeoil.obj import make_kls
from snakeoil.osutils import listdir_files, listdir_dirs, pjoin
from snakeoil.sequences import iflatten_instance, stable_unique
from snakeoil.strings import pluralism as _pl
from snakeoil.weakrefs import WeakValCache
from pkgcore import fetch
from pkgcore.config.hint import ConfigHint, configurable
from pkgcore.ebuild import (
cpv, digest, ebd, repo_objs, atom, restricts, processor,
ebuild_src, eclass_cache as eclass_cache_mod, errors as ebuild_errors,
)
from pkgcore.ebuild.eapi import get_eapi
from pkgcore.fs.livefs import sorted_scan
from pkgcore.log import logger
from pkgcore.operations import repo as _repo_ops
from pkgcore.package import errors as pkg_errors
from pkgcore.repository import prototype, errors, configured, util
from pkgcore.repository.virtual import RestrictionRepo
from pkgcore.restrictions import packages
from pkgcore.util.packages import groupby_pkg
class repo_operations(_repo_ops.operations):
def _cmd_implementation_digests(self, domain, matches, observer,
mirrors=False, force=False):
manifest_config = self.repo.config.manifests
if manifest_config.disabled:
observer.info(f"repo {self.repo.repo_id} has manifests disabled")
return
required_chksums = set(manifest_config.required_hashes)
write_chksums = manifest_config.hashes
distdir = domain.fetcher.distdir
ret = set()
for key_query in sorted(set(match.unversioned_atom for match in matches)):
pkgs = self.repo.match(key_query)
# check for pkgs masked by bad metadata
bad_metadata = self.repo._bad_masked.match(key_query)
if bad_metadata:
for pkg in bad_metadata:
e = pkg.data
error_str = f"{pkg.cpvstr}: {e.msg(verbosity=observer.verbosity)}"
observer.error(error_str)
ret.add(key_query)
continue
# Check for bad ebuilds -- mismatched or invalid PNs won't be
# matched by regular restrictions so they will otherwise be
# ignored.
ebuilds = {
x for x in listdir_files(pjoin(self.repo.location, str(key_query)))
if x.endswith('.ebuild')
}
unknown_ebuilds = ebuilds.difference(os.path.basename(x.path) for x in pkgs)
if unknown_ebuilds:
error_str = (
f"{key_query}: invalid ebuild{_pl(unknown_ebuilds)}: "
f"{', '.join(unknown_ebuilds)}"
)
observer.error(error_str)
ret.add(key_query)
continue
# empty package dir
if not pkgs:
continue
manifest = pkgs[0].manifest
# all pkgdir fetchables
pkgdir_fetchables = {}
for pkg in pkgs:
pkgdir_fetchables.update({
fetchable.filename: fetchable for fetchable in
iflatten_instance(pkg._get_attr['fetchables'](
pkg, allow_missing_checksums=True,
skip_default_mirrors=(not mirrors)),
fetch.fetchable)
})
# fetchables targeted for (re-)manifest generation
fetchables = {}
chksum_set = set(write_chksums)
for filename, fetchable in pkgdir_fetchables.items():
if force or not required_chksums.issubset(fetchable.chksums):
fetchable.chksums = {
k: v for k, v in fetchable.chksums.items() if k in chksum_set}
fetchables[filename] = fetchable
# Manifest files aren't necessary with thin manifests and no distfiles
if manifest_config.thin and not pkgdir_fetchables:
if os.path.exists(manifest.path):
try:
os.remove(manifest.path)
except EnvironmentError as e:
observer.error(
'failed removing old manifest: '
f'{key_query}::{self.repo.repo_id}: {e}')
ret.add(key_query)
continue
# Manifest file is current and not forcing a refresh
if not force and manifest.distfiles.keys() == pkgdir_fetchables.keys():
continue
pkg_ops = domain.pkg_operations(pkgs[0], observer=observer)
if not pkg_ops.supports("fetch"):
observer.error(f"pkg {pkg} doesn't support fetching, can't generate manifest")
ret.add(key_query)
continue
# fetch distfiles
if not pkg_ops.fetch(list(fetchables.values()), observer):
ret.add(key_query)
continue
# calculate checksums for fetched distfiles
try:
for fetchable in fetchables.values():
chksums = chksum.get_chksums(
pjoin(distdir, fetchable.filename), *write_chksums)
fetchable.chksums = dict(zip(write_chksums, chksums))
except chksum.MissingChksumHandler as e:
observer.error(f'failed generating chksum: {e}')
ret.add(key_query)
break
if key_query not in ret:
fetchables.update(pkgdir_fetchables)
observer.info(f"generating manifest: {key_query}::{self.repo.repo_id}")
manifest.update(sorted(fetchables.values()), chfs=write_chksums)
return ret
def _sort_eclasses(config, repo_config):
repo_path = repo_config.location
repo_id = repo_config.repo_id
masters = repo_config.masters
eclasses = []
default = config.get_default('repo_config')
if repo_config._missing_masters and default is not None:
# use default repo's eclasses for overlays with missing masters
location = default.location
else:
location = repo_path
if not masters:
eclasses = [location]
else:
repo_map = {
r.repo_id: r.location for r in
config.objects['repo_config'].values()}
eclasses = [repo_map[x] for x in masters]
# add the repo's eclass directories if it's not specified.
# do it in this fashion so that the repo's masters can actually interpose
# this repo's eclasses in between others.
# admittedly an odd thing to do, but it has some benefits
if repo_path not in eclasses:
eclasses.append(repo_path)
eclasses = [eclass_cache_mod.cache(pjoin(x, 'eclass'), location=location)
for x in eclasses]
if len(eclasses) == 1:
eclasses = eclasses[0]
else:
eclasses = list(reversed(eclasses))
eclasses = eclass_cache_mod.StackedCaches(
eclasses, location=location, eclassdir=location)
return eclasses
class ProvidesRepo(util.SimpleTree):
"""Fake, installed repo populated with entries from package.provided."""
class PkgProvidedParent:
def __init__(self, **kwds):
self.__dict__.update(kwds)
class PkgProvided(ebuild_src.base):
__slots__ = ('use',)
package_is_real = False
__inst_caching__ = True
@property
def keywords(self):
return InvertedContains(())
def __init__(self, *a, **kwds):
super().__init__(*a, **kwds)
object.__setattr__(self, "use", [])
object.__setattr__(self, "data", {"SLOT": "0"})
object.__setattr__(self, "eapi", get_eapi('0'))
def __init__(self, pkgs, repo_id='package.provided'):
d = {}
for pkg in pkgs:
d.setdefault(pkg.category, {}).setdefault(pkg.package, []).append(pkg.fullver)
intermediate_parent = self.PkgProvidedParent()
super().__init__(
d, pkg_klass=partial(self.PkgProvided, intermediate_parent),
livefs=True, frozen=True, repo_id=repo_id)
intermediate_parent._parent_repo = self
if not d:
self.match = self.itermatch = self._empty_provides_iterable
self.has_match = self._empty_provides_has_match
@staticmethod
def _empty_provides_iterable(*args, **kwds):
return iter(())
@staticmethod
def _empty_provides_has_match(*args, **kwds):
return False
@configurable(
typename='repo',
types={
'repo_config': 'ref:repo_config', 'cache': 'refs:cache',
'eclass_cache': 'ref:eclass_cache',
'default_mirrors': 'list',
'allow_missing_manifests': 'bool'},
requires_config='config')
def tree(config, repo_config, cache=(), eclass_cache=None,
default_mirrors=None, allow_missing_manifests=False):
"""Initialize an unconfigured ebuild repository."""
repo_id = repo_config.repo_id
repo_path = repo_config.location
if repo_config.masters is None:
# if it's None, that means it's not a standalone, and is PMS, or misconfigured.
# empty tuple means it's a standalone repository
default = config.get_default('repo_config')
if default is None:
raise errors.InitializationError(
f"repo {repo_id!r} at {repo_path!r} requires missing default repo")
configured_repos = tuple(r.repo_id for r in config.objects['repo_config'].values())
missing = set(repo_config.masters).difference(configured_repos)
if missing:
missing = ', '.join(map(repr, sorted(missing)))
raise errors.InitializationError(
f'repo {repo_id!r} at path {repo_path!r} has missing masters: {missing}')
try:
masters = tuple(config.objects['repo'][r] for r in repo_config.masters)
except RecursionError:
repo_id = repo_config.repo_id
masters = ', '.join(repo_config.masters)
raise errors.InitializationError(
f'{repo_id!r} repo has cyclic masters: {masters}')
if eclass_cache is None:
eclass_cache = _sort_eclasses(config, repo_config)
return UnconfiguredTree(
repo_config.location, eclass_cache=eclass_cache, masters=masters, cache=cache,
default_mirrors=default_mirrors,
allow_missing_manifests=allow_missing_manifests,
repo_config=repo_config)
class UnconfiguredTree(prototype.tree):
"""Raw implementation supporting standard ebuild tree.
Return packages don't have USE configuration bound to them.
"""
false_packages = frozenset(["CVS", ".svn"])
false_categories = frozenset([
"eclass", "profiles", "packages", "distfiles", "metadata",
"licenses", "scripts", "CVS", "local"])
configured = False
configurables = ("domain", "settings")
configure = None
package_factory = staticmethod(ebuild_src.generate_new_factory)
enable_gpg = False
extension = '.ebuild'
operations_kls = repo_operations
pkgcore_config_type = ConfigHint({
'location': 'str',
'eclass_cache': 'ref:eclass_cache',
'masters': 'refs:repo',
'cache': 'refs:cache',
'default_mirrors': 'list',
'allow_missing_manifests': 'bool',
'repo_config': 'ref:repo_config',
},
typename='repo')
def __init__(self, location, eclass_cache=None, masters=(), cache=(),
default_mirrors=None, allow_missing_manifests=False, repo_config=None):
"""
:param location: on disk location of the tree
:param cache: sequence of :obj:`pkgcore.cache.template.database` instances
to use for storing metadata
:param masters: repo masters this repo inherits from
:param eclass_cache: If not None, :obj:`pkgcore.ebuild.eclass_cache`
instance representing the eclasses available,
if None, generates the eclass_cache itself
:param default_mirrors: Either None, or sequence of mirrors to try
fetching from first, then falling back to other uri
"""
super().__init__()
self.base = self.location = location
try:
if not stat.S_ISDIR(os.stat(self.base).st_mode):
raise errors.InitializationError(f"base not a dir: {self.base}")
except OSError as e:
raise errors.InitializationError(f"lstat failed: {self.base}") from e
if repo_config is None:
repo_config = repo_objs.RepoConfig(location)
self.config = repo_config
# profiles dir is required by PMS
if not os.path.isdir(self.config.profiles_base):
raise errors.InvalidRepo(f'missing required profiles dir: {self.location!r}')
# verify we support the repo's EAPI
if not self.is_supported:
raise errors.UnsupportedRepo(self)
if eclass_cache is None:
eclass_cache = eclass_cache_mod.cache(
pjoin(self.location, 'eclass'), location=self.location)
self.eclass_cache = eclass_cache
self.masters = masters
self.trees = tuple(masters) + (self,)
self.licenses = repo_objs.Licenses(self.location)
self.profiles = self.config.profiles
if masters:
self.licenses = repo_objs.OverlayedLicenses(*self.trees)
self.profiles = repo_objs.OverlayedProfiles(*self.trees)
# use mirrors from masters if not defined in the repo
mirrors = dict(self.thirdpartymirrors)
for master in masters:
for k, v in master.mirrors.items():
if k not in mirrors:
mirrors[k] = v
if isinstance(cache, (tuple, list)):
cache = tuple(cache)
else:
cache = (cache,)
self.mirrors = mirrors
self.default_mirrors = default_mirrors
self.cache = cache
self._allow_missing_chksums = allow_missing_manifests
self.package_class = self.package_factory(
self, cache, self.eclass_cache, self.mirrors, self.default_mirrors)
self._shared_pkg_cache = WeakValCache()
self._bad_masked = RestrictionRepo(repo_id='bad_masked')
self.projects_xml = repo_objs.LocalProjectsXml(
pjoin(self.location, 'metadata', 'projects.xml'))
repo_id = klass.alias_attr("config.repo_id")
repo_name = klass.alias_attr("config.repo_name")
aliases = klass.alias_attr("config.aliases")
eapi = klass.alias_attr('config.eapi')
is_supported = klass.alias_attr('config.eapi.is_supported')
pkg_masks = klass.alias_attr('config.pkg_masks')
@klass.jit_attr
def known_arches(self):
"""Return all known arches for a repo (including masters)."""
return frozenset(chain.from_iterable(
r.config.known_arches for r in self.trees))
def path_restrict(self, path):
"""Return a restriction from a given path in a repo.
:param path: full or partial path to an ebuild
:return: a package restriction matching the given path if possible
:raises ValueError: if the repo doesn't contain the given path, the
path relates to a file that isn't an ebuild, or the ebuild isn't in the
proper directory layout
"""
if path not in self:
raise ValueError(f"{self.repo_id!r} repo doesn't contain: {path!r}")
if not path.startswith(os.sep) and os.path.exists(pjoin(self.location, path)):
path_chunks = path.split(os.path.sep)
else:
path = os.path.realpath(os.path.abspath(path))
relpath = path[len(os.path.realpath(self.location)):].strip('/')
path_chunks = relpath.split(os.path.sep)
if os.path.isfile(path):
if not path.endswith('.ebuild'):
raise ValueError(f"file is not an ebuild: {path!r}")
elif len(path_chunks) != 3:
# ebuild isn't in a category/PN directory
raise ValueError(
f"ebuild not in the correct directory layout: {path!r}")
restrictions = []
# add restrictions until path components run out
try:
restrictions.append(restricts.RepositoryDep(self.repo_id))
if path_chunks[0] in self.categories:
restrictions.append(restricts.CategoryDep(path_chunks[0]))
restrictions.append(restricts.PackageDep(path_chunks[1]))
base = cpv.VersionedCPV(f"{path_chunks[0]}/{os.path.splitext(path_chunks[2])[0]}")
restrictions.append(restricts.VersionMatch('=', base.version, rev=base.revision))
except IndexError:
pass
return packages.AndRestriction(*restrictions)
def __getitem__(self, cpv):
cpv_inst = self.package_class(*cpv)
if cpv_inst.fullver not in self.versions[(cpv_inst.category, cpv_inst.package)]:
raise KeyError(cpv)
return cpv_inst
def rebind(self, **kwds):
"""Generate a new tree instance with the same location using new keywords.
:param kwds: see __init__ for valid values
"""
o = self.__class__(self.location, **kwds)
o.categories = self.categories
o.packages = self.packages
o.versions = self.versions
return o
@klass.jit_attr
def thirdpartymirrors(self):
mirrors = {}
fp = pjoin(self.location, 'profiles', 'thirdpartymirrors')
try:
for k, v in read_dict(fp, splitter=None).items():
v = v.split()
# shuffle mirrors so the same ones aren't used every time
shuffle(v)
mirrors[k] = v
except FileNotFoundError:
pass
return ImmutableDict(mirrors)
@klass.jit_attr
def category_dirs(self):
try:
return frozenset(map(intern, filterfalse(
self.false_categories.__contains__,
(x for x in listdir_dirs(self.base) if not x.startswith('.')))))
except EnvironmentError as e:
logger.error(f"failed listing categories: {e}")
return ()
def _get_categories(self, *optional_category):
# why the auto return? current porttrees don't allow/support
# categories deeper then one dir.
if optional_category:
# raise KeyError
return ()
categories = frozenset(chain.from_iterable(repo.config.categories for repo in self.trees))
if categories:
return categories
return self.category_dirs
def _get_packages(self, category):
cpath = pjoin(self.base, category.lstrip(os.path.sep))
try:
return tuple(filterfalse(
self.false_packages.__contains__, listdir_dirs(cpath)))
except FileNotFoundError:
if category in self.categories:
# ignore it, since it's PMS mandated that it be allowed.
return ()
except EnvironmentError as e:
category = pjoin(self.base, category.lstrip(os.path.sep))
raise KeyError(
f'failed fetching packages for category {category}: {e}') from e
def _get_versions(self, catpkg):
"""Determine available versions for a given package.
Ebuilds with mismatched or invalid package names are ignored.
"""
cppath = pjoin(self.base, catpkg[0], catpkg[1])
pkg = f'{catpkg[-1]}-'
lp = len(pkg)
extension = self.extension
ext_len = -len(extension)
try:
return tuple(
x[lp:ext_len] for x in listdir_files(cppath)
if x[ext_len:] == extension and x[:lp] == pkg)
except EnvironmentError as e:
raise KeyError(
"failed fetching versions for package %s: %s" %
(pjoin(self.base, '/'.join(catpkg)), str(e))) from e
def _pkg_filter(self, raw, error_callback, pkgs):
"""Filter packages with bad metadata."""
while True:
try:
pkg = next(pkgs)
except pkg_errors.PackageError as e:
# ignore pkgs with invalid CPVs
continue
except StopIteration:
return
if raw:
yield pkg
elif self._bad_masked.has_match(pkg.versioned_atom) and error_callback is not None:
error_callback(self._bad_masked[pkg.versioned_atom])
else:
# check pkgs for unsupported/invalid EAPIs and bad metadata
try:
if not pkg.is_supported:
exc = pkg_errors.MetadataException(
pkg, 'eapi', f"EAPI '{pkg.eapi}' is not supported")
self._bad_masked[pkg.versioned_atom] = exc
if error_callback is not None:
error_callback(exc)
continue
# TODO: add a generic metadata validation method to avoid slow metadata checks?
pkg.data
pkg.slot
pkg.required_use
except pkg_errors.MetadataException as e:
self._bad_masked[e.pkg.versioned_atom] = e
if error_callback is not None:
error_callback(e)
continue
yield pkg
def itermatch(self, *args, **kwargs):
raw = 'raw_pkg_cls' in kwargs or not kwargs.get('versioned', True)
error_callback = kwargs.pop('error_callback', None)
kwargs.setdefault('pkg_filter', partial(self._pkg_filter, raw, error_callback))
return super().itermatch(*args, **kwargs)
def _get_ebuild_path(self, pkg):
return pjoin(
self.base, pkg.category, pkg.package,
f"{pkg.package}-{pkg.fullver}{self.extension}")
def _get_ebuild_src(self, pkg):
return local_source(self._get_ebuild_path(pkg), encoding='utf8')
def _get_shared_pkg_data(self, category, package):
key = (category, package)
o = self._shared_pkg_cache.get(key)
if o is None:
mxml = self._get_metadata_xml(category, package)
manifest = self._get_manifest(category, package)
o = repo_objs.SharedPkgData(mxml, manifest)
self._shared_pkg_cache[key] = o
return o
def _get_metadata_xml(self, category, package):
return repo_objs.LocalMetadataXml(pjoin(
self.base, category, package, "metadata.xml"))
def _get_manifest(self, category, package):
return digest.Manifest(pjoin(
self.base, category, package, "Manifest"),
thin=self.config.manifests.thin,
enforce_gpg=self.enable_gpg)
def _get_digests(self, pkg, allow_missing=False):
if self.config.manifests.disabled:
return True, {}
try:
manifest = pkg._shared_pkg_data.manifest
manifest.allow_missing = allow_missing
return allow_missing, manifest.distfiles
except pkg_errors.ParseChksumError as e:
if e.missing and allow_missing:
return allow_missing, {}
raise
def __repr__(self):
return "<ebuild %s location=%r @%#8x>" % (
self.__class__.__name__, self.base, id(self))
@klass.jit_attr
def deprecated(self):
"""Base deprecated packages restriction from profiles/package.deprecated."""
return packages.OrRestriction(*self.config.pkg_deprecated)
def _regen_operation_helper(self, **kwds):
return _RegenOpHelper(
self, force=bool(kwds.get('force', False)),
eclass_caching=bool(kwds.get('eclass_caching', True)))
def __getstate__(self):
d = self.__dict__.copy()
del d['_shared_pkg_cache']
return d
def __setstate__(self, state):
self.__dict__ = state.copy()
self.__dict__['_shared_pkg_cache'] = WeakValCache()
class _RegenOpHelper:
def __init__(self, repo, force=False, eclass_caching=True):
self.force = force
self.eclass_caching = eclass_caching
self.ebp = self.request_ebp()
def request_ebp(self):
ebp = processor.request_ebuild_processor()
if self.eclass_caching:
ebp.allow_eclass_caching()
return ebp
def __call__(self, pkg):
try:
return pkg._fetch_metadata(ebp=self.ebp, force_regen=self.force)
except pkg_errors.MetadataException as e:
# ebuild processor is dead, so force a replacement request
self.ebp = self.request_ebp()
raise
def __del__(self):
if self.eclass_caching:
self.ebp.disable_eclass_caching()
processor.release_ebuild_processor(self.ebp)
class ConfiguredTree(configured.tree):
"""Wrapper around a :obj:`UnconfiguredTree` binding build/configuration data (USE)."""
configurable = "use"
config_wrappables = {
x: klass.alias_method("evaluate_depset")
for x in (
"bdepend", "depend", "rdepend", "pdepend",
"fetchables", "license", "src_uri", "restrict", "required_use",
)
}
def __init__(self, raw_repo, domain, domain_settings, fetcher=None):
"""
:param raw_repo: :obj:`UnconfiguredTree` instance
:param domain_settings: environment settings to bind
:param fetcher: :obj:`pkgcore.fetch.base.fetcher` instance to use
for getting access to fetchable files
"""
required_settings = {'USE', 'CHOST'}
missing_settings = required_settings.difference(domain_settings)
if missing_settings:
raise errors.InitializationError(
f"{self.__class__} missing required setting{_pl(missing_settings)}: "
f"{', '.join(map(repr, missing_settings))}")
chost = domain_settings['CHOST']
scope_update = {'chost': chost}
scope_update.update(
(x, domain_settings.get(x.upper(), chost))
for x in ('cbuild', 'ctarget'))
scope_update.update(
(x, domain_settings[x.upper()])
for x in ('cflags', 'cxxflags', 'ldflags'))
scope_update['operations_callback'] = self._generate_pkg_operations
# update wrapped attr funcs requiring access to the class instance
for k, v in self.config_wrappables.items():
if isinstance(v, str):
self.config_wrappables[k] = getattr(self, v)
super().__init__(
raw_repo, self.config_wrappables, pkg_kls_injections=scope_update)
self.domain = domain
self.domain_settings = domain_settings
self._fetcher_override = fetcher
self._delayed_iuse = partial(make_kls(InvertedContains), InvertedContains)
def _wrap_attr(config_wrappables):
"""Register wrapped attrs that require class instance access."""
def _wrap_func(func):
@wraps(func)
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
attr = func.__name__.lstrip('_')
config_wrappables[attr] = func.__name__
return wrapped
return _wrap_func
@_wrap_attr(config_wrappables)
def _iuse_effective(self, raw_pkg_iuse_effective, _enabled_use, pkg):
"""IUSE_EFFECTIVE for a package."""
profile_iuse_effective = self.domain.profile.iuse_effective
return frozenset(profile_iuse_effective.union(raw_pkg_iuse_effective))
@_wrap_attr(config_wrappables)
def _distfiles(self, raw_pkg_distfiles, enabled_use, pkg):
"""Distfiles used by a package."""
return tuple(stable_unique(raw_pkg_distfiles.evaluate_depset(enabled_use)))
@_wrap_attr(config_wrappables)
def _user_patches(self, _raw_pkg_patches, _enabled_use, pkg):
"""User patches that will be applied when building a package."""
# determine available user patches for >= EAPI 6
if pkg.eapi.options.user_patches:
patches = []
patchroot = pjoin(self.domain.config_dir, 'patches')
patch_dirs = [
pkg.PF,
f'{pkg.PF}:{pkg.slot}',
pkg.P,
f'{pkg.P}:{pkg.slot}',
pkg.PN,
f'{pkg.PN}:{pkg.slot}',
]
for d in patch_dirs:
for root, _dirs, files in os.walk(pjoin(patchroot, pkg.category, d)):
files = (
pjoin(root, f) for f in sorted(files, key=locale.strxfrm)
if f.endswith(('.diff', '.patch')))
patches.append((root, tuple(files)))
return tuple(patches)
return None
def _get_delayed_immutable(self, pkg, immutable):
return InvertedContains(set(pkg.iuse).difference(immutable))
def _get_pkg_kwds(self, pkg):
immutable, enabled, _disabled = self.domain.get_package_use_unconfigured(pkg)
return {
"initial_settings": enabled,
"unchangable_settings": self._delayed_iuse(
self._get_delayed_immutable, pkg, immutable)}
def _generate_pkg_operations(self, domain, pkg, **kwds):
fetcher = self._fetcher_override
if fetcher is None:
fetcher = domain.fetcher
return ebd.src_operations(
domain, pkg, pkg.repo.eclass_cache, fetcher=fetcher, **kwds)
UnconfiguredTree.configure = ConfiguredTree