Merge pull request #2381 from mark-asymbl/write_text_file_lock_fix

Added io.py write_text exponential backoff to gracefully handle transient file locks
This commit is contained in:
paul-gauthier 2024-11-15 16:21:40 -08:00 committed by GitHub
commit 383bef456d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -333,14 +333,31 @@ class InputOutput:
self.tool_error("Use --encoding to set the unicode encoding.")
return
def write_text(self, filename, content):
def write_text(self, filename, content, max_retries=5, initial_delay=0.1):
"""
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 initial_delay: Initial delay (in seconds) before the first retry.
"""
if self.dry_run:
return
try:
with open(str(filename), "w", encoding=self.encoding) as f:
f.write(content)
except OSError as err:
self.tool_error(f"Unable to write file {filename}: {err}")
delay = initial_delay
for attempt in range(max_retries):
try:
with open(str(filename), "w", encoding=self.encoding) as f:
f.write(content)
return # Successfully wrote the file
except OSError as err:
if attempt < max_retries - 1:
time.sleep(delay)
delay *= 2 # Exponential backoff
else:
self.tool_error(f"Unable to write file {filename} after {max_retries} attempts: {err}")
raise
def rule(self):
if self.pretty: