🐛 Fix unicode vs bytes issues for atomic_write

NamedTemporaryFile doesn't support the encoding parameter under py2.
However, without it specifying text mode defaults to ascii, causing some
issues especially with config files containing utf-8.

By swapping NamedTemporaryFile for mkstemp and a custom io.open call
(parameterized according to the open mode) we can support a proper
encoding aware atomic_write.
This commit is contained in:
Gina Häußge committed 2019-02-06 16:03:32 +01:00
1 parent 496e9f0ec4
commit 09cc7cf5f7
4 files changed
+124 -53

No files matched your search

+2 -2
View File
@@ -1539,7 +1539,7 @@ class LocalFileStorage(StorageInterface):
metadata_path = os.path.join(path, ".metadata.json")
try:
import json
with atomic_write(metadata_path, mode='wt') as f:
with atomic_write(metadata_path, mode='wb') as f:
json.dump(metadata, f, indent=4, separators=(",", ": "))
except Exception:
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
@@ -1588,7 +1588,7 @@ class LocalFileStorage(StorageInterface):
# looks invalid, ignore it
return
with atomic_write(metadata_path_json, mode='wt') as f:
with atomic_write(metadata_path_json, mode='wb') as f:
json.dump(metadata, f, indent=4, separators=(",", ": "))
# TODO 1.3.10 Remove ".metadata.yaml" files
+1 -1
View File
@@ -1772,7 +1772,7 @@ class Settings(object):
path, _ = os.path.split(filename)
if not os.path.exists(path):
os.makedirs(path)
with atomic_write(filename, mode='wb', max_permissions=0o666) as f:
with atomic_write(filename, mode='wt', max_permissions=0o666) as f:
f.write(script)
def generateApiKey(self):
+10 -2
View File
@@ -1007,12 +1007,20 @@ def mime_type_matches(mime, other):
return type_matches and subtype_matches
@contextlib.contextmanager
def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777):
def atomic_write(filename, mode="w+b", encoding="utf-8", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777):
if os.path.exists(filename):
permissions |= os.stat(filename).st_mode
permissions &= max_permissions
temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False)
# NamedTemporaryFile doesn't yet have an encoding parameter in py2, so we go the long way
fd, path = tempfile.mkstemp(suffix=suffix, prefix=prefix)
os.close(fd)
if "b" in mode:
temp_config = io.open(path, mode=mode)
else:
temp_config = io.open(path, mode=mode, encoding=encoding)
try:
yield temp_config
finally: