[diffoscope] [PATCH] python-magic >=0.4.12 does not require decode

Rainer Müller raimue at macports.org
Fri Jul 8 16:02:58 CEST 2016


As of python-magic >=0.4.12 [1], the conversion to bytes was inlined
into the module. The additional .decode('utf-8') triggered an
AttributeError on the str object. Add a helper function to do the decode
only if required.

[1] https://github.com/ahupp/python-magic/commit/b1666986236eab820e9155a5943d6b94938b4c40
---
 diffoscope/comparators/binary.py | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/diffoscope/comparators/binary.py b/diffoscope/comparators/binary.py
index 9dfd44c..dfab2dd 100644
--- a/diffoscope/comparators/binary.py
+++ b/diffoscope/comparators/binary.py
@@ -37,6 +37,12 @@ from diffoscope.config import Config
 from diffoscope.difference import Difference
 from diffoscope import tool_required, RequiredToolNotFound, OutputParsingError, logger
 
+# helper function to convert to bytes if necessary
+def maybe_decode(s):
+    if str == bytes:
+        return s
+    else:
+        return s.decode('utf-8')
 
 def hexdump_fallback(path):
     hexdump = StringIO()
@@ -79,13 +85,13 @@ class File(object, metaclass=ABCMeta):
         def guess_file_type(self, path):
             if not hasattr(self, '_mimedb'):
                 self._mimedb = magic.Magic()
-            return self._mimedb.from_file(path).decode('utf-8')
+            return maybe_decode(self._mimedb.from_file(path))
 
         @classmethod
         def guess_encoding(self, path):
             if not hasattr(self, '_mimedb_encoding'):
                 self._mimedb_encoding = magic.Magic(mime_encoding=True)
-            return self._mimedb_encoding.from_file(path).decode('utf-8')
+            return maybe_decode(self._mimedb_encoding.from_file(path))
 
     def __init__(self, container=None):
         self._container = container
-- 
2.9.0



More information about the diffoscope mailing list