Merge pull request #2253 from justvanrossum/fix-536

[ttLib] TTFont.save: create file on disk as late as possible
This commit is contained in:
Just van Rossum 2021-03-31 20:27:22 +02:00 committed by GitHub
commit 21826f52dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -161,22 +161,17 @@ class TTFont(object):
if self.lazy and self.reader.file.name == file: if self.lazy and self.reader.file.name == file:
raise TTLibError( raise TTLibError(
"Can't overwrite TTFont when 'lazy' attribute is True") "Can't overwrite TTFont when 'lazy' attribute is True")
closeStream = True createStream = True
file = open(file, "wb")
else: else:
# assume "file" is a writable file object # assume "file" is a writable file object
closeStream = False createStream = False
tmp = BytesIO() tmp = BytesIO()
writer_reordersTables = self._save(tmp) writer_reordersTables = self._save(tmp)
if (reorderTables is None or writer_reordersTables or if not (reorderTables is None or writer_reordersTables or
(reorderTables is False and self.reader is None)): (reorderTables is False and self.reader is None)):
# don't reorder tables and save as is
file.write(tmp.getvalue())
tmp.close()
else:
if reorderTables is False: if reorderTables is False:
# sort tables using the original font's order # sort tables using the original font's order
tableOrder = list(self.reader.keys()) tableOrder = list(self.reader.keys())
@ -186,12 +181,17 @@ class TTFont(object):
tmp.flush() tmp.flush()
tmp2 = BytesIO() tmp2 = BytesIO()
reorderFontTables(tmp, tmp2, tableOrder) reorderFontTables(tmp, tmp2, tableOrder)
file.write(tmp2.getvalue())
tmp.close() tmp.close()
tmp2.close() tmp = tmp2
if closeStream: if createStream:
file.close() # "file" is a path
with open(file, "wb") as file:
file.write(tmp.getvalue())
else:
file.write(tmp.getvalue())
tmp.close()
def _save(self, file, tableCache=None): def _save(self, file, tableCache=None):
"""Internal function, to be shared by save() and TTCollection.save()""" """Internal function, to be shared by save() and TTCollection.save()"""