Writes content to a file, retrying with progressive backoff if the file is locked. :param filename: Path to the file to write. :param content: Content to write to the file. :param max_retries: Maximum number of retries if a file lock is encountered. :param i
(self, filename, content, max_retries=5, initial_delay=0.1)
| 476 | return |
| 477 | |
| 478 | def write_text(self, filename, content, max_retries=5, initial_delay=0.1): |
| 479 | """ |
| 480 | Writes content to a file, retrying with progressive backoff if the file is locked. |
| 481 | |
| 482 | :param filename: Path to the file to write. |
| 483 | :param content: Content to write to the file. |
| 484 | :param max_retries: Maximum number of retries if a file lock is encountered. |
| 485 | :param initial_delay: Initial delay (in seconds) before the first retry. |
| 486 | """ |
| 487 | if self.dry_run: |
| 488 | return |
| 489 | |
| 490 | delay = initial_delay |
| 491 | for attempt in range(max_retries): |
| 492 | try: |
| 493 | with open(str(filename), "w", encoding=self.encoding, newline=self.newline) as f: |
| 494 | f.write(content) |
| 495 | return # Successfully wrote the file |
| 496 | except PermissionError as err: |
| 497 | if attempt < max_retries - 1: |
| 498 | time.sleep(delay) |
| 499 | delay *= 2 # Exponential backoff |
| 500 | else: |
| 501 | self.tool_error( |
| 502 | f"Unable to write file {filename} after {max_retries} attempts: {err}" |
| 503 | ) |
| 504 | raise |
| 505 | except OSError as err: |
| 506 | self.tool_error(f"Unable to write file {filename}: {err}") |
| 507 | raise |
| 508 | |
| 509 | def rule(self): |
| 510 | if self.pretty: |