˝
˝#!/usr/bin/env python3
˝"""
˝Replace Method Tool - Replace an entire Python method/function by name
˝
˝Usage:
˝ python3 replace_method/main.py <file> –method "name" –new-body "def name(): pass"
˝ python3 replace_method/main.py <file> –method "name" –new-body-file /path/to/impl.py
˝"""
˝
˝import argparse, re, sys
˝from pathlib import Path
˝
˝def find_method_boundaries(content: str, method_name: str) -> tuple:
˝ """Find the start and end positions of a method based on indentation."""
˝ lines = content.split(’\n’)
˝
˝ # Pattern to match method/function definition strictly
˝ method_pattern = re.compile(rf’ˆ(\s*)(def\s+{re.escape(method_name)}\s*()’)
˝
˝ # … [Logic to find start_line and base_indent] …
˝
˝ # Find the end of the method by checking indentation levels
˝ end_line = len(lines)
˝ for i in range(start_line + 1, len(lines)):
˝ line = lines[i]
˝ stripped = line.lstrip()
˝
˝ # Skip empty lines and comments
˝ if not stripped or stripped.startswith(’#’): continue
˝
˝ current_indent = len(line) - len(stripped)
˝
˝ # Stop if we find a line at same or lower indentation level
˝ if current_indent <= base_indent:
˝ end_line = i
˝ break
˝
˝ return start_pos, end_pos, base_indent
˝
˝def replace_method(filepath: str, method_name: str, new_body: str) -> None:
˝ """Replace a method/function with new implementation."""
˝ path = Path(filepath)
˝ content = path.read_text()
˝
˝ # 1. Locate the method in the source file
˝ start_pos, end_pos, indent = find_method_boundaries(content, method_name)
˝
˝ if start_pos is None:
˝ print(f"ERROR: Method ’{method_name}’ not found")
˝ sys.exit(1)
˝
˝ # 2. Align the new body to the correct indentation level
˝ new_lines = new_body.split(’\n’)
˝ indented_lines = []
˝ for line in new_lines:
˝ if line.strip() and not line.startswith(’ ’ * indent):
˝ line = ’ ’ * indent + line.lstrip()
˝ indented_lines.append(line)
˝ new_body_indented = ’\n’.join(indented_lines)
˝
˝ # 3. Perform the string replacement
˝ new_content = content[:start_pos] + new_body_indented + content[end_pos:]
˝ path.write_text(new_content)
˝ print(f"SUCCESS: Replaced method ’{method_name}’ in {filepath}")
˝
˝def main():
˝ # … [Argparse setup omitted for brevity] …
˝ if args.show_only:
˝ replace_method(args.file, args.method, "", show_only=True)
˝ elif args.new_body:
˝ replace_method(args.file, args.method, args.new_body)
˝
˝if name == "main":
˝ main()
˝