Apply a context patch to an existing text file.
(path: str, patch_text: str)
| 370 | |
| 371 | |
| 372 | def apply_context_patch_file(path: str, patch_text: str) -> ContextPatchFileResult: |
| 373 | """Apply a context patch to an existing text file.""" |
| 374 | path = os.path.expanduser(path) |
| 375 | if not os.path.isfile(path): |
| 376 | raise FileNotFoundError("file not found") |
| 377 | |
| 378 | with open(path, "r", encoding="utf-8", errors="replace") as src: |
| 379 | content = src.read() |
| 380 | |
| 381 | result = apply_context_patch_with_metadata(content, patch_text) |
| 382 | dir_name = os.path.dirname(path) or "." |
| 383 | fd, tmp_path = tempfile.mkstemp(dir=dir_name, suffix=".tmp") |
| 384 | try: |
| 385 | with os.fdopen(fd, "w", encoding="utf-8") as dst: |
| 386 | dst.write(result.content) |
| 387 | shutil.move(tmp_path, path) |
| 388 | except Exception: |
| 389 | if os.path.exists(tmp_path): |
| 390 | os.unlink(tmp_path) |
| 391 | raise |
| 392 | |
| 393 | return ContextPatchFileResult( |
| 394 | total_lines=_count_content_lines(result.content), |
| 395 | hunk_count=result.hunk_count, |
| 396 | line_from=result.line_from, |
| 397 | line_to=result.line_to, |
| 398 | ) |
| 399 | |
| 400 | |
| 401 | def apply_exact_replace_file( |