|
| 1 | +import sys |
| 2 | + |
| 3 | +import six |
| 4 | + |
| 5 | +try: |
| 6 | + from os import fsencode, fsdecode |
| 7 | +except ImportError: |
| 8 | + def _fscodec(): |
| 9 | + encoding = sys.getfilesystemencoding() |
| 10 | + errors = 'strict' if encoding == 'mbcs' else 'surrogateescape' |
| 11 | + |
| 12 | + def fsencode(filename): |
| 13 | + """ |
| 14 | + Encode filename to the filesystem encoding with 'surrogateescape' error |
| 15 | + handler, return bytes unchanged. On Windows, use 'strict' error handler if |
| 16 | + the file system encoding is 'mbcs' (which is the default encoding). |
| 17 | + """ |
| 18 | + if isinstance(filename, bytes): |
| 19 | + return filename |
| 20 | + elif isinstance(filename, six.text_type): |
| 21 | + return filename.encode(encoding, errors) |
| 22 | + else: |
| 23 | + raise TypeError("expect string type, not %s" % type(filename).__name__) |
| 24 | + |
| 25 | + def fsdecode(filename): |
| 26 | + """ |
| 27 | + Decode filename from the filesystem encoding with 'surrogateescape' error |
| 28 | + handler, return str unchanged. On Windows, use 'strict' error handler if |
| 29 | + the file system encoding is 'mbcs' (which is the default encoding). |
| 30 | + """ |
| 31 | + if isinstance(filename, six.text_type): |
| 32 | + return filename |
| 33 | + elif isinstance(filename, bytes): |
| 34 | + return filename.decode(encoding, errors) |
| 35 | + else: |
| 36 | + raise TypeError("expect string type, not %s" % type(filename).__name__) |
| 37 | + |
| 38 | + return fsencode, fsdecode |
| 39 | + |
| 40 | + fsencode, fsdecode = _fscodec() |
| 41 | + del _fscodec |
| 42 | + |
| 43 | +try: |
| 44 | + from os import fspath |
| 45 | +except ImportError: |
| 46 | + def fspath(path): |
| 47 | + """Return the path representation of a path-like object. |
| 48 | +
|
| 49 | + If str or bytes is passed in, it is returned unchanged. Otherwise the |
| 50 | + os.PathLike interface is used to get the path representation. If the |
| 51 | + path representation is not str or bytes, TypeError is raised. If the |
| 52 | + provided path is not str, bytes, or os.PathLike, TypeError is raised. |
| 53 | + """ |
| 54 | + if isinstance(path, (six.text_type, bytes)): |
| 55 | + return path |
| 56 | + |
| 57 | + # Work from the object's type to match method resolution of other magic |
| 58 | + # methods. |
| 59 | + path_type = type(path) |
| 60 | + try: |
| 61 | + path_repr = path_type.__fspath__(path) |
| 62 | + except AttributeError: |
| 63 | + if hasattr(path_type, '__fspath__'): |
| 64 | + raise |
| 65 | + else: |
| 66 | + raise TypeError("expected string type or os.PathLike object, " |
| 67 | + "not " + path_type.__name__) |
| 68 | + if isinstance(path_repr, (six.text_type, bytes)): |
| 69 | + return path_repr |
| 70 | + else: |
| 71 | + raise TypeError("expected {}.__fspath__() to return string type " |
| 72 | + "not {}".format(path_type.__name__, |
| 73 | + type(path_repr).__name__)) |
0 commit comments