logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

abc.py (14421B)


  1. """Abstract base classes related to import."""
  2. from . import _bootstrap_external
  3. from . import machinery
  4. try:
  5. import _frozen_importlib
  6. except ImportError as exc:
  7. if exc.name != '_frozen_importlib':
  8. raise
  9. _frozen_importlib = None
  10. try:
  11. import _frozen_importlib_external
  12. except ImportError:
  13. _frozen_importlib_external = _bootstrap_external
  14. from ._abc import Loader
  15. import abc
  16. import warnings
  17. from typing import BinaryIO, Iterable, Text
  18. from typing import Protocol, runtime_checkable
  19. def _register(abstract_cls, *classes):
  20. for cls in classes:
  21. abstract_cls.register(cls)
  22. if _frozen_importlib is not None:
  23. try:
  24. frozen_cls = getattr(_frozen_importlib, cls.__name__)
  25. except AttributeError:
  26. frozen_cls = getattr(_frozen_importlib_external, cls.__name__)
  27. abstract_cls.register(frozen_cls)
  28. class Finder(metaclass=abc.ABCMeta):
  29. """Legacy abstract base class for import finders.
  30. It may be subclassed for compatibility with legacy third party
  31. reimplementations of the import system. Otherwise, finder
  32. implementations should derive from the more specific MetaPathFinder
  33. or PathEntryFinder ABCs.
  34. Deprecated since Python 3.3
  35. """
  36. def __init__(self):
  37. warnings.warn("the Finder ABC is deprecated and "
  38. "slated for removal in Python 3.12; use MetaPathFinder "
  39. "or PathEntryFinder instead",
  40. DeprecationWarning)
  41. @abc.abstractmethod
  42. def find_module(self, fullname, path=None):
  43. """An abstract method that should find a module.
  44. The fullname is a str and the optional path is a str or None.
  45. Returns a Loader object or None.
  46. """
  47. warnings.warn("importlib.abc.Finder along with its find_module() "
  48. "method are deprecated and "
  49. "slated for removal in Python 3.12; use "
  50. "MetaPathFinder.find_spec() or "
  51. "PathEntryFinder.find_spec() instead",
  52. DeprecationWarning)
  53. class MetaPathFinder(metaclass=abc.ABCMeta):
  54. """Abstract base class for import finders on sys.meta_path."""
  55. # We don't define find_spec() here since that would break
  56. # hasattr checks we do to support backward compatibility.
  57. def find_module(self, fullname, path):
  58. """Return a loader for the module.
  59. If no module is found, return None. The fullname is a str and
  60. the path is a list of strings or None.
  61. This method is deprecated since Python 3.4 in favor of
  62. finder.find_spec(). If find_spec() exists then backwards-compatible
  63. functionality is provided for this method.
  64. """
  65. warnings.warn("MetaPathFinder.find_module() is deprecated since Python "
  66. "3.4 in favor of MetaPathFinder.find_spec() and is "
  67. "slated for removal in Python 3.12",
  68. DeprecationWarning,
  69. stacklevel=2)
  70. if not hasattr(self, 'find_spec'):
  71. return None
  72. found = self.find_spec(fullname, path)
  73. return found.loader if found is not None else None
  74. def invalidate_caches(self):
  75. """An optional method for clearing the finder's cache, if any.
  76. This method is used by importlib.invalidate_caches().
  77. """
  78. _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter,
  79. machinery.PathFinder, machinery.WindowsRegistryFinder)
  80. class PathEntryFinder(metaclass=abc.ABCMeta):
  81. """Abstract base class for path entry finders used by PathFinder."""
  82. # We don't define find_spec() here since that would break
  83. # hasattr checks we do to support backward compatibility.
  84. def find_loader(self, fullname):
  85. """Return (loader, namespace portion) for the path entry.
  86. The fullname is a str. The namespace portion is a sequence of
  87. path entries contributing to part of a namespace package. The
  88. sequence may be empty. If loader is not None, the portion will
  89. be ignored.
  90. The portion will be discarded if another path entry finder
  91. locates the module as a normal module or package.
  92. This method is deprecated since Python 3.4 in favor of
  93. finder.find_spec(). If find_spec() is provided than backwards-compatible
  94. functionality is provided.
  95. """
  96. warnings.warn("PathEntryFinder.find_loader() is deprecated since Python "
  97. "3.4 in favor of PathEntryFinder.find_spec() "
  98. "(available since 3.4)",
  99. DeprecationWarning,
  100. stacklevel=2)
  101. if not hasattr(self, 'find_spec'):
  102. return None, []
  103. found = self.find_spec(fullname)
  104. if found is not None:
  105. if not found.submodule_search_locations:
  106. portions = []
  107. else:
  108. portions = found.submodule_search_locations
  109. return found.loader, portions
  110. else:
  111. return None, []
  112. find_module = _bootstrap_external._find_module_shim
  113. def invalidate_caches(self):
  114. """An optional method for clearing the finder's cache, if any.
  115. This method is used by PathFinder.invalidate_caches().
  116. """
  117. _register(PathEntryFinder, machinery.FileFinder)
  118. class ResourceLoader(Loader):
  119. """Abstract base class for loaders which can return data from their
  120. back-end storage.
  121. This ABC represents one of the optional protocols specified by PEP 302.
  122. """
  123. @abc.abstractmethod
  124. def get_data(self, path):
  125. """Abstract method which when implemented should return the bytes for
  126. the specified path. The path must be a str."""
  127. raise OSError
  128. class InspectLoader(Loader):
  129. """Abstract base class for loaders which support inspection about the
  130. modules they can load.
  131. This ABC represents one of the optional protocols specified by PEP 302.
  132. """
  133. def is_package(self, fullname):
  134. """Optional method which when implemented should return whether the
  135. module is a package. The fullname is a str. Returns a bool.
  136. Raises ImportError if the module cannot be found.
  137. """
  138. raise ImportError
  139. def get_code(self, fullname):
  140. """Method which returns the code object for the module.
  141. The fullname is a str. Returns a types.CodeType if possible, else
  142. returns None if a code object does not make sense
  143. (e.g. built-in module). Raises ImportError if the module cannot be
  144. found.
  145. """
  146. source = self.get_source(fullname)
  147. if source is None:
  148. return None
  149. return self.source_to_code(source)
  150. @abc.abstractmethod
  151. def get_source(self, fullname):
  152. """Abstract method which should return the source code for the
  153. module. The fullname is a str. Returns a str.
  154. Raises ImportError if the module cannot be found.
  155. """
  156. raise ImportError
  157. @staticmethod
  158. def source_to_code(data, path='<string>'):
  159. """Compile 'data' into a code object.
  160. The 'data' argument can be anything that compile() can handle. The'path'
  161. argument should be where the data was retrieved (when applicable)."""
  162. return compile(data, path, 'exec', dont_inherit=True)
  163. exec_module = _bootstrap_external._LoaderBasics.exec_module
  164. load_module = _bootstrap_external._LoaderBasics.load_module
  165. _register(InspectLoader, machinery.BuiltinImporter, machinery.FrozenImporter)
  166. class ExecutionLoader(InspectLoader):
  167. """Abstract base class for loaders that wish to support the execution of
  168. modules as scripts.
  169. This ABC represents one of the optional protocols specified in PEP 302.
  170. """
  171. @abc.abstractmethod
  172. def get_filename(self, fullname):
  173. """Abstract method which should return the value that __file__ is to be
  174. set to.
  175. Raises ImportError if the module cannot be found.
  176. """
  177. raise ImportError
  178. def get_code(self, fullname):
  179. """Method to return the code object for fullname.
  180. Should return None if not applicable (e.g. built-in module).
  181. Raise ImportError if the module cannot be found.
  182. """
  183. source = self.get_source(fullname)
  184. if source is None:
  185. return None
  186. try:
  187. path = self.get_filename(fullname)
  188. except ImportError:
  189. return self.source_to_code(source)
  190. else:
  191. return self.source_to_code(source, path)
  192. _register(ExecutionLoader, machinery.ExtensionFileLoader)
  193. class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader):
  194. """Abstract base class partially implementing the ResourceLoader and
  195. ExecutionLoader ABCs."""
  196. _register(FileLoader, machinery.SourceFileLoader,
  197. machinery.SourcelessFileLoader)
  198. class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader):
  199. """Abstract base class for loading source code (and optionally any
  200. corresponding bytecode).
  201. To support loading from source code, the abstractmethods inherited from
  202. ResourceLoader and ExecutionLoader need to be implemented. To also support
  203. loading from bytecode, the optional methods specified directly by this ABC
  204. is required.
  205. Inherited abstractmethods not implemented in this ABC:
  206. * ResourceLoader.get_data
  207. * ExecutionLoader.get_filename
  208. """
  209. def path_mtime(self, path):
  210. """Return the (int) modification time for the path (str)."""
  211. if self.path_stats.__func__ is SourceLoader.path_stats:
  212. raise OSError
  213. return int(self.path_stats(path)['mtime'])
  214. def path_stats(self, path):
  215. """Return a metadata dict for the source pointed to by the path (str).
  216. Possible keys:
  217. - 'mtime' (mandatory) is the numeric timestamp of last source
  218. code modification;
  219. - 'size' (optional) is the size in bytes of the source code.
  220. """
  221. if self.path_mtime.__func__ is SourceLoader.path_mtime:
  222. raise OSError
  223. return {'mtime': self.path_mtime(path)}
  224. def set_data(self, path, data):
  225. """Write the bytes to the path (if possible).
  226. Accepts a str path and data as bytes.
  227. Any needed intermediary directories are to be created. If for some
  228. reason the file cannot be written because of permissions, fail
  229. silently.
  230. """
  231. _register(SourceLoader, machinery.SourceFileLoader)
  232. class ResourceReader(metaclass=abc.ABCMeta):
  233. """Abstract base class for loaders to provide resource reading support."""
  234. @abc.abstractmethod
  235. def open_resource(self, resource: Text) -> BinaryIO:
  236. """Return an opened, file-like object for binary reading.
  237. The 'resource' argument is expected to represent only a file name.
  238. If the resource cannot be found, FileNotFoundError is raised.
  239. """
  240. # This deliberately raises FileNotFoundError instead of
  241. # NotImplementedError so that if this method is accidentally called,
  242. # it'll still do the right thing.
  243. raise FileNotFoundError
  244. @abc.abstractmethod
  245. def resource_path(self, resource: Text) -> Text:
  246. """Return the file system path to the specified resource.
  247. The 'resource' argument is expected to represent only a file name.
  248. If the resource does not exist on the file system, raise
  249. FileNotFoundError.
  250. """
  251. # This deliberately raises FileNotFoundError instead of
  252. # NotImplementedError so that if this method is accidentally called,
  253. # it'll still do the right thing.
  254. raise FileNotFoundError
  255. @abc.abstractmethod
  256. def is_resource(self, path: Text) -> bool:
  257. """Return True if the named 'path' is a resource.
  258. Files are resources, directories are not.
  259. """
  260. raise FileNotFoundError
  261. @abc.abstractmethod
  262. def contents(self) -> Iterable[str]:
  263. """Return an iterable of entries in `package`."""
  264. raise FileNotFoundError
  265. @runtime_checkable
  266. class Traversable(Protocol):
  267. """
  268. An object with a subset of pathlib.Path methods suitable for
  269. traversing directories and opening files.
  270. """
  271. @abc.abstractmethod
  272. def iterdir(self):
  273. """
  274. Yield Traversable objects in self
  275. """
  276. def read_bytes(self):
  277. """
  278. Read contents of self as bytes
  279. """
  280. with self.open('rb') as strm:
  281. return strm.read()
  282. def read_text(self, encoding=None):
  283. """
  284. Read contents of self as text
  285. """
  286. with self.open(encoding=encoding) as strm:
  287. return strm.read()
  288. @abc.abstractmethod
  289. def is_dir(self) -> bool:
  290. """
  291. Return True if self is a dir
  292. """
  293. @abc.abstractmethod
  294. def is_file(self) -> bool:
  295. """
  296. Return True if self is a file
  297. """
  298. @abc.abstractmethod
  299. def joinpath(self, child):
  300. """
  301. Return Traversable child in self
  302. """
  303. def __truediv__(self, child):
  304. """
  305. Return Traversable child in self
  306. """
  307. return self.joinpath(child)
  308. @abc.abstractmethod
  309. def open(self, mode='r', *args, **kwargs):
  310. """
  311. mode may be 'r' or 'rb' to open as text or binary. Return a handle
  312. suitable for reading (same as pathlib.Path.open).
  313. When opening as text, accepts encoding parameters such as those
  314. accepted by io.TextIOWrapper.
  315. """
  316. @abc.abstractproperty
  317. def name(self) -> str:
  318. """
  319. The base name of this object without any parent references.
  320. """
  321. class TraversableResources(ResourceReader):
  322. """
  323. The required interface for providing traversable
  324. resources.
  325. """
  326. @abc.abstractmethod
  327. def files(self):
  328. """Return a Traversable object for the loaded package."""
  329. def open_resource(self, resource):
  330. return self.files().joinpath(resource).open('rb')
  331. def resource_path(self, resource):
  332. raise FileNotFoundError(resource)
  333. def is_resource(self, path):
  334. return self.files().joinpath(path).is_file()
  335. def contents(self):
  336. return (item.name for item in self.files().iterdir())