|
| 1 | +""" |
| 2 | +A shim of the os module containing only simple path-related utilities |
| 3 | +""" |
| 4 | + |
| 5 | +try: |
| 6 | + from os import * |
| 7 | +except ImportError: |
| 8 | + import abc |
| 9 | + |
| 10 | + def __getattr__(name): |
| 11 | + raise OSError("no os specific module found") |
| 12 | + |
| 13 | + def _shim(): |
| 14 | + import _dummy_os, sys |
| 15 | + sys.modules['os'] = _dummy_os |
| 16 | + sys.modules['os.path'] = _dummy_os.path |
| 17 | + |
| 18 | + import posixpath as path |
| 19 | + import sys |
| 20 | + sys.modules['os.path'] = path |
| 21 | + del sys |
| 22 | + |
| 23 | + sep = path.sep |
| 24 | + |
| 25 | + |
| 26 | + def fspath(path): |
| 27 | + """Return the path representation of a path-like object. |
| 28 | +
|
| 29 | + If str or bytes is passed in, it is returned unchanged. Otherwise the |
| 30 | + os.PathLike interface is used to get the path representation. If the |
| 31 | + path representation is not str or bytes, TypeError is raised. If the |
| 32 | + provided path is not str, bytes, or os.PathLike, TypeError is raised. |
| 33 | + """ |
| 34 | + if isinstance(path, (str, bytes)): |
| 35 | + return path |
| 36 | + |
| 37 | + # Work from the object's type to match method resolution of other magic |
| 38 | + # methods. |
| 39 | + path_type = type(path) |
| 40 | + try: |
| 41 | + path_repr = path_type.__fspath__(path) |
| 42 | + except AttributeError: |
| 43 | + if hasattr(path_type, '__fspath__'): |
| 44 | + raise |
| 45 | + else: |
| 46 | + raise TypeError("expected str, bytes or os.PathLike object, " |
| 47 | + "not " + path_type.__name__) |
| 48 | + if isinstance(path_repr, (str, bytes)): |
| 49 | + return path_repr |
| 50 | + else: |
| 51 | + raise TypeError("expected {}.__fspath__() to return str or bytes, " |
| 52 | + "not {}".format(path_type.__name__, |
| 53 | + type(path_repr).__name__)) |
| 54 | + |
| 55 | + class PathLike(abc.ABC): |
| 56 | + |
| 57 | + """Abstract base class for implementing the file system path protocol.""" |
| 58 | + |
| 59 | + @abc.abstractmethod |
| 60 | + def __fspath__(self): |
| 61 | + """Return the file system path representation of the object.""" |
| 62 | + raise NotImplementedError |
| 63 | + |
| 64 | + @classmethod |
| 65 | + def __subclasshook__(cls, subclass): |
| 66 | + return hasattr(subclass, '__fspath__') |
0 commit comments