Skip to content

Commit 62bd3c6

Browse files
committed
format with ruff
1 parent 5a89644 commit 62bd3c6

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
@@ -101,7 +116,9 @@ def __init__(self, mime=False, magic_file=None, mime_encoding=False,
101116
# MAGIC_EXTENSION was added in 523 or 524, so bail if
102117
# it doesn't appear to be available
103118
if extension and (not _has_version or version() < 524):
104-
raise NotImplementedError('MAGIC_EXTENSION is not supported in this version of libmagic')
119+
raise NotImplementedError(
120+
"MAGIC_EXTENSION is not supported in this version of libmagic"
121+
)
105122

106123
# For https://github.com/ahupp/python-magic/issues/190
107124
# libmagic has fixed internal limits that some files exceed, causing
@@ -128,7 +145,7 @@ def from_buffer(self, buf):
128145
# which is not what libmagic expects
129146
# NEXTBREAK: only take bytes
130147
if type(buf) == str and str != bytes:
131-
buf = buf.encode('utf-8', errors='replace')
148+
buf = buf.encode("utf-8", errors="replace")
132149
return maybe_decode(magic_buffer(self.cookie, buf))
133150
except MagicException as e:
134151
return self._handle509Bug(e)
@@ -176,7 +193,7 @@ def __del__(self):
176193
# incorrect fix for a threading problem, however I'm leaving
177194
# it in because it's harmless and I'm slightly afraid to
178195
# remove it.
179-
if hasattr(self, 'cookie') and self.cookie and magic_close:
196+
if hasattr(self, "cookie") and self.cookie and magic_close:
180197
magic_close(self.cookie)
181198
self.cookie = None
182199

@@ -192,7 +209,7 @@ def _get_magic_type(mime):
192209

193210

194211
def from_file(filename, mime=False):
195-
""""
212+
"""
196213
Accepts a filename and returns the detected filetype. Return
197214
value is the mimetype if mime=True, otherwise a human readable
198215
name.
@@ -230,7 +247,9 @@ def from_descriptor(fd, mime=False):
230247
m = _get_magic_type(mime)
231248
return m.from_descriptor(fd)
232249

250+
233251
from . import loader
252+
234253
libmagic = loader.load_lib()
235254

236255
magic_t = ctypes.c_void_p
@@ -261,20 +280,23 @@ def maybe_decode(s):
261280
else:
262281
# backslashreplace here because sometimes libmagic will return metadata in the charset
263282
# of the file, which is unknown to us (e.g the title of a Word doc)
264-
return s.decode('utf-8', 'backslashreplace')
283+
return s.decode("utf-8", "backslashreplace")
265284

266285

267286
try:
268287
from os import PathLike
288+
269289
def unpath(filename):
270290
if isinstance(filename, PathLike):
271291
return filename.__fspath__()
272292
else:
273293
return filename
274294
except ImportError:
295+
275296
def unpath(filename):
276297
return filename
277298

299+
278300
def coerce_filename(filename):
279301
if filename is None:
280302
return None
@@ -286,12 +308,11 @@ def coerce_filename(filename):
286308
# then you'll get inconsistent behavior (crashes) depending on the user's
287309
# LANG environment variable
288310
# NEXTBREAK: remove
289-
is_unicode = (sys.version_info[0] <= 2 and
290-
isinstance(filename, unicode)) or \
291-
(sys.version_info[0] >= 3 and
292-
isinstance(filename, str))
311+
is_unicode = (sys.version_info[0] <= 2 and isinstance(filename, unicode)) or (
312+
sys.version_info[0] >= 3 and isinstance(filename, str)
313+
)
293314
if is_unicode:
294-
return filename.encode('utf-8', 'surrogateescape')
315+
return filename.encode("utf-8", "surrogateescape")
295316
else:
296317
return filename
297318

@@ -370,7 +391,7 @@ def magic_load(cookie, filename):
370391
magic_compile.argtypes = [magic_t, c_char_p]
371392

372393
_has_param = False
373-
if hasattr(libmagic, 'magic_setparam') and hasattr(libmagic, 'magic_getparam'):
394+
if hasattr(libmagic, "magic_setparam") and hasattr(libmagic, "magic_getparam"):
374395
_has_param = True
375396
_magic_setparam = libmagic.magic_setparam
376397
_magic_setparam.restype = c_int
@@ -443,8 +464,8 @@ def version():
443464
MAGIC_NO_CHECK_CDF = 0x0040000 # Don't check for CDF files
444465
MAGIC_NO_CHECK_CSV = 0x0080000 # Don't check for CSV files
445466
MAGIC_NO_CHECK_ENCODING = 0x0200000 # Don't check text encodings
446-
MAGIC_NO_CHECK_JSON = 0x0400000 # Don't check for JSON files
447-
MAGIC_NO_CHECK_SIMH = 0x0800000 # Don't check for SIMH tape files
467+
MAGIC_NO_CHECK_JSON = 0x0400000 # Don't check for JSON files
468+
MAGIC_NO_CHECK_SIMH = 0x0800000 # Don't check for SIMH tape files
448469

449470
MAGIC_PARAM_INDIR_MAX = 0 # Recursion limit for indirect magic
450471
MAGIC_PARAM_NAME_MAX = 1 # Use count limit for name/use magic
@@ -468,22 +489,20 @@ def _(*args, **kwargs):
468489
warnings.warn(
469490
"Using compatibility mode with libmagic's python binding. "
470491
"See https://github.com/ahupp/python-magic/blob/master/COMPAT.md for details.",
471-
PendingDeprecationWarning)
492+
PendingDeprecationWarning,
493+
)
472494

473495
return fn(*args, **kwargs)
474496

475497
return _
476498

477-
fn = ['detect_from_filename',
478-
'detect_from_content',
479-
'detect_from_fobj',
480-
'open']
499+
fn = ["detect_from_filename", "detect_from_content", "detect_from_fobj", "open"]
481500
for fname in fn:
482501
to_module[fname] = deprecation_wrapper(compat.__dict__[fname])
483502

484503
# copy constants over, ensuring there's no conflicts
485504
is_const_re = re.compile("^[A-Z_]+$")
486-
allowed_inconsistent = set(['MAGIC_MIME'])
505+
allowed_inconsistent = set(["MAGIC_MIME"])
487506
for name, value in compat.__dict__.items():
488507
if is_const_re.match(name):
489508
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)