py3: pass str and return bytes from mimetypes.guess_type()
authorGregory Szorc <gregory.szorc@gmail.com>
Thu, 11 Oct 2018 21:47:39 +0200
changeset 40158 9310037f0636
parent 40157 a8be613391d1
child 40159 5774fc623a18
py3: pass str and return bytes from mimetypes.guess_type() This function wants a str (which represents a path) and returns a str. We normalize input to str and output to bytes. Differential Revision: https://phab.mercurial-scm.org/D4967
mercurial/hgweb/common.py
mercurial/hgweb/webcommands.py
--- a/mercurial/hgweb/common.py	Thu Oct 11 22:27:52 2018 +0200
+++ b/mercurial/hgweb/common.py	Thu Oct 11 21:47:39 2018 +0200
@@ -182,7 +182,8 @@
             break
     try:
         os.stat(path)
-        ct = mimetypes.guess_type(pycompat.fsdecode(path))[0] or "text/plain"
+        ct = pycompat.sysbytes(
+            mimetypes.guess_type(pycompat.fsdecode(path))[0] or "text/plain")
         with open(path, 'rb') as fh:
             data = fh.read()
 
--- a/mercurial/hgweb/webcommands.py	Thu Oct 11 22:27:52 2018 +0200
+++ b/mercurial/hgweb/webcommands.py	Thu Oct 11 21:47:39 2018 +0200
@@ -123,12 +123,15 @@
     text = fctx.data()
     mt = 'application/binary'
     if guessmime:
-        mt = mimetypes.guess_type(path)[0]
+        mt = mimetypes.guess_type(pycompat.fsdecode(path))[0]
         if mt is None:
             if stringutil.binary(text):
                 mt = 'application/binary'
             else:
                 mt = 'text/plain'
+        else:
+            mt = pycompat.sysbytes(mt)
+
     if mt.startswith('text/'):
         mt += '; charset="%s"' % encoding.encoding
 
@@ -146,7 +149,9 @@
     ishead = fctx.filenode() in fctx.filelog().heads()
 
     if stringutil.binary(text):
-        mt = mimetypes.guess_type(f)[0] or 'application/octet-stream'
+        mt = pycompat.sysbytes(
+            mimetypes.guess_type(pycompat.fsdecode(f))[0]
+            or 'application/octet-stream')
         text = '(binary:%s)' % mt
 
     def lines(context):
@@ -857,9 +862,9 @@
 
     def filelines(f):
         if f.isbinary():
-            mt = mimetypes.guess_type(f.path())[0]
-            if not mt:
-                mt = 'application/octet-stream'
+            mt = pycompat.sysbytes(
+                mimetypes.guess_type(pycompat.fsdecode(f.path()))[0]
+                or 'application/octet-stream')
             return [_('(binary file %s, hash: %s)') % (mt, hex(f.filenode()))]
         return f.data().splitlines()
 
@@ -945,8 +950,9 @@
 
     def annotate(context):
         if fctx.isbinary():
-            mt = (mimetypes.guess_type(fctx.path())[0]
-                  or 'application/octet-stream')
+            mt = pycompat.sysbytes(
+                mimetypes.guess_type(pycompat.fsdecode(fctx.path()))[0]
+                or 'application/octet-stream')
             lines = [dagop.annotateline(fctx=fctx.filectx(fctx.filerev()),
                                         lineno=1, text='(binary:%s)' % mt)]
         else: