2828# avoid shadowing the real open with the version from compat.py
2929_real_open = open
3030
31+
3132class MagicException (Exception ):
3233 def __init__ (self , message ):
33- super (MagicException , self ).__init__ (message )
34+ super (Exception , self ).__init__ (message )
3435 self .message = message
3536
3637
@@ -162,6 +163,7 @@ def __del__(self):
162163 magic_close (self .cookie )
163164 self .cookie = None
164165
166+
165167_instances = {}
166168
167169
@@ -215,10 +217,10 @@ def from_descriptor(fd, mime=False):
215217libmagic = None
216218# Let's try to find magic or magic1
217219dll = ctypes .util .find_library ('magic' ) \
218- or ctypes .util .find_library ('magic1' ) \
219- or ctypes .util .find_library ('cygmagic-1' ) \
220- or ctypes .util .find_library ('libmagic-1' ) \
221- or ctypes .util .find_library ('msys-magic-1' ) # for MSYS2
220+ or ctypes .util .find_library ('magic1' ) \
221+ or ctypes .util .find_library ('cygmagic-1' ) \
222+ or ctypes .util .find_library ('libmagic-1' ) \
223+ or ctypes .util .find_library ('msys-magic-1' ) # for MSYS2
222224
223225# necessary because find_library returns None if it doesn't find the library
224226if dll :
@@ -228,12 +230,13 @@ def from_descriptor(fd, mime=False):
228230 windows_dlls = ['magic1.dll' , 'cygmagic-1.dll' , 'libmagic-1.dll' , 'msys-magic-1.dll' ]
229231 platform_to_lib = {'darwin' : ['/opt/local/lib/libmagic.dylib' ,
230232 '/usr/local/lib/libmagic.dylib' ] +
231- # Assumes there will only be one version installed
232- glob .glob ('/usr/local/Cellar/libmagic/*/lib/libmagic.dylib' ), # flake8:noqa
233+ # Assumes there will only be one version installed
234+ glob .glob ('/usr/local/Cellar/libmagic/*/lib/libmagic.dylib' ), # flake8:noqa
233235 'win32' : windows_dlls ,
234236 'cygwin' : windows_dlls ,
235- 'linux' : ['libmagic.so.1' ], # fallback for some Linuxes (e.g. Alpine) where library search does not work # flake8:noqa
236- }
237+ 'linux' : ['libmagic.so.1' ],
238+ # fallback for some Linuxes (e.g. Alpine) where library search does not work # flake8:noqa
239+ }
237240 platform = 'linux' if sys .platform .startswith ('linux' ) else sys .platform
238241 for dll in platform_to_lib .get (platform , []):
239242 try :
@@ -280,15 +283,7 @@ def coerce_filename(filename):
280283 if filename is None :
281284 return None
282285
283- # ctypes will implicitly convert unicode strings to bytes with
284- # .encode('ascii'). If you use the filesystem encoding
285- # then you'll get inconsistent behavior (crashes) depending on the user's
286- # LANG environment variable
287- is_unicode = (sys .version_info [0 ] <= 2 and
288- isinstance (filename , unicode )) or \
289- (sys .version_info [0 ] >= 3 and
290- isinstance (filename , str ))
291- if is_unicode :
286+ if isinstance (filename , str ):
292287 return filename .encode ('utf-8' , 'surrogateescape' )
293288 else :
294289 return filename
@@ -329,6 +324,7 @@ def magic_file(cookie, filename):
329324def magic_buffer (cookie , buf ):
330325 return _magic_buffer (cookie , buf , len (buf ))
331326
327+
332328magic_descriptor = libmagic .magic_descriptor
333329magic_descriptor .restype = c_char_p
334330magic_descriptor .argtypes = [magic_t , c_int ]
@@ -379,73 +375,78 @@ def magic_load(cookie, filename):
379375 _magic_getparam .argtypes = [magic_t , c_int , POINTER (c_size_t )]
380376 _magic_getparam .errcheck = errorcheck_negative_one
381377
378+
382379def magic_setparam (cookie , param , val ):
383380 if not _has_param :
384381 raise NotImplementedError ("magic_setparam not implemented" )
385382 v = c_size_t (val )
386383 return _magic_setparam (cookie , param , byref (v ))
387384
385+
388386def magic_getparam (cookie , param ):
389387 if not _has_param :
390388 raise NotImplementedError ("magic_getparam not implemented" )
391389 val = c_size_t ()
392390 _magic_getparam (cookie , param , byref (val ))
393391 return val .value
394392
393+
395394_has_version = False
396395if hasattr (libmagic , "magic_version" ):
397396 _has_version = True
398397 magic_version = libmagic .magic_version
399398 magic_version .restype = c_int
400399 magic_version .argtypes = []
401400
401+
402402def version ():
403403 if not _has_version :
404404 raise NotImplementedError ("magic_version not implemented" )
405405 return magic_version ()
406406
407- MAGIC_NONE = 0x000000 # No flags
408- MAGIC_DEBUG = 0x000001 # Turn on debugging
409- MAGIC_SYMLINK = 0x000002 # Follow symlinks
410- MAGIC_COMPRESS = 0x000004 # Check inside compressed files
411- MAGIC_DEVICES = 0x000008 # Look at the contents of devices
412- MAGIC_MIME_TYPE = 0x000010 # Return a mime string
413- MAGIC_MIME_ENCODING = 0x000400 # Return the MIME encoding
407+
408+ MAGIC_NONE = 0x000000 # No flags
409+ MAGIC_DEBUG = 0x000001 # Turn on debugging
410+ MAGIC_SYMLINK = 0x000002 # Follow symlinks
411+ MAGIC_COMPRESS = 0x000004 # Check inside compressed files
412+ MAGIC_DEVICES = 0x000008 # Look at the contents of devices
413+ MAGIC_MIME_TYPE = 0x000010 # Return a mime string
414+ MAGIC_MIME_ENCODING = 0x000400 # Return the MIME encoding
414415# TODO: should be
415416# MAGIC_MIME = MAGIC_MIME_TYPE | MAGIC_MIME_ENCODING
416- MAGIC_MIME = 0x000010 # Return a mime string
417- MAGIC_EXTENSION = 0x1000000 # Return a /-separated list of extensions
418-
419- MAGIC_CONTINUE = 0x000020 # Return all matches
420- MAGIC_CHECK = 0x000040 # Print warnings to stderr
421- MAGIC_PRESERVE_ATIME = 0x000080 # Restore access time on exit
422- MAGIC_RAW = 0x000100 # Don't translate unprintable chars
423- MAGIC_ERROR = 0x000200 # Handle ENOENT etc as real errors
424-
425- MAGIC_NO_CHECK_COMPRESS = 0x001000 # Don't check for compressed files
426- MAGIC_NO_CHECK_TAR = 0x002000 # Don't check for tar files
427- MAGIC_NO_CHECK_SOFT = 0x004000 # Don't check magic entries
428- MAGIC_NO_CHECK_APPTYPE = 0x008000 # Don't check application type
429- MAGIC_NO_CHECK_ELF = 0x010000 # Don't check for elf details
430- MAGIC_NO_CHECK_ASCII = 0x020000 # Don't check for ascii files
431- MAGIC_NO_CHECK_TROFF = 0x040000 # Don't check ascii/troff
432- MAGIC_NO_CHECK_FORTRAN = 0x080000 # Don't check ascii/fortran
433- MAGIC_NO_CHECK_TOKENS = 0x100000 # Don't check ascii/tokens
434-
435- MAGIC_PARAM_INDIR_MAX = 0 # Recursion limit for indirect magic
436- MAGIC_PARAM_NAME_MAX = 1 # Use count limit for name/use magic
437- MAGIC_PARAM_ELF_PHNUM_MAX = 2 # Max ELF notes processed
438- MAGIC_PARAM_ELF_SHNUM_MAX = 3 # Max ELF program sections processed
439- MAGIC_PARAM_ELF_NOTES_MAX = 4 # # Max ELF sections processed
440- MAGIC_PARAM_REGEX_MAX = 5 # Length limit for regex searches
441- MAGIC_PARAM_BYTES_MAX = 6 # Max number of bytes to read from file
417+ MAGIC_MIME = 0x000010 # Return a mime string
418+ MAGIC_EXTENSION = 0x1000000 # Return a /-separated list of extensions
419+
420+ MAGIC_CONTINUE = 0x000020 # Return all matches
421+ MAGIC_CHECK = 0x000040 # Print warnings to stderr
422+ MAGIC_PRESERVE_ATIME = 0x000080 # Restore access time on exit
423+ MAGIC_RAW = 0x000100 # Don't translate unprintable chars
424+ MAGIC_ERROR = 0x000200 # Handle ENOENT etc as real errors
425+
426+ MAGIC_NO_CHECK_COMPRESS = 0x001000 # Don't check for compressed files
427+ MAGIC_NO_CHECK_TAR = 0x002000 # Don't check for tar files
428+ MAGIC_NO_CHECK_SOFT = 0x004000 # Don't check magic entries
429+ MAGIC_NO_CHECK_APPTYPE = 0x008000 # Don't check application type
430+ MAGIC_NO_CHECK_ELF = 0x010000 # Don't check for elf details
431+ MAGIC_NO_CHECK_ASCII = 0x020000 # Don't check for ascii files
432+ MAGIC_NO_CHECK_TROFF = 0x040000 # Don't check ascii/troff
433+ MAGIC_NO_CHECK_FORTRAN = 0x080000 # Don't check ascii/fortran
434+ MAGIC_NO_CHECK_TOKENS = 0x100000 # Don't check ascii/tokens
435+
436+ MAGIC_PARAM_INDIR_MAX = 0 # Recursion limit for indirect magic
437+ MAGIC_PARAM_NAME_MAX = 1 # Use count limit for name/use magic
438+ MAGIC_PARAM_ELF_PHNUM_MAX = 2 # Max ELF notes processed
439+ MAGIC_PARAM_ELF_SHNUM_MAX = 3 # Max ELF program sections processed
440+ MAGIC_PARAM_ELF_NOTES_MAX = 4 # # Max ELF sections processed
441+ MAGIC_PARAM_REGEX_MAX = 5 # Length limit for regex searches
442+ MAGIC_PARAM_BYTES_MAX = 6 # Max number of bytes to read from file
443+
442444
443445# This package name conflicts with the one provided by upstream
444446# libmagic. This is a common source of confusion for users. To
445447# resolve, We ship a copy of that module, and expose it's functions
446448# wrapped in deprecation warnings.
447449def add_compat (to_module ):
448-
449450 import warnings , re
450451 from magic import compat
451452
@@ -456,6 +457,7 @@ def _(*args, **kwargs):
456457 DeprecationWarning )
457458
458459 return compat [fn ](* args , ** kwargs )
460+
459461 return _
460462
461463 fn = [('detect_from_filename' , 'magic.from_file' ),
@@ -466,7 +468,7 @@ def _(*args, **kwargs):
466468 # for now, disable the deprecation warning until theres clarity on
467469 # what the merged module should look like
468470 to_module [fname ] = compat .__dict__ .get (fname )
469- #to_module[fname] = deprecation_wrapper(compat.__dict__, fname, alternate)
471+ # to_module[fname] = deprecation_wrapper(compat.__dict__, fname, alternate)
470472
471473 # copy constants over, ensuring there's no conflicts
472474 is_const_re = re .compile ("^[A-Z_]+$" )
@@ -483,4 +485,5 @@ def _(*args, **kwargs):
483485 else :
484486 to_module [name ] = value
485487
488+
486489add_compat (globals ())
0 commit comments