Clover/tools/file_tools.py
Jarian Cottingham 7e8d31af6e Clover created
2026-01-13 00:07:41 -06:00

139 lines
3.9 KiB
Python

"""
File operation tools for Clover - A terminal assistant for AI-powered project management
"""
import os
import shutil
from pathlib import Path
def read_file(filepath):
"""
Read content from a file and return its contents.
Args:
filepath (str): Path to the file to read
Returns:
str: Content of the file
Raises:
FileNotFoundError: If the file does not exist
IOError: If there's an error reading the file
"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
return content
except FileNotFoundError:
raise FileNotFoundError(f"File '{filepath}' not found")
except Exception as e:
raise IOError(f"Error reading file '{filepath}': {str(e)}")
def create_file(filepath, content=""):
"""
Create a new file with specified content.
Args:
filepath (str): Path to the file to create
content (str): Content to write to the file
Returns:
bool: True if successful, False otherwise
"""
try:
# Create parent directories if they don't exist
Path(filepath).parent.mkdir(parents=True, exist_ok=True)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
return True
except Exception as e:
print(f"Error creating file '{filepath}': {str(e)}")
return False
def update_file(filepath, content="", start_line=None, end_line=None):
"""
Modify an existing file's content.
Args:
filepath (str): Path to the file to update
content (str): New content to insert
start_line (int): Starting line number (1-based) - optional
end_line (int): Ending line number (1-based) - optional
Returns:
bool: True if successful, False otherwise
"""
try:
# Read existing content
if os.path.exists(filepath):
with open(filepath, 'r', encoding='utf-8') as f:
lines = f.readlines()
else:
lines = []
# If specific line range is specified, replace that section
if start_line is not None and end_line is not None:
# Adjust for 0-based indexing
start_idx = max(0, start_line - 1)
end_idx = min(len(lines), end_line)
lines[start_idx:end_idx] = [content + '\n']
else:
# Append content at the end
lines.append(content + '\n')
# Write updated content back to file
with open(filepath, 'w', encoding='utf-8') as f:
f.writelines(lines)
return True
except Exception as e:
print(f"Error updating file '{filepath}': {str(e)}")
return False
def delete_file(filepath):
"""
Remove a file from the project.
Args:
filepath (str): Path to the file to delete
Returns:
bool: True if successful, False otherwise
"""
try:
if os.path.exists(filepath):
os.remove(filepath)
return True
else:
print(f"File '{filepath}' does not exist")
return False
except Exception as e:
print(f"Error deleting file '{filepath}': {str(e)}")
return False
def list_files(directory=".", recursive=False):
"""
List all files in a directory.
Args:
directory (str): Directory to list files from
recursive (bool): Whether to list recursively
Returns:
list: List of file paths
"""
try:
if recursive:
files = []
for root, dirs, filenames in os.walk(directory):
for filename in filenames:
files.append(os.path.join(root, filename))
return files
else:
return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
except Exception as e:
print(f"Error listing files in '{directory}': {str(e)}")
return []