Prevent fd leak if copystat fails

This commit is contained in:
Kovid Goyal 2021-07-16 08:46:04 +05:30
parent 040a152f1f
commit 01ce0e1d1a
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C

View file

@ -24,8 +24,8 @@
def atomic_write(path: str, data: Union[str, bytes]) -> None:
mode = 'w' + ('b' if isinstance(data, bytes) else '')
fd, tpath = mkstemp(dir=os.path.dirname(path), text=isinstance(data, str))
shutil.copystat(path, tpath)
with open(fd, mode) as f:
shutil.copystat(path, tpath)
f.write(data)
os.rename(tpath, path)