Skip to content

Commit c8a599b

Browse files
committed
Merge branch 'master' of https://github.com/ahupp/python-magic into abi3-wheels
* 'master' of https://github.com/ahupp/python-magic: format with ruff
2 parents 2bb9fa8 + 62bd3c6 commit c8a599b

4 files changed

Lines changed: 78 additions & 36 deletions

File tree

magic/__init__.py

Lines changed: 44 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,27 @@ class Magic:
3838
Magic is a wrapper around the libmagic C library.
3939
"""
4040

41-
def __init__(self, mime=False, magic_file=None, mime_encoding=False,
42-
keep_going=False, uncompress=False, raw=False, extension=False,
43-
follow_symlinks=False, check_tar=True, check_soft=True,
44-
check_apptype=True, check_elf=True, check_text=True,
45-
check_cdf=True, check_csv=True, check_encoding=True,
46-
check_json=True, check_simh=True):
41+
def __init__(
42+
self,
43+
mime=False,
44+
magic_file=None,
45+
mime_encoding=False,
46+
keep_going=False,
47+
uncompress=False,
48+
raw=False,
49+
extension=False,
50+
follow_symlinks=False,
51+
check_tar=True,
52+
check_soft=True,
53+
check_apptype=True,
54+
check_elf=True,
55+
check_text=True,
56+
check_cdf=True,
57+
check_csv=True,
58+
check_encoding=True,
59+
check_json=True,
60+
check_simh=True,
61+
):
4762
"""
4863
Create a new libmagic wrapper.
4964
@@ -107,7 +122,9 @@ def __init__(self, mime=False, magic_file=None, mime_encoding=False,
107122
# MAGIC_EXTENSION was added in 523 or 524, so bail if
108123
# it doesn't appear to be available
109124
if extension and (not _has_version or version() < 524):
110-
raise NotImplementedError('MAGIC_EXTENSION is not supported in this version of libmagic')
125+
raise NotImplementedError(
126+
"MAGIC_EXTENSION is not supported in this version of libmagic"
127+
)
111128

112129
# For https://github.com/ahupp/python-magic/issues/190
113130
# libmagic has fixed internal limits that some files exceed, causing
@@ -134,7 +151,7 @@ def from_buffer(self, buf):
134151
# which is not what libmagic expects
135152
# NEXTBREAK: only take bytes
136153
if type(buf) == str and str != bytes:
137-
buf = buf.encode('utf-8', errors='replace')
154+
buf = buf.encode("utf-8", errors="replace")
138155
return maybe_decode(magic_buffer(self.cookie, buf))
139156
except MagicException as e:
140157
return self._handle509Bug(e)
@@ -182,7 +199,7 @@ def __del__(self):
182199
# incorrect fix for a threading problem, however I'm leaving
183200
# it in because it's harmless and I'm slightly afraid to
184201
# remove it.
185-
if hasattr(self, 'cookie') and self.cookie and magic_close:
202+
if hasattr(self, "cookie") and self.cookie and magic_close:
186203
magic_close(self.cookie)
187204
self.cookie = None
188205

@@ -198,7 +215,7 @@ def _get_magic_type(mime):
198215

199216

200217
def from_file(filename, mime=False):
201-
""""
218+
"""
202219
Accepts a filename and returns the detected filetype. Return
203220
value is the mimetype if mime=True, otherwise a human readable
204221
name.
@@ -236,7 +253,9 @@ def from_descriptor(fd, mime=False):
236253
m = _get_magic_type(mime)
237254
return m.from_descriptor(fd)
238255

256+
239257
from . import loader
258+
240259
libmagic = loader.load_lib()
241260

242261
magic_t = ctypes.c_void_p
@@ -267,20 +286,23 @@ def maybe_decode(s):
267286
else:
268287
# backslashreplace here because sometimes libmagic will return metadata in the charset
269288
# of the file, which is unknown to us (e.g the title of a Word doc)
270-
return s.decode('utf-8', 'backslashreplace')
289+
return s.decode("utf-8", "backslashreplace")
271290

272291

273292
try:
274293
from os import PathLike
294+
275295
def unpath(filename):
276296
if isinstance(filename, PathLike):
277297
return filename.__fspath__()
278298
else:
279299
return filename
280300
except ImportError:
301+
281302
def unpath(filename):
282303
return filename
283304

305+
284306
def coerce_filename(filename):
285307
if filename is None:
286308
return None
@@ -292,12 +314,11 @@ def coerce_filename(filename):
292314
# then you'll get inconsistent behavior (crashes) depending on the user's
293315
# LANG environment variable
294316
# NEXTBREAK: remove
295-
is_unicode = (sys.version_info[0] <= 2 and
296-
isinstance(filename, unicode)) or \
297-
(sys.version_info[0] >= 3 and
298-
isinstance(filename, str))
317+
is_unicode = (sys.version_info[0] <= 2 and isinstance(filename, unicode)) or (
318+
sys.version_info[0] >= 3 and isinstance(filename, str)
319+
)
299320
if is_unicode:
300-
return filename.encode('utf-8', 'surrogateescape')
321+
return filename.encode("utf-8", "surrogateescape")
301322
else:
302323
return filename
303324

@@ -376,7 +397,7 @@ def magic_load(cookie, filename):
376397
magic_compile.argtypes = [magic_t, c_char_p]
377398

378399
_has_param = False
379-
if hasattr(libmagic, 'magic_setparam') and hasattr(libmagic, 'magic_getparam'):
400+
if hasattr(libmagic, "magic_setparam") and hasattr(libmagic, "magic_getparam"):
380401
_has_param = True
381402
_magic_setparam = libmagic.magic_setparam
382403
_magic_setparam.restype = c_int
@@ -449,8 +470,8 @@ def version():
449470
MAGIC_NO_CHECK_CDF = 0x0040000 # Don't check for CDF files
450471
MAGIC_NO_CHECK_CSV = 0x0080000 # Don't check for CSV files
451472
MAGIC_NO_CHECK_ENCODING = 0x0200000 # Don't check text encodings
452-
MAGIC_NO_CHECK_JSON = 0x0400000 # Don't check for JSON files
453-
MAGIC_NO_CHECK_SIMH = 0x0800000 # Don't check for SIMH tape files
473+
MAGIC_NO_CHECK_JSON = 0x0400000 # Don't check for JSON files
474+
MAGIC_NO_CHECK_SIMH = 0x0800000 # Don't check for SIMH tape files
454475

455476
MAGIC_PARAM_INDIR_MAX = 0 # Recursion limit for indirect magic
456477
MAGIC_PARAM_NAME_MAX = 1 # Use count limit for name/use magic
@@ -474,22 +495,20 @@ def _(*args, **kwargs):
474495
warnings.warn(
475496
"Using compatibility mode with libmagic's python binding. "
476497
"See https://github.com/ahupp/python-magic/blob/master/COMPAT.md for details.",
477-
PendingDeprecationWarning)
498+
PendingDeprecationWarning,
499+
)
478500

479501
return fn(*args, **kwargs)
480502

481503
return _
482504

483-
fn = ['detect_from_filename',
484-
'detect_from_content',
485-
'detect_from_fobj',
486-
'open']
505+
fn = ["detect_from_filename", "detect_from_content", "detect_from_fobj", "open"]
487506
for fname in fn:
488507
to_module[fname] = deprecation_wrapper(compat.__dict__[fname])
489508

490509
# copy constants over, ensuring there's no conflicts
491510
is_const_re = re.compile("^[A-Z_]+$")
492-
allowed_inconsistent = set(['MAGIC_MIME'])
511+
allowed_inconsistent = set(["MAGIC_MIME"])
493512
for name, value in compat.__dict__.items():
494513
if is_const_re.match(name):
495514
if name in to_module:

magic/__init__.pyi

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,25 @@ class Magic:
1111
flags: int = ...
1212
cookie: Any = ...
1313
lock: threading.Lock = ...
14-
def __init__(self, mime: bool = ..., magic_file: Optional[Any] = ..., mime_encoding: bool = ..., keep_going: bool = ..., uncompress: bool = ..., raw: bool = ..., extension: bool = ..., follow_symlinks: bool = ..., check_tar: bool = ..., check_soft: bool = ..., check_apptype: bool = ..., check_elf: bool = ..., check_text: bool = ..., check_encoding: bool = ..., check_json: bool = ..., check_simh: bool = ...) -> None: ...
14+
def __init__(
15+
self,
16+
mime: bool = ...,
17+
magic_file: Optional[Any] = ...,
18+
mime_encoding: bool = ...,
19+
keep_going: bool = ...,
20+
uncompress: bool = ...,
21+
raw: bool = ...,
22+
extension: bool = ...,
23+
follow_symlinks: bool = ...,
24+
check_tar: bool = ...,
25+
check_soft: bool = ...,
26+
check_apptype: bool = ...,
27+
check_elf: bool = ...,
28+
check_text: bool = ...,
29+
check_encoding: bool = ...,
30+
check_json: bool = ...,
31+
check_simh: bool = ...,
32+
) -> None: ...
1533
def from_buffer(self, buf: Union[bytes, str]) -> Text: ...
1634
def from_file(self, filename: Union[bytes, str, PathLike]) -> Text: ...
1735
def from_descriptor(self, fd: int, mime: bool = ...) -> Text: ...

ruff.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
exclude = ["magic/compat.py"]
2+
3+

test/libmagic_test.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,20 @@
66
import os.path
77

88
# magic_descriptor is broken (?) in centos 7, so don't run those tests
9-
SKIP_FROM_DESCRIPTOR = bool(os.environ.get('SKIP_FROM_DESCRIPTOR'))
9+
SKIP_FROM_DESCRIPTOR = bool(os.environ.get("SKIP_FROM_DESCRIPTOR"))
1010

11-
TESTDATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testdata'))
11+
TESTDATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "testdata"))
1212

1313

1414
class MagicTestCase(unittest.TestCase):
15-
filename = os.path.join(TESTDATA_DIR, 'test.pdf')
16-
expected_mime_type = 'application/pdf'
17-
expected_encoding = 'us-ascii'
18-
expected_name = ('PDF document, version 1.2', 'PDF document, version 1.2, 2 pages', 'PDF document, version 1.2, 2 page(s)')
15+
filename = os.path.join(TESTDATA_DIR, "test.pdf")
16+
expected_mime_type = "application/pdf"
17+
expected_encoding = "us-ascii"
18+
expected_name = (
19+
"PDF document, version 1.2",
20+
"PDF document, version 1.2, 2 pages",
21+
"PDF document, version 1.2, 2 page(s)",
22+
)
1923

2024
def assert_result(self, result):
2125
self.assertEqual(result.mime_type, self.expected_mime_type)
@@ -27,11 +31,9 @@ def test_detect_from_filename(self):
2731
self.assert_result(result)
2832

2933
def test_detect_from_fobj(self):
30-
3134
if SKIP_FROM_DESCRIPTOR:
3235
self.skipTest("magic_descriptor is broken in this version of libmagic")
3336

34-
3537
with open(self.filename) as fobj:
3638
result = magic.detect_from_fobj(fobj)
3739
self.assert_result(result)
@@ -41,10 +43,10 @@ def test_detect_from_content(self):
4143
# this avoids hitting a bug in python3+libfile bindings
4244
# see https://github.com/ahupp/python-magic/issues/152
4345
# for a similar issue
44-
with open(self.filename, 'rb') as fobj:
46+
with open(self.filename, "rb") as fobj:
4547
result = magic.detect_from_content(fobj.read(4096))
4648
self.assert_result(result)
4749

4850

49-
if __name__ == '__main__':
51+
if __name__ == "__main__":
5052
unittest.main()

0 commit comments

Comments
 (0)