gateway/rename_renderers.py
2025-10-11 23:39:13 +02:00

197 lines
7.4 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
Script to rename renderer files from <name>_renderer.py to renderer<Name>.py
and update all references in the codebase.
"""
import os
import re
import shutil
from pathlib import Path
from typing import Dict, List, Tuple
def get_renderer_files(renderers_dir: Path) -> List[Tuple[str, str]]:
"""Get list of renderer files to rename."""
renderer_files = []
for file_path in renderers_dir.glob("*_renderer.py"):
if file_path.name not in ['base_renderer.py', 'registry.py']:
old_name = file_path.name
# Extract the name part (e.g., "csv" from "csv_renderer.py")
name_part = old_name.replace('_renderer.py', '')
# Create new name (e.g., "rendererCsv.py")
new_name = f"renderer{name_part.capitalize()}.py"
renderer_files.append((old_name, new_name))
return renderer_files
def update_file_imports(file_path: Path, old_to_new: Dict[str, str]) -> bool:
"""Update import statements in a file."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
original_content = content
changes_made = False
# Update import statements
for old_name, new_name in old_to_new.items():
old_module = old_name.replace('.py', '')
new_module = new_name.replace('.py', '')
# Pattern for from .old_module import
pattern1 = rf'from \.{re.escape(old_module)} import'
replacement1 = f'from .{new_module} import'
if re.search(pattern1, content):
content = re.sub(pattern1, replacement1, content)
changes_made = True
# Pattern for from modules.services.serviceGeneration.renderers.old_module import
pattern2 = rf'from modules\.services\.serviceGeneration\.renderers\.{re.escape(old_module)} import'
replacement2 = f'from modules.services.serviceGeneration.renderers.{new_module} import'
if re.search(pattern2, content):
content = re.sub(pattern2, replacement2, content)
changes_made = True
if changes_made:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"✅ Updated imports in: {file_path}")
return True
else:
print(f" No imports to update in: {file_path}")
return False
except Exception as e:
print(f"❌ Error updating {file_path}: {str(e)}")
return False
def update_class_names_in_file(file_path: Path, old_to_new: Dict[str, str]) -> bool:
"""Update class names in renderer files."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
original_content = content
changes_made = False
# Update class names
for old_name, new_name in old_to_new.items():
old_module = old_name.replace('.py', '')
new_module = new_name.replace('.py', '')
# Extract the name part for class name
name_part = old_module.replace('_renderer', '')
old_class = f"{name_part.capitalize()}Renderer"
new_class = f"Renderer{name_part.capitalize()}"
# Update class definition
pattern1 = rf'class {re.escape(old_class)}\('
replacement1 = f'class {new_class}('
if re.search(pattern1, content):
content = re.sub(pattern1, replacement1, content)
changes_made = True
# Update class instantiation
pattern2 = rf'{re.escape(old_class)}\('
replacement2 = f'{new_class}('
if re.search(pattern2, content):
content = re.sub(pattern2, replacement2, content)
changes_made = True
if changes_made:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"✅ Updated class names in: {file_path}")
return True
else:
print(f" No class names to update in: {file_path}")
return False
except Exception as e:
print(f"❌ Error updating class names in {file_path}: {str(e)}")
return False
def main():
"""Main function to rename renderer files and update references."""
print("🔄 Starting renderer file renaming process...")
# Get the gateway directory
gateway_dir = Path(__file__).parent
renderers_dir = gateway_dir / "modules" / "services" / "serviceGeneration" / "renderers"
if not renderers_dir.exists():
print(f"❌ Renderers directory not found: {renderers_dir}")
return
print(f"📁 Working in directory: {renderers_dir}")
# Get list of files to rename
renderer_files = get_renderer_files(renderers_dir)
if not renderer_files:
print(" No renderer files found to rename.")
return
print(f"📋 Found {len(renderer_files)} renderer files to rename:")
for old_name, new_name in renderer_files:
print(f" {old_name}{new_name}")
# Create mapping dictionary
old_to_new = {old_name: new_name for old_name, new_name in renderer_files}
# Step 1: Update imports in all Python files
print("\n🔄 Step 1: Updating import statements...")
updated_files = []
# Search in gateway directory
for py_file in gateway_dir.rglob("*.py"):
if py_file.name != "rename_renderers.py": # Skip this script
if update_file_imports(py_file, old_to_new):
updated_files.append(py_file)
print(f"✅ Updated imports in {len(updated_files)} files")
# Step 2: Update class names in renderer files
print("\n🔄 Step 2: Updating class names in renderer files...")
class_updated_files = []
for old_name, new_name in renderer_files:
old_file_path = renderers_dir / old_name
if old_file_path.exists():
if update_class_names_in_file(old_file_path, old_to_new):
class_updated_files.append(old_file_path)
print(f"✅ Updated class names in {len(class_updated_files)} files")
# Step 3: Rename the files
print("\n🔄 Step 3: Renaming files...")
renamed_files = []
for old_name, new_name in renderer_files:
old_file_path = renderers_dir / old_name
new_file_path = renderers_dir / new_name
if old_file_path.exists():
try:
shutil.move(str(old_file_path), str(new_file_path))
renamed_files.append((old_name, new_name))
print(f"✅ Renamed: {old_name}{new_name}")
except Exception as e:
print(f"❌ Error renaming {old_name}: {str(e)}")
else:
print(f"⚠️ File not found: {old_name}")
print(f"\n🎉 Renaming process completed!")
print(f"📊 Summary:")
print(f" - Files renamed: {len(renamed_files)}")
print(f" - Import statements updated: {len(updated_files)}")
print(f" - Class names updated: {len(class_updated_files)}")
if renamed_files:
print(f"\n📋 Renamed files:")
for old_name, new_name in renamed_files:
print(f"{old_name}{new_name}")
if __name__ == "__main__":
main()