Skip to content

Commit

Permalink
Close file handle in preloadFont
Browse files Browse the repository at this point in the history
Commit 785f90a introduced a regression
by not using a context manager when opening the file, which eventually
lead to a resource leak because the file handle 'f' never gets closed.

This is fixed by passing the font path, instead of the open file handle,
and by opening the handle using a 'with' context manager.

The issue can be reproduced by running pytest with the '-W error' flag
for the following minimal example:

    def test_file_gets_closed():
        Figlet().renderText("")

This will succeed now, but fails for v1.0.1.
  • Loading branch information
anz-ableton committed Sep 12, 2023
1 parent d47fc46 commit e5ec554
Showing 1 changed file with 13 additions and 12 deletions.
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 = full_name
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 open(font_path, '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

0 comments on commit e5ec554

Please sign in to comment.