import os import subprocess from .base import tool @tool( name="code_analyze_file", description="Analyze code structure and suggest improvements", parameters={ "file_path": {"type": "string", "description": "Path to the file to analyze"} } ) def code_analyze_file(file_path: str) -> str: try: with open(os.path.expanduser(file_path), 'r') as f: content = f.read() lines = content.split('\n') functions = [l for l in lines if 'def ' in l] classes = [l for l in lines if 'class ' in l] issues = [] if len(lines) > 500: issues.append(f"Large file ({len(lines)} lines) - consider splitting") if len(functions) > 30: issues.append(f"Many functions ({len(functions)}) - consider refactoring") return f"""File: {file_path} Lines: {len(lines)} | Functions: {len(functions)} | Classes: {len(classes)} Issues: {chr(10).join(f'- {i}' for i in issues) if issues else '- None detected'}""" except Exception as e: return f"Error: {str(e)}" @tool( name="generate_readme", description="Generate a README.md for the current project", parameters={ "path": {"type": "string", "description": "Project root path", "default": "."} } ) def generate_readme(path: str = ".") -> str: try: project_name = os.path.basename(os.path.abspath(path)) readme_content = f"# {project_name}\n\nGenerated by Ollama CLI." readme_path = os.path.join(path, "README.md") with open(readme_path, 'w') as f: f.write(readme_content) return f"Generated README.md at {readme_path}" except Exception as e: return f"Error: {str(e)}" @tool( name="replace_text", description="Surgically replace text in a file", parameters={ "path": {"type": "string", "description": "Path to the file"}, "old_text": {"type": "string", "description": "The exact text to find"}, "new_text": {"type": "string", "description": "The text to replace it with"} } ) def replace_text(path: str, old_text: str, new_text: str) -> str: try: expanded_path = os.path.expanduser(path) with open(expanded_path, 'r') as f: content = f.read() if old_text not in content: return f"Error: The text to replace was not found in {path}" new_content = content.replace(old_text, new_text, 1) # Replace first occurrence with open(expanded_path, 'w') as f: f.write(new_content) return f"Successfully updated {path}" except Exception as e: return f"Error: {str(e)}" @tool( name="run_linter", description="Run a linter on a file", parameters={ "file_path": {"type": "string", "description": "Path to the file"}, "linter": {"type": "string", "description": "Linter to use (pylint|eslint|auto)", "default": "auto"} } ) def run_linter(file_path: str, linter: str = "auto") -> str: try: file_path = os.path.expanduser(file_path) if linter == "auto": ext = os.path.splitext(file_path)[1] linter = "pylint" if ext == ".py" else "eslint" result = subprocess.run(f"{linter} {file_path}", shell=True, capture_output=True, text=True) return result.stdout + result.stderr except Exception as e: return f"Error: {str(e)}"