-
Notifications
You must be signed in to change notification settings - Fork 109
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
3 changed files
with
44 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# -*- coding=UTF-8 -*- | ||
# pyright: strict | ||
|
||
from __future__ import annotations | ||
|
||
import contextlib | ||
import os | ||
from typing import Text | ||
|
||
|
||
def force_rename(src: Text, dst: Text): | ||
try: | ||
os.rename(src, dst) | ||
except FileExistsError: | ||
os.unlink(dst) | ||
os.rename(src, dst) | ||
|
||
|
||
@contextlib.contextmanager | ||
def atomic_save_path( | ||
path: Text, | ||
*, | ||
temp_suffix: Text = ".tmp", | ||
backup_suffix: Text = "", | ||
): | ||
tmp_path = path + temp_suffix | ||
yield tmp_path | ||
if backup_suffix: | ||
backup_path = path + backup_suffix | ||
try: | ||
force_rename(path, backup_path) | ||
except FileNotFoundError: | ||
pass | ||
force_rename(tmp_path, path) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters