handle not found errors inside fileop (#1188)

This commit is contained in:
Robert Brennan 2024-04-18 07:16:48 -04:00 committed by GitHub
parent 1356da8795
commit 74c9b58d1b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -38,21 +38,24 @@ class FileReadAction(ExecutableAction):
async def run(self, controller) -> FileReadObservation:
path = resolve_path(self.path)
self.start = max(self.start, 0)
with open(path, 'r', encoding='utf-8') as file:
if self.end == -1:
if self.start == 0:
code_view = file.read()
try:
with open(path, 'r', encoding='utf-8') as file:
if self.end == -1:
if self.start == 0:
code_view = file.read()
else:
all_lines = file.readlines()
code_slice = all_lines[self.start:]
code_view = ''.join(code_slice)
else:
all_lines = file.readlines()
code_slice = all_lines[self.start:]
num_lines = len(all_lines)
begin = max(0, min(self.start, num_lines - 2))
end = -1 if self.end > num_lines else max(begin + 1, self.end)
code_slice = all_lines[begin:end]
code_view = ''.join(code_slice)
else:
all_lines = file.readlines()
num_lines = len(all_lines)
begin = max(0, min(self.start, num_lines - 2))
end = -1 if self.end > num_lines else max(begin + 1, self.end)
code_slice = all_lines[begin:end]
code_view = ''.join(code_slice)
except FileNotFoundError:
raise FileNotFoundError(f'File not found: {self.path}')
return FileReadObservation(path=path, content=code_view)
@property
@ -73,19 +76,22 @@ class FileWriteAction(ExecutableAction):
whole_path = resolve_path(self.path)
mode = 'w' if not os.path.exists(whole_path) else 'r+'
insert = self.content.split('\n')
with open(whole_path, mode, encoding='utf-8') as file:
if mode != 'w':
all_lines = file.readlines()
new_file = [''] if self.start == 0 else all_lines[:self.start]
new_file += [i + '\n' for i in insert]
new_file += [''] if self.end == -1 else all_lines[self.end:]
else:
new_file = insert
try:
with open(whole_path, mode, encoding='utf-8') as file:
if mode != 'w':
all_lines = file.readlines()
new_file = [''] if self.start == 0 else all_lines[:self.start]
new_file += [i + '\n' for i in insert]
new_file += [''] if self.end == -1 else all_lines[self.end:]
else:
new_file = insert
file.seek(0)
file.writelines(new_file)
file.truncate()
obs = f'WRITE OPERATION:\nYou have written to "{self.path}" on these lines: {self.start}:{self.end}.'
file.seek(0)
file.writelines(new_file)
file.truncate()
obs = f'WRITE OPERATION:\nYou have written to "{self.path}" on these lines: {self.start}:{self.end}.'
except FileNotFoundError:
raise FileNotFoundError(f'File not found: {self.path}')
return FileWriteObservation(content=obs + ''.join(new_file), path=self.path)
@property