Skip to content

Commit c0d0278

Browse files
committed
format with ruff
1 parent 36ecbf9 commit c0d0278

7 files changed

+202
-129
lines changed

magic/__init__.py

+45-25
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,24 @@ 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
294+
274295
except ImportError:
296+
275297
def unpath(filename):
276298
return filename
277299

300+
278301
def coerce_filename(filename):
279302
if filename is None:
280303
return None
@@ -286,12 +309,11 @@ def coerce_filename(filename):
286309
# then you'll get inconsistent behavior (crashes) depending on the user's
287310
# LANG environment variable
288311
# 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))
312+
is_unicode = (sys.version_info[0] <= 2 and isinstance(filename, unicode)) or (
313+
sys.version_info[0] >= 3 and isinstance(filename, str)
314+
)
293315
if is_unicode:
294-
return filename.encode('utf-8', 'surrogateescape')
316+
return filename.encode("utf-8", "surrogateescape")
295317
else:
296318
return filename
297319

@@ -370,7 +392,7 @@ def magic_load(cookie, filename):
370392
magic_compile.argtypes = [magic_t, c_char_p]
371393

372394
_has_param = False
373-
if hasattr(libmagic, 'magic_setparam') and hasattr(libmagic, 'magic_getparam'):
395+
if hasattr(libmagic, "magic_setparam") and hasattr(libmagic, "magic_getparam"):
374396
_has_param = True
375397
_magic_setparam = libmagic.magic_setparam
376398
_magic_setparam.restype = c_int
@@ -443,8 +465,8 @@ def version():
443465
MAGIC_NO_CHECK_CDF = 0x0040000 # Don't check for CDF files
444466
MAGIC_NO_CHECK_CSV = 0x0080000 # Don't check for CSV files
445467
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
468+
MAGIC_NO_CHECK_JSON = 0x0400000 # Don't check for JSON files
469+
MAGIC_NO_CHECK_SIMH = 0x0800000 # Don't check for SIMH tape files
448470

449471
MAGIC_PARAM_INDIR_MAX = 0 # Recursion limit for indirect magic
450472
MAGIC_PARAM_NAME_MAX = 1 # Use count limit for name/use magic
@@ -468,22 +490,20 @@ def _(*args, **kwargs):
468490
warnings.warn(
469491
"Using compatibility mode with libmagic's python binding. "
470492
"See https://github.com/ahupp/python-magic/blob/master/COMPAT.md for details.",
471-
PendingDeprecationWarning)
493+
PendingDeprecationWarning,
494+
)
472495

473496
return fn(*args, **kwargs)
474497

475498
return _
476499

477-
fn = ['detect_from_filename',
478-
'detect_from_content',
479-
'detect_from_fobj',
480-
'open']
500+
fn = ["detect_from_filename", "detect_from_content", "detect_from_fobj", "open"]
481501
for fname in fn:
482502
to_module[fname] = deprecation_wrapper(compat.__dict__[fname])
483503

484504
# copy constants over, ensuring there's no conflicts
485505
is_const_re = re.compile("^[A-Z_]+$")
486-
allowed_inconsistent = set(['MAGIC_MIME'])
506+
allowed_inconsistent = set(["MAGIC_MIME"])
487507
for name, value in compat.__dict__.items():
488508
if is_const_re.match(name):
489509
if name in to_module:

magic/__init__.pyi

+19-1
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: ...

magic/loader.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
logger = logging.getLogger(__name__)
99

10+
1011
def _lib_candidates_linux():
1112
"""Yield possible libmagic library names on Linux.
1213

@@ -51,7 +52,7 @@ def _lib_candidates():
5152
"darwin": _lib_candidates_macos,
5253
"linux": _lib_candidates_linux,
5354
"win32": _lib_candidates_windows,
54-
"sunos5": _lib_candidates_linux,
55+
"sunos5": _lib_candidates_linux,
5556
}.get(sys.platform)
5657
if func is None:
5758
raise ImportError("python-magic: Unsupported platform: " + sys.platform)

ruff.toml

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
exclude = ["magic/compat.py"]

setup.py

+28-27
Original file line numberDiff line numberDiff line change
@@ -8,41 +8,42 @@
88

99
def read(file_name):
1010
"""Read a text file and return the content as a string."""
11-
with io.open(os.path.join(os.path.dirname(__file__), file_name),
12-
encoding='utf-8') as f:
11+
with io.open(
12+
os.path.join(os.path.dirname(__file__), file_name), encoding="utf-8"
13+
) as f:
1314
return f.read()
1415

16+
1517
setuptools.setup(
16-
name='python-magic',
17-
description='File type identification using libmagic',
18-
author='Adam Hupp',
19-
author_email='[email protected]',
18+
name="python-magic",
19+
description="File type identification using libmagic",
20+
author="Adam Hupp",
21+
author_email="[email protected]",
2022
url="http://github.com/ahupp/python-magic",
21-
version='0.4.28',
22-
long_description=read('README.md'),
23-
long_description_content_type='text/markdown',
24-
packages=['magic'],
23+
version="0.4.28",
24+
long_description=read("README.md"),
25+
long_description_content_type="text/markdown",
26+
packages=["magic"],
2527
package_data={
26-
'magic': ['py.typed', '*.pyi', '**/*.pyi'],
28+
"magic": ["py.typed", "*.pyi", "**/*.pyi"],
2729
},
2830
keywords="mime magic file",
2931
license="MIT",
30-
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*',
32+
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",
3133
classifiers=[
32-
'Intended Audience :: Developers',
33-
'License :: OSI Approved :: MIT License',
34-
'Programming Language :: Python',
35-
'Programming Language :: Python :: 2.7',
36-
'Programming Language :: Python :: 3',
37-
'Programming Language :: Python :: 3.5',
38-
'Programming Language :: Python :: 3.6',
39-
'Programming Language :: Python :: 3.7',
40-
'Programming Language :: Python :: 3.8',
41-
'Programming Language :: Python :: 3.9',
42-
'Programming Language :: Python :: 3.10',
43-
'Programming Language :: Python :: 3.11',
44-
'Programming Language :: Python :: 3.12',
45-
'Programming Language :: Python :: Implementation :: CPython',
34+
"Intended Audience :: Developers",
35+
"License :: OSI Approved :: MIT License",
36+
"Programming Language :: Python",
37+
"Programming Language :: Python :: 2.7",
38+
"Programming Language :: Python :: 3",
39+
"Programming Language :: Python :: 3.5",
40+
"Programming Language :: Python :: 3.6",
41+
"Programming Language :: Python :: 3.7",
42+
"Programming Language :: Python :: 3.8",
43+
"Programming Language :: Python :: 3.9",
44+
"Programming Language :: Python :: 3.10",
45+
"Programming Language :: Python :: 3.11",
46+
"Programming Language :: Python :: 3.12",
47+
"Programming Language :: Python :: Implementation :: CPython",
4648
],
4749
)
48-

test/libmagic_test.py

+12-10
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)