| 128 | |
| 129 | @contextmanager |
| 130 | def rewrite( |
| 131 | path: StrPath, |
| 132 | encoding: Optional[str], |
| 133 | ) -> Iterator[Tuple[IO[str], IO[str]]]: |
| 134 | if not os.path.isfile(path): |
| 135 | with open(path, mode="w", encoding=encoding) as source: |
| 136 | source.write("") |
| 137 | with tempfile.NamedTemporaryFile(mode="w", encoding=encoding, delete=False) as dest: |
| 138 | try: |
| 139 | with open(path, encoding=encoding) as source: |
| 140 | yield (source, dest) |
| 141 | except BaseException: |
| 142 | os.unlink(dest.name) |
| 143 | raise |
| 144 | shutil.move(dest.name, path) |
| 145 | |
| 146 | |
| 147 | def set_key( |