mirror of
https://github.com/ArchiveBox/ArchiveBox.git
synced 2025-05-13 06:34:25 -04:00
switch to atomic disk writes for all index operations
This commit is contained in:
parent
a214bd7c02
commit
d2a34f2602
2 changed files with 47 additions and 33 deletions
|
@ -670,3 +670,22 @@ class ExtendedEncoder(JSONEncoder):
|
|||
return tuple(obj)
|
||||
|
||||
return JSONEncoder.default(self, obj)
|
||||
|
||||
|
||||
def atomic_write(contents: Union[dict, str], path: str):
|
||||
"""Safe atomic file write and swap using a tmp file"""
|
||||
try:
|
||||
tmp_file = '{}.tmp'.format(path)
|
||||
with open(tmp_file, 'w+', encoding='utf-8') as f:
|
||||
if isinstance(contents, dict):
|
||||
json.dump(contents, f, indent=4, cls=ExtendedEncoder)
|
||||
else:
|
||||
f.write(contents)
|
||||
|
||||
os.fsync(f.fileno())
|
||||
|
||||
os.rename(tmp_file, path)
|
||||
chmod_file(path)
|
||||
finally:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue