changeset 30119:f4a5e0e86a7e

py3: add an os.fsencode backport to ease path handling
author Martijn Pieters <mjpieters@fb.com>
date Sun, 09 Oct 2016 17:44:23 +0200
parents c19266edd93e
children 932faa29b4c1
files mercurial/pycompat.py
diffstat 1 files changed, 30 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/mercurial/pycompat.py	Sun Oct 09 14:10:01 2016 +0200
+++ b/mercurial/pycompat.py	Sun Oct 09 17:44:23 2016 +0200
@@ -34,6 +34,8 @@
 if ispy3:
     import builtins
     import functools
+    import os
+    fsencode = os.fsencode
 
     def sysstr(s):
         """Return a keyword str to be passed to Python functions such as
@@ -64,6 +66,34 @@
     def sysstr(s):
         return s
 
+    # Partial backport from os.py in Python 3
+    def _fscodec():
+        encoding = sys.getfilesystemencoding()
+        if encoding == 'mbcs':
+            errors = 'strict'
+        else:
+            errors = 'surrogateescape'
+
+        def fsencode(filename):
+            """
+            Encode filename to the filesystem encoding with 'surrogateescape'
+            error handler, return bytes unchanged. On Windows, use 'strict'
+            error handler if the file system encoding is 'mbcs' (which is the
+            default encoding).
+            """
+            if isinstance(filename, str):
+                return filename
+            elif isinstance(filename, unicode):
+                return filename.encode(encoding, errors)
+            else:
+                raise TypeError(
+                    "expect str or unicode, not %s" % type(filename).__name__)
+
+        return fsencode
+
+    fsencode = _fscodec()
+    del _fscodec
+
 stringio = io.StringIO
 empty = _queue.Empty
 queue = _queue.Queue