_legacy.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import functools
  2. import os
  3. import pathlib
  4. import types
  5. import warnings
  6. from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any
  7. from . import _common
  8. Package = Union[types.ModuleType, str]
  9. Resource = str
  10. def deprecated(func):
  11. @functools.wraps(func)
  12. def wrapper(*args, **kwargs):
  13. warnings.warn(
  14. f"{func.__name__} is deprecated. Use files() instead. "
  15. "Refer to https://importlib-resources.readthedocs.io"
  16. "/en/latest/using.html#migrating-from-legacy for migration advice.",
  17. DeprecationWarning,
  18. stacklevel=2,
  19. )
  20. return func(*args, **kwargs)
  21. return wrapper
  22. def normalize_path(path: Any) -> str:
  23. """Normalize a path by ensuring it is a string.
  24. If the resulting string contains path separators, an exception is raised.
  25. """
  26. str_path = str(path)
  27. parent, file_name = os.path.split(str_path)
  28. if parent:
  29. raise ValueError(f'{path!r} must be only a file name')
  30. return file_name
  31. @deprecated
  32. def open_binary(package: Package, resource: Resource) -> BinaryIO:
  33. """Return a file-like object opened for binary reading of the resource."""
  34. return (_common.files(package) / normalize_path(resource)).open('rb')
  35. @deprecated
  36. def read_binary(package: Package, resource: Resource) -> bytes:
  37. """Return the binary contents of the resource."""
  38. return (_common.files(package) / normalize_path(resource)).read_bytes()
  39. @deprecated
  40. def open_text(
  41. package: Package,
  42. resource: Resource,
  43. encoding: str = 'utf-8',
  44. errors: str = 'strict',
  45. ) -> TextIO:
  46. """Return a file-like object opened for text reading of the resource."""
  47. return (_common.files(package) / normalize_path(resource)).open(
  48. 'r', encoding=encoding, errors=errors
  49. )
  50. @deprecated
  51. def read_text(
  52. package: Package,
  53. resource: Resource,
  54. encoding: str = 'utf-8',
  55. errors: str = 'strict',
  56. ) -> str:
  57. """Return the decoded string of the resource.
  58. The decoding-related arguments have the same semantics as those of
  59. bytes.decode().
  60. """
  61. with open_text(package, resource, encoding, errors) as fp:
  62. return fp.read()
  63. @deprecated
  64. def contents(package: Package) -> Iterable[str]:
  65. """Return an iterable of entries in `package`.
  66. Note that not all entries are resources. Specifically, directories are
  67. not considered resources. Use `is_resource()` on each entry returned here
  68. to check if it is a resource or not.
  69. """
  70. return [path.name for path in _common.files(package).iterdir()]
  71. @deprecated
  72. def is_resource(package: Package, name: str) -> bool:
  73. """True if `name` is a resource inside `package`.
  74. Directories are *not* resources.
  75. """
  76. resource = normalize_path(name)
  77. return any(
  78. traversable.name == resource and traversable.is_file()
  79. for traversable in _common.files(package).iterdir()
  80. )
  81. @deprecated
  82. def path(
  83. package: Package,
  84. resource: Resource,
  85. ) -> ContextManager[pathlib.Path]:
  86. """A context manager providing a file path object to the resource.
  87. If the resource does not already exist on its own on the file system,
  88. a temporary file will be created. If the file was created, the file
  89. will be deleted upon exiting the context manager (no exception is
  90. raised if the file was deleted prior to the context manager
  91. exiting).
  92. """
  93. return _common.as_file(_common.files(package) / normalize_path(resource))