From 7354884c26cec98b5b5bb02e54a371da658cf10d Mon Sep 17 00:00:00 2001 From: Nicolas Delaby Date: Fri, 15 Oct 2010 14:20:47 +0200 Subject: Add new feature which return mime_encoding of file. --- README | 6 ++++++ magic.py | 9 +++++++-- test.py | 16 +++++++++++++++- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/README b/README index 567d33d..2f92668 100644 --- a/README +++ b/README @@ -44,3 +44,9 @@ To build and install run: >>> mime.from_file("testdata/test.pdf") 'application/pdf' >>> + +# For MIME encoding +>>> mime_encoding = magic.Magic(mime_encoding=True) +>>> mime_encoding.from_file("testdata/text-iso8859-1.txt") +'iso-8859-1' +>>> diff --git a/magic.py b/magic.py index 53e9609..b8c6935 100644 --- a/magic.py +++ b/magic.py @@ -31,18 +31,21 @@ class Magic: """ - def __init__(self, mime=False, magic_file=None): + def __init__(self, mime=False, mime_encoding=False, magic_file=None): """ Create a new libmagic wrapper. mime - if True, mimetypes are returned instead of textual descriptions + mime_encoding - if True, codec is returned magic_file - use a mime database other than the system default """ flags = MAGIC_NONE if mime: flags |= MAGIC_MIME - + elif mime_encoding: + flags |= MAGIC_MIME_ENCODING + self.cookie = magic_open(flags) magic_load(self.cookie, magic_file) @@ -186,6 +189,8 @@ MAGIC_DEVICES = 0x000008 # Look at the contents of devices MAGIC_MIME = 0x000010 # Return a mime string +MAGIC_MIME_ENCODING = 0x000400 # Return the MIME encoding + MAGIC_CONTINUE = 0x000020 # Return all matches MAGIC_CHECK = 0x000040 # Print warnings to stderr diff --git a/test.py b/test.py index 0d5140e..f353124 100644 --- a/test.py +++ b/test.py @@ -14,6 +14,7 @@ testfile = [ ("text.txt", "ASCII text", "text/plain; charset=us-ascii"), ] +testFileEncoding = [('text-iso8859-1.txt', 'iso-8859-1')] class TestMagic(unittest.TestCase): @@ -45,7 +46,20 @@ class TestMagic(unittest.TestCase): class TestMagicMime(TestMagic): mime = True - + +class TestMagicMimeEncoding(TestMagic): + def setUp(self): + self.m = Magic(mime_encoding=True) + + def testFileEncoding(self): + for filename, encoding in testFileEncoding: + filename = path.join(path.dirname(__file__), + "testdata", + filename) + self.assertEqual(encoding, self.m.from_buffer(open(filename).read(1024))) + self.assertEqual(encoding, self.m.from_file(filename), filename) + + if __name__ == '__main__': unittest.main() -- cgit v1.2.1