sitecustomize.pyx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import pathlib
  2. import re
  3. import sys
  4. import __res
  5. from importlib.abc import ResourceReader
  6. from importlib.metadata import Distribution, DistributionFinder, PackageNotFoundError, Prepared
  7. ResourceReader.register(__res._ResfsResourceReader)
  8. METADATA_NAME = re.compile('^Name: (.*)$', re.MULTILINE)
  9. class ArcadiaDistribution(Distribution):
  10. def __init__(self, prefix):
  11. self.prefix = prefix
  12. @property
  13. def _path(self):
  14. return pathlib.Path(self.prefix)
  15. def read_text(self, filename):
  16. data = __res.resfs_read(f'{self.prefix}{filename}')
  17. if data:
  18. return data.decode('utf-8')
  19. read_text.__doc__ = Distribution.read_text.__doc__
  20. def locate_file(self, path):
  21. return f'{self.prefix}{path}'
  22. class ArcadiaMetadataFinder(DistributionFinder):
  23. prefixes = {}
  24. @classmethod
  25. def find_distributions(cls, context=DistributionFinder.Context()):
  26. found = cls._search_prefixes(context.name)
  27. return map(ArcadiaDistribution, found)
  28. @classmethod
  29. def _init_prefixes(cls):
  30. cls.prefixes.clear()
  31. for resource in __res.resfs_files():
  32. resource = resource.decode('utf-8')
  33. if not resource.endswith('METADATA'):
  34. continue
  35. data = __res.resfs_read(resource).decode('utf-8')
  36. metadata_name = METADATA_NAME.search(data)
  37. if metadata_name:
  38. metadata_name = Prepared(metadata_name.group(1))
  39. cls.prefixes[metadata_name.normalized] = resource[:-len('METADATA')]
  40. @classmethod
  41. def _search_prefixes(cls, name):
  42. if not cls.prefixes:
  43. cls._init_prefixes()
  44. if name:
  45. try:
  46. yield cls.prefixes[Prepared(name).normalized]
  47. except KeyError:
  48. raise PackageNotFoundError(name)
  49. else:
  50. for prefix in sorted(cls.prefixes.values()):
  51. yield prefix
  52. # monkeypatch standart library
  53. import importlib.metadata
  54. importlib.metadata.MetadataPathFinder = ArcadiaMetadataFinder