A meta_path importer that loads code from built-in resources.
| 288 | |
| 289 | |
| 290 | class ResourceImporter(SourceFileLoader): |
| 291 | |
| 292 | """ A meta_path importer that loads code from built-in resources. |
| 293 | """ |
| 294 | |
| 295 | def __init__(self, fullname, path): |
| 296 | super().__init__(fullname, path) |
| 297 | self.memory = set(iter_py_modules()) # Set of importable module names. |
| 298 | self._source_name = {} # Map from original to altered module names. |
| 299 | self._package_prefix = '' |
| 300 | |
| 301 | self._before_import_callback = None |
| 302 | self._after_import_callback = None |
| 303 | |
| 304 | if Y_PYTHON_SOURCE_ROOT and Y_PYTHON_EXTENDED_SOURCE_SEARCH: |
| 305 | self.arcadia_source_finder = ArcadiaSourceFinder(_s(Y_PYTHON_SOURCE_ROOT)) |
| 306 | else: |
| 307 | self.arcadia_source_finder = None |
| 308 | |
| 309 | for p in list(self.memory) + list(sys.builtin_module_names): |
| 310 | for pp in iter_prefixes(p): |
| 311 | k = pp + '.__init__' |
| 312 | if k not in self.memory: |
| 313 | self.memory.add(k) |
| 314 | |
| 315 | def set_callbacks(self, before_import=None, after_import=None): |
| 316 | """Callable[[module], None]""" |
| 317 | self._before_import_callback= before_import |
| 318 | self._after_import_callback = after_import |
| 319 | |
| 320 | def for_package(self, name): |
| 321 | import copy |
| 322 | importer = copy.copy(self) |
| 323 | importer._package_prefix = name + '.' |
| 324 | return importer |
| 325 | |
| 326 | def _find_mod_path(self, fullname): |
| 327 | """Find arcadia relative path by module name""" |
| 328 | relpath = resfs_src(mod_path(fullname), resfs_file=True) |
| 329 | if relpath or not self.arcadia_source_finder: |
| 330 | return relpath |
| 331 | return self.arcadia_source_finder.get_module_path(fullname) |
| 332 | |
| 333 | def find_spec(self, fullname, path=None, target=None): |
| 334 | # Поддежка переопределения стандартного distutils из пакетом из setuptools |
| 335 | if fullname.startswith("distutils."): |
| 336 | setuptools_path = f"{path_sep}setuptools{path_sep}_distutils" |
| 337 | if path and len(path) > 0 and setuptools_path in path[0]: |
| 338 | import importlib |
| 339 | import importlib.abc |
| 340 | |
| 341 | setuptools_name = "setuptools._distutils.{}".format(fullname.removeprefix("distutils.")) |
| 342 | is_package = self.is_package(setuptools_name) |
| 343 | if is_package: |
| 344 | source = self.get_source(f"{setuptools_name}.__init__") |
| 345 | relpath = self._find_mod_path(f"{setuptools_name}.__init__") |
| 346 | else: |
| 347 | source = self.get_source(setuptools_name) |