1 """File utility functions."""
3 from __future__
import annotations
9 from atomicwrites
import AtomicWriter
13 _LOGGER = logging.getLogger(__name__)
17 """Error writing the data."""
21 filename: str, utf8_data: bytes | str, private: bool =
False, mode: str =
"w"
23 """Write a file and rename it into place using atomicwrites.
25 Writes all or nothing.
27 This function uses fsync under the hood. It should
28 only be used to write mission critical files as
29 fsync can block for a few seconds or longer is the
32 Using this function frequently will significantly
33 negatively impact performance.
36 with AtomicWriter(filename, mode=mode, overwrite=
True).
open()
as fdesc:
38 os.fchmod(fdesc.fileno(), 0o644)
39 fdesc.write(utf8_data)
40 except OSError
as error:
41 _LOGGER.exception(
"Saving file failed: %s", filename)
42 raise WriteError(error)
from error
46 filename: str, utf8_data: bytes | str, private: bool =
False, mode: str =
"w"
48 """Write a file and rename it into place.
50 Writes all or nothing.
53 encoding =
"utf-8" if "b" not in mode
else None
56 with tempfile.NamedTemporaryFile(
57 mode=mode, encoding=encoding, dir=os.path.dirname(filename), delete=
False
59 fdesc.write(utf8_data)
60 tmp_filename = fdesc.name
62 os.fchmod(fdesc.fileno(), 0o644)
63 os.replace(tmp_filename, filename)
64 except OSError
as error:
65 _LOGGER.exception(
"Saving file failed: %s", filename)
68 if os.path.exists(tmp_filename):
70 os.remove(tmp_filename)
71 except OSError
as err:
75 "File replacement cleanup failed for %s while saving %s: %s",
None open(self, **Any kwargs)
None write_utf8_file_atomic(str filename, bytes|str utf8_data, bool private=False, str mode="w")
None write_utf8_file(str filename, bytes|str utf8_data, bool private=False, str mode="w")