Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close file handle in preloadFont #131

Merged
merged 1 commit into from
Sep 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions pyfiglet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,30 +135,31 @@ def preloadFont(cls, font):
"""
# Find a plausible looking font file.
data = None
f = None
font_path = None
for extension in ('tlf', 'flf'):
fn = '%s.%s' % (font, extension)
path = importlib.resources.files('pyfiglet.fonts').joinpath(fn)
if path.exists():
f = path.open('rb')
font_path = path
break
else:
for location in ("./", SHARED_DIRECTORY):
full_name = os.path.join(location, fn)
if os.path.isfile(full_name):
f = open(full_name, 'rb')
font_path = pathlib.Path(full_name)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CI should now succeed.

The fix was replacing the string typed font_path with pathlib.Path objects . Line 141 already uses a Path object, which knows how to open files inside a Python .egg (where the test is taken fonts from), so we only needed to convert the string path in line 149 to a Path object so we can use its .open method in line 154.

break

# Unzip the first file if this file/stream looks like a ZIP file.
if f:
if zipfile.is_zipfile(f):
with zipfile.ZipFile(f) as zip_file:
zip_font = zip_file.open(zip_file.namelist()[0])
data = zip_font.read()
else:
# ZIP file check moves the current file pointer - reset to start of file.
f.seek(0)
data = f.read()
if font_path:
with font_path.open('rb') as f:
if zipfile.is_zipfile(f):
with zipfile.ZipFile(f) as zip_file:
zip_font = zip_file.open(zip_file.namelist()[0])
data = zip_font.read()
else:
# ZIP file check moves the current file pointer - reset to start of file.
f.seek(0)
data = f.read()

# Return the decoded data (if any).
if data:
Expand Down