Dateien
Hetzner-Backup/v2_adminpanel/cleanup_commented_routes_auto.py
2025-06-16 23:20:23 +02:00

153 Zeilen
5.7 KiB
Python

#!/usr/bin/env python3
"""
Automatisches Cleanup-Skript zum Entfernen auskommentierter Routes aus app.py
Führt das Cleanup ohne Benutzerinteraktion durch
"""
import re
import sys
from datetime import datetime
import os
def cleanup_commented_routes(file_path):
"""Entfernt auskommentierte Route-Blöcke aus app.py"""
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
print(f"📄 Datei geladen: {len(lines)} Zeilen")
cleaned_lines = []
removed_blocks = []
i = 0
while i < len(lines):
line = lines[i]
# Prüfe ob eine auskommentierte Route beginnt
if re.match(r'^# @app\.route\(', line.strip()):
block_start_line = i + 1 # 1-basiert für Anzeige
block_lines = [line]
i += 1
# Sammle den ganzen auskommentierten Block
while i < len(lines):
current_line = lines[i]
# Block endet wenn:
# 1. Eine neue Funktion/Route beginnt (nicht auskommentiert)
# 2. Eine neue auskommentierte Route beginnt
# 3. Nicht-kommentierter Code gefunden wird
if re.match(r'^@', current_line.strip()) or \
re.match(r'^def\s+\w+', current_line.strip()) or \
re.match(r'^class\s+\w+', current_line.strip()):
# Nicht-kommentierter Code gefunden, Block endet
break
if re.match(r'^# @app\.route\(', current_line.strip()) and len(block_lines) > 1:
# Neue auskommentierte Route, vorheriger Block endet
break
# Prüfe ob die Zeile zum kommentierten Block gehört
if current_line.strip() == '' and i + 1 < len(lines):
# Schaue voraus
next_line = lines[i + 1]
if not (next_line.strip().startswith('#') or next_line.strip() == ''):
# Leerzeile gefolgt von nicht-kommentiertem Code
block_lines.append(current_line)
i += 1
break
if current_line.strip().startswith('#') or current_line.strip() == '':
block_lines.append(current_line)
i += 1
else:
# Nicht-kommentierte Zeile gefunden, Block endet
break
# Entferne trailing Leerzeilen vom Block
while block_lines and block_lines[-1].strip() == '':
block_lines.pop()
i -= 1
removed_blocks.append({
'start_line': block_start_line,
'end_line': block_start_line + len(block_lines) - 1,
'lines': len(block_lines),
'route': extract_route_info(block_lines)
})
# Füge eine Leerzeile ein wenn nötig (um Abstand zu wahren)
if cleaned_lines and cleaned_lines[-1].strip() != '' and \
i < len(lines) and lines[i].strip() != '':
cleaned_lines.append('\n')
else:
cleaned_lines.append(line)
i += 1
return cleaned_lines, removed_blocks
def extract_route_info(block_lines):
"""Extrahiert Route-Information aus dem kommentierten Block"""
for line in block_lines:
match = re.search(r'# @app\.route\("([^"]+)"', line)
if match:
return match.group(1)
return "Unknown"
def main():
file_path = 'app.py'
backup_path = f'app.py.backup_before_cleanup_{datetime.now().strftime("%Y%m%d_%H%M%S")}'
print("🧹 Starte automatisches Cleanup der auskommentierten Routes...\n")
# Backup erstellen
print(f"💾 Erstelle Backup: {backup_path}")
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
with open(backup_path, 'w', encoding='utf-8') as f:
f.write(content)
# Cleanup durchführen
cleaned_lines, removed_blocks = cleanup_commented_routes(file_path)
# Statistiken anzeigen
print(f"\n📊 Cleanup-Statistiken:")
print(f" Entfernte Blöcke: {len(removed_blocks)}")
print(f" Entfernte Zeilen: {sum(block['lines'] for block in removed_blocks)}")
print(f" Neue Dateigröße: {len(cleaned_lines)} Zeilen")
if len(removed_blocks) > 10:
print(f"\n🗑️ Erste 10 entfernte Routes:")
for block in removed_blocks[:10]:
print(f" Zeilen {block['start_line']}-{block['end_line']}: {block['route']} ({block['lines']} Zeilen)")
print(f" ... und {len(removed_blocks) - 10} weitere Routes")
else:
print(f"\n🗑️ Entfernte Routes:")
for block in removed_blocks:
print(f" Zeilen {block['start_line']}-{block['end_line']}: {block['route']} ({block['lines']} Zeilen)")
# Bereinigte Datei schreiben
print(f"\n✍️ Schreibe bereinigte Datei...")
with open(file_path, 'w', encoding='utf-8') as f:
f.writelines(cleaned_lines)
# Größenvergleich
old_size = os.path.getsize(backup_path)
new_size = os.path.getsize(file_path)
reduction = old_size - new_size
reduction_percent = (reduction / old_size) * 100
print(f"\n📉 Dateigrößen-Reduktion:")
print(f" Vorher: {old_size:,} Bytes")
print(f" Nachher: {new_size:,} Bytes")
print(f" Reduziert um: {reduction:,} Bytes ({reduction_percent:.1f}%)")
print(f"\n✅ Cleanup erfolgreich abgeschlossen!")
print(f" Backup: {backup_path}")
print(f" Rollback möglich mit: cp {backup_path} app.py")
if __name__ == "__main__":
main()