372 lines
13 KiB
Python
372 lines
13 KiB
Python
import os
|
|
import shutil
|
|
from typing import Optional, List, Dict, Any
|
|
from langchain import tools
|
|
|
|
|
|
@tools.tool("read_file")
|
|
def read_file(file_path: str, start_line: Optional[int] = None, end_line: Optional[int] = None) -> str:
|
|
"""
|
|
Reads the content of a file and returns it as a string.
|
|
|
|
Args:
|
|
file_path: Path to the file to read
|
|
start_line: Starting line number (1-based, inclusive). If None, starts from the beginning.
|
|
end_line: Ending line number (1-based, inclusive). If None, reads to the end.
|
|
|
|
Returns:
|
|
The content of the file as a string
|
|
"""
|
|
try:
|
|
with open(file_path, 'r') as file:
|
|
lines = file.readlines()
|
|
|
|
# Convert 1-based to 0-based indexing
|
|
if start_line is not None:
|
|
start_idx = max(0, start_line - 1)
|
|
else:
|
|
start_idx = 0
|
|
|
|
if end_line is not None:
|
|
end_idx = end_line # end_line is already correct for slicing (1-based inclusive -> 0-based exclusive)
|
|
else:
|
|
end_idx = len(lines)
|
|
|
|
selected_lines = lines[start_idx:end_idx]
|
|
return ''.join(selected_lines)
|
|
except FileNotFoundError:
|
|
raise FileNotFoundError(f"File not found: {file_path}")
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied reading: {file_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error reading file '{file_path}': {str(e)}")
|
|
|
|
|
|
@tools.tool("write_file")
|
|
def write_file(file_path: str, content: str, overwrite: bool = False) -> str:
|
|
"""
|
|
Writes the given content to a file.
|
|
|
|
Args:
|
|
file_path: Path to the file to write
|
|
content: Content to write to the file
|
|
overwrite: If True, overwrites existing file. If False, raises error if file exists.
|
|
|
|
Returns:
|
|
Success message
|
|
"""
|
|
try:
|
|
# Ensure directory exists
|
|
dir_path = os.path.dirname(file_path)
|
|
if dir_path and not os.path.exists(dir_path):
|
|
os.makedirs(dir_path, exist_ok=True)
|
|
|
|
if os.path.exists(file_path) and not overwrite:
|
|
raise FileExistsError(
|
|
f"File '{file_path}' already exists. Set overwrite=True to replace it, "
|
|
"or use 'replace_in_file' to modify content."
|
|
)
|
|
|
|
with open(file_path, 'w') as file:
|
|
file.write(content)
|
|
|
|
return f"Successfully wrote to file: {file_path}"
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied writing to: {file_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error writing file '{file_path}': {str(e)}")
|
|
|
|
|
|
@tools.tool("replace_in_file")
|
|
def replace_in_file(file_path: str, old_content: str, new_content: str, count: int = -1) -> str:
|
|
"""
|
|
Replaces occurrences of old_content with new_content in a file.
|
|
|
|
Args:
|
|
file_path: Path to the file to modify
|
|
old_content: Content to replace
|
|
new_content: Content to replace with
|
|
count: Maximum number of occurrences to replace. -1 means all occurrences.
|
|
|
|
Returns:
|
|
Success message with replacement count
|
|
"""
|
|
try:
|
|
content = read_file(file_path)
|
|
new_content_str, replacement_count = content.replace(old_content, new_content, count), content.count(old_content) if count == -1 else min(count, content.count(old_content))
|
|
|
|
with open(file_path, 'w') as file:
|
|
file.write(new_content_str)
|
|
|
|
return f"Successfully replaced {replacement_count} occurrence(s) in '{file_path}'"
|
|
except FileNotFoundError:
|
|
raise FileNotFoundError(f"File not found: {file_path}")
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied modifying: {file_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error replacing content in '{file_path}': {str(e)}")
|
|
|
|
|
|
@tools.tool("delete_in_file")
|
|
def delete_in_file(file_path: str, content_to_delete: str, count: int = -1) -> str:
|
|
"""
|
|
Deletes occurrences of content_to_delete from a file.
|
|
|
|
Args:
|
|
file_path: Path to the file to modify
|
|
content_to_delete: Content to delete
|
|
count: Maximum number of occurrences to delete. -1 means all occurrences.
|
|
|
|
Returns:
|
|
Success message with deletion count
|
|
"""
|
|
try:
|
|
content = read_file(file_path)
|
|
new_content_str = content.replace(content_to_delete, '', count)
|
|
deletion_count = content.count(content_to_delete) if count == -1 else min(count, content.count(content_to_delete))
|
|
|
|
with open(file_path, 'w') as file:
|
|
file.write(new_content_str)
|
|
|
|
return f"Successfully deleted {deletion_count} occurrence(s) from '{file_path}'"
|
|
except FileNotFoundError:
|
|
raise FileNotFoundError(f"File not found: {file_path}")
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied modifying: {file_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error deleting content from '{file_path}': {str(e)}")
|
|
|
|
|
|
@tools.tool("delete_file")
|
|
def delete_file(file_path: str) -> str:
|
|
"""
|
|
Deletes a file.
|
|
|
|
Args:
|
|
file_path: Path to the file to delete
|
|
|
|
Returns:
|
|
Success message
|
|
"""
|
|
try:
|
|
if not os.path.exists(file_path):
|
|
raise FileNotFoundError(f"File not found: {file_path}")
|
|
os.remove(file_path)
|
|
return f"Successfully deleted file: {file_path}"
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied deleting: {file_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error deleting file '{file_path}': {str(e)}")
|
|
|
|
|
|
@tools.tool("copy_file")
|
|
def copy_file(source_path: str, destination_path: str, overwrite: bool = False) -> str:
|
|
"""
|
|
Copies a file from source_path to destination_path.
|
|
|
|
Args:
|
|
source_path: Path to the source file
|
|
destination_path: Path to the destination
|
|
overwrite: If True, overwrites existing destination file
|
|
|
|
Returns:
|
|
Success message
|
|
"""
|
|
try:
|
|
if not os.path.exists(source_path):
|
|
raise FileNotFoundError(f"Source file not found: {source_path}")
|
|
|
|
if os.path.exists(destination_path) and not overwrite:
|
|
raise FileExistsError(
|
|
f"Destination '{destination_path}' already exists. Set overwrite=True to replace it."
|
|
)
|
|
|
|
# Ensure destination directory exists
|
|
dir_path = os.path.dirname(destination_path)
|
|
if dir_path and not os.path.exists(dir_path):
|
|
os.makedirs(dir_path, exist_ok=True)
|
|
|
|
shutil.copy(source_path, destination_path)
|
|
return f"Successfully copied '{source_path}' to '{destination_path}'"
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied during copy operation")
|
|
except Exception as e:
|
|
raise Exception(f"Error copying file: {str(e)}")
|
|
|
|
|
|
@tools.tool("move_file")
|
|
def move_file(source_path: str, destination_path: str, overwrite: bool = False) -> str:
|
|
"""
|
|
Moves a file from source_path to destination_path.
|
|
|
|
Args:
|
|
source_path: Path to the source file
|
|
destination_path: Path to the destination
|
|
overwrite: If True, overwrites existing destination file
|
|
|
|
Returns:
|
|
Success message
|
|
"""
|
|
try:
|
|
if not os.path.exists(source_path):
|
|
raise FileNotFoundError(f"Source file not found: {source_path}")
|
|
|
|
if os.path.exists(destination_path) and not overwrite:
|
|
raise FileExistsError(
|
|
f"Destination '{destination_path}' already exists. Set overwrite=True to replace it."
|
|
)
|
|
|
|
# Ensure destination directory exists
|
|
dir_path = os.path.dirname(destination_path)
|
|
if dir_path and not os.path.exists(dir_path):
|
|
os.makedirs(dir_path, exist_ok=True)
|
|
|
|
shutil.move(source_path, destination_path)
|
|
return f"Successfully moved '{source_path}' to '{destination_path}'"
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied during move operation")
|
|
except Exception as e:
|
|
raise Exception(f"Error moving file: {str(e)}")
|
|
|
|
|
|
@tools.tool("create_directory")
|
|
def create_directory(directory_path: str, parents: bool = True) -> str:
|
|
"""
|
|
Creates a new directory at the specified path.
|
|
|
|
Args:
|
|
directory_path: Path to the directory to create
|
|
parents: If True, creates parent directories as needed
|
|
|
|
Returns:
|
|
Success message
|
|
"""
|
|
try:
|
|
os.makedirs(directory_path, exist_ok=parents)
|
|
return f"Successfully created directory: {directory_path}"
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied creating directory: {directory_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error creating directory '{directory_path}': {str(e)}")
|
|
|
|
|
|
@tools.tool("delete_directory")
|
|
def delete_directory(directory_path: str, recursive: bool = True) -> str:
|
|
"""
|
|
Deletes a directory at the specified path.
|
|
|
|
Args:
|
|
directory_path: Path to the directory to delete
|
|
recursive: If True, deletes directory and all contents
|
|
|
|
Returns:
|
|
Success message
|
|
"""
|
|
try:
|
|
if not os.path.exists(directory_path):
|
|
raise FileNotFoundError(f"Directory not found: {directory_path}")
|
|
if not os.path.isdir(directory_path):
|
|
raise NotADirectoryError(f"Path is not a directory: {directory_path}")
|
|
|
|
shutil.rmtree(directory_path)
|
|
return f"Successfully deleted directory: {directory_path}"
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied deleting directory: {directory_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error deleting directory '{directory_path}': {str(e)}")
|
|
|
|
|
|
@tools.tool("list_directory")
|
|
def list_directory(directory_path: str, level: int = 1, recursive: bool = False) -> List[Dict[str, Any]]:
|
|
"""
|
|
Lists the contents of a directory.
|
|
|
|
Args:
|
|
directory_path: Path to the directory to list
|
|
level: Depth level for recursive listing (1 = immediate children only)
|
|
recursive: If True, lists all contents recursively
|
|
|
|
Returns:
|
|
List of dictionaries containing file/folder information with keys:
|
|
- 'name': Name of the item
|
|
- 'path': Full path of the item
|
|
- 'type': 'file' or 'directory'
|
|
"""
|
|
try:
|
|
if not os.path.exists(directory_path):
|
|
raise FileNotFoundError(f"Directory not found: {directory_path}")
|
|
if not os.path.isdir(directory_path):
|
|
raise NotADirectoryError(f"Path is not a directory: {directory_path}")
|
|
|
|
def get_directory_contents(path: str, current_level: int, max_level: int) -> List[Dict[str, Any]]:
|
|
contents = []
|
|
try:
|
|
for item in os.listdir(path):
|
|
item_path = os.path.join(path, item)
|
|
is_dir = os.path.isdir(item_path)
|
|
|
|
item_info = {
|
|
'name': item,
|
|
'path': item_path,
|
|
'type': 'directory' if is_dir else 'file'
|
|
}
|
|
contents.append(item_info)
|
|
|
|
# Recursively get contents if needed
|
|
if is_dir and current_level < max_level:
|
|
sub_contents = get_directory_contents(item_path, current_level + 1, max_level)
|
|
item_info['contents'] = sub_contents
|
|
|
|
except PermissionError:
|
|
item_info = {'name': path, 'path': path, 'type': 'directory', 'error': 'Permission denied'}
|
|
contents.append(item_info)
|
|
|
|
return contents
|
|
|
|
if recursive:
|
|
return get_directory_contents(directory_path, 1, level)
|
|
else:
|
|
return get_directory_contents(directory_path, 1, 1)
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied listing directory: {directory_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error listing directory '{directory_path}': {str(e)}")
|
|
|
|
|
|
@tools.tool("get_file_info")
|
|
def get_file_info(file_path: str) -> Dict[str, Any]:
|
|
"""
|
|
Gets information about a file.
|
|
|
|
Args:
|
|
file_path: Path to the file
|
|
|
|
Returns:
|
|
Dictionary containing file information:
|
|
- 'name': File name
|
|
- 'path': Full path
|
|
- 'size': Size in bytes
|
|
- 'is_file': True if it's a file
|
|
- 'is_directory': True if it's a directory
|
|
- 'modified': Last modified timestamp
|
|
- 'created': Created timestamp
|
|
"""
|
|
try:
|
|
if not os.path.exists(file_path):
|
|
raise FileNotFoundError(f"File not found: {file_path}")
|
|
|
|
stat_info = os.stat(file_path)
|
|
return {
|
|
'name': os.path.basename(file_path),
|
|
'path': file_path,
|
|
'size': stat_info.st_size,
|
|
'is_file': os.path.isfile(file_path),
|
|
'is_directory': os.path.isdir(file_path),
|
|
'modified': stat_info.st_mtime,
|
|
'created': stat_info.st_ctime
|
|
}
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied getting info for: {file_path}")
|
|
except Exception as e:
|
|
raise Exception(f"Error getting file info for '{file_path}': {str(e)}")
|