refactor: improve error handling for .gitignore file operations

This commit is contained in:
Paul Gauthier (aider) 2024-11-26 15:01:50 -08:00
parent f45533e20b
commit 3ba4aca268

View file

@ -157,13 +157,17 @@ def check_gitignore(git_root, io, ask=True):
gitignore_file = Path(git_root) / ".gitignore" gitignore_file = Path(git_root) / ".gitignore"
if gitignore_file.exists(): if gitignore_file.exists():
content = io.read_text(gitignore_file) try:
if content is None: content = io.read_text(gitignore_file)
if content is None:
return
existing_lines = content.splitlines()
for pat in patterns:
if pat not in existing_lines:
patterns_to_add.append(pat)
except OSError as e:
io.tool_error(f"Error when trying to read {gitignore_file}: {e}")
return return
existing_lines = content.splitlines()
for pat in patterns:
if pat not in existing_lines:
patterns_to_add.append(pat)
else: else:
content = "" content = ""
patterns_to_add = patterns patterns_to_add = patterns
@ -181,8 +185,8 @@ def check_gitignore(git_root, io, ask=True):
try: try:
io.write_text(gitignore_file, content) io.write_text(gitignore_file, content)
io.tool_output(f"Added {', '.join(patterns_to_add)} to .gitignore") io.tool_output(f"Added {', '.join(patterns_to_add)} to .gitignore")
except PermissionError: except OSError as e:
io.tool_error(f"Permission denied when trying to write to {gitignore_file}") io.tool_error(f"Error when trying to write to {gitignore_file}: {e}")
io.tool_output( io.tool_output(
"Try running with appropriate permissions or manually add these patterns to .gitignore:" "Try running with appropriate permissions or manually add these patterns to .gitignore:"
) )