1 file changed
@@ -3,6 +3,7 @@ | |||
| 3 | 3 | ||
| 4 | 4 | """Index utilities.""" | |
| 5 | 5 | ||
| 6 | + import contextlib | ||
| 6 | 7 | from functools import wraps | |
| 7 | 8 | import os | |
| 8 | 9 | import os.path as osp | |
@@ -40,12 +41,10 @@ class TemporaryFileSwap: | |||
| 40 | 41 | ||
| 41 | 42 | def __init__(self, file_path: PathLike) -> None: | |
| 42 | 43 | self.file_path = file_path | |
| 43 | - self.tmp_file_path = str(self.file_path) + tempfile.mktemp("", "", "") | ||
| 44 | - # It may be that the source does not exist. | ||
| 45 | - try: | ||
| 46 | - os.rename(self.file_path, self.tmp_file_path) | ||
| 47 | - except OSError: | ||
| 48 | - pass | ||
| 44 | + fd, self.tmp_file_path = tempfile.mkstemp(prefix=self.file_path, dir="") | ||
| 45 | + os.close(fd) | ||
| 46 | + with contextlib.suppress(OSError): # It may be that the source does not exist. | ||
| 47 | + os.replace(self.file_path, self.tmp_file_path) | ||
| 49 | 48 | ||
| 50 | 49 | def __enter__(self) -> "TemporaryFileSwap": | |
| 51 | 50 | return self | |
@@ -57,10 +56,7 @@ def __exit__( | |||
| 57 | 56 | exc_tb: Optional[TracebackType], | |
| 58 | 57 | ) -> bool: | |
| 59 | 58 | if osp.isfile(self.tmp_file_path): | |
| 60 | - if os.name == "nt" and osp.exists(self.file_path): | ||
| 61 | - os.remove(self.file_path) | ||
| 62 | - os.rename(self.tmp_file_path, self.file_path) | ||
| 63 | - | ||
| 59 | + os.replace(self.tmp_file_path, self.file_path) | ||
| 64 | 60 | return False | |
| 65 | 61 | ||
| 66 | 62 | ||
0 commit comments