Write a capture under a unique name without clobbering another writer.
(target_dir: Path, filename: str, content: str | Callable[[], bytes])
| 244 | |
| 245 | |
| 246 | def _write_capture(target_dir: Path, filename: str, content: str | Callable[[], bytes]) -> Path: |
| 247 | """Write a capture under a unique name without clobbering another writer.""" |
| 248 | out_path = _free_capture_path(target_dir, filename) |
| 249 | # Inspect the destination before fetching, and fetch at most once per capture. |
| 250 | payload = content() if callable(content) else content |
| 251 | if isinstance(payload, str): |
| 252 | # Preserve the newline translation of Path.write_text on Windows. |
| 253 | payload = payload.replace("\n", linesep).encode("utf-8") |
| 254 | while True: |
| 255 | try: |
| 256 | handle = out_path.open("xb") |
| 257 | except FileExistsError: |
| 258 | out_path = _free_capture_path(target_dir, filename) |
| 259 | continue |
| 260 | try: |
| 261 | with handle: |
| 262 | handle.write(payload) |
| 263 | except (OSError, UnicodeError): |
| 264 | with suppress(OSError): |
| 265 | out_path.unlink() |
| 266 | raise |
| 267 | return out_path |
| 268 | |
| 269 | |
| 270 | def _download_binary(url: str, suffix: str, target_dir: Path) -> Path: |
no test coverage detected