Skip to content

Commit 10914ce

Browse files
committed
Clean up loader.py
1 parent fc7ebc0 commit 10914ce

1 file changed

Lines changed: 48 additions & 30 deletions

File tree

magic/loader.py

Lines changed: 48 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -4,47 +4,65 @@
44
import glob
55
import os.path
66

7-
def _lib_candidates():
87

9-
yield find_library('magic')
8+
def _lib_candidates_linux():
9+
"""Yield possible libmagic library names on Linux.
10+
11+
This is necessary because alpine is bad
12+
"""
13+
yield "libmagic.so.1"
1014

11-
if sys.platform == 'darwin':
1215

16+
def _lib_candidates_macos():
17+
"""Yield possible libmagic library names on macOS."""
1318
paths = [
14-
'/opt/local/lib',
15-
'/usr/local/lib',
16-
'/opt/homebrew/lib',
17-
] + glob.glob('/usr/local/Cellar/libmagic/*/lib')
19+
"/opt/homebrew/lib",
20+
"/opt/local/lib",
21+
"/usr/local/lib",
22+
] + glob.glob("/usr/local/Cellar/libmagic/*/lib")
23+
for path in paths:
24+
yield os.path.join(path, "libmagic.dylib")
1825

19-
for i in paths:
20-
yield os.path.join(i, 'libmagic.dylib')
2126

22-
elif sys.platform in ('win32', 'cygwin'):
27+
def _lib_candidates_windows():
28+
"""Yield possible libmagic library names on Windows."""
29+
prefixes = (
30+
"libmagic",
31+
"magic1",
32+
"magic-1",
33+
"cygmagic-1",
34+
"libmagic-1",
35+
"msys-magic-1",
36+
)
37+
for prefix in prefixes:
38+
# find_library searches in %PATH% but not the current directory,
39+
# so look for both
40+
yield "./%s.dll" % (prefix,)
41+
yield find_library(prefix)
2342

24-
prefixes = ['libmagic', 'magic1', 'magic-1', 'cygmagic-1', 'libmagic-1', 'msys-magic-1']
2543

26-
for i in prefixes:
27-
# find_library searches in %PATH% but not the current directory,
28-
# so look for both
29-
yield './%s.dll' % (i,)
30-
yield find_library(i)
44+
def _lib_candidates():
45+
yield find_library("magic")
3146

32-
elif sys.platform == 'linux':
33-
# This is necessary because alpine is bad
34-
yield 'libmagic.so.1'
47+
func = {
48+
"cygwin": _lib_candidates_windows,
49+
"darwin": _lib_candidates_macos,
50+
"linux": _lib_candidates_linux,
51+
"win32": _lib_candidates_windows,
52+
}[sys.platform]
53+
# When we drop legacy Python, we can just `yield from func()`
54+
for path in func():
55+
yield path
3556

3657

3758
def load_lib():
59+
for lib in _lib_candidates():
60+
# find_library returns None when lib not found
61+
if lib:
62+
try:
63+
return ctypes.CDLL(lib)
64+
except OSError:
65+
pass
3866

39-
for lib in _lib_candidates():
40-
# find_library returns None when lib not found
41-
if lib is None:
42-
continue
43-
try:
44-
return ctypes.CDLL(lib)
45-
except OSError:
46-
pass
47-
else:
4867
# It is better to raise an ImportError since we are importing magic module
49-
raise ImportError('failed to find libmagic. Check your installation')
50-
68+
raise ImportError("failed to find libmagic. Check your installation")

0 commit comments

Comments
 (0)