Files
mobile-android/remove_logs.py
2026-02-05 02:05:26 +05:00

120 lines
4.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
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
"""
Скрипт для удаления Log.d/e/w/i/v вызовов из Kotlin файлов
"""
import os
import re
import sys
def remove_logs_from_file(filepath):
"""Удаляет Log.d/e/w/i/v вызовы из файла"""
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
original_content = content
# Паттерн для Log.d/e/w/i/v с учетом многострочных вызовов
# Матчит: Log.d("TAG", "message") или Log.d(TAG, "message", exception)
patterns = [
# Простые однострочные логи
r'^\s*Log\.[dewiv]\([^)]*\)\s*\n',
# Многострочные логи (с переносами внутри скобок)
r'^\s*Log\.[dewiv]\([^)]*\n[^)]*\)\s*\n',
r'^\s*Log\.[dewiv]\([^)]*\n[^)]*\n[^)]*\)\s*\n',
r'^\s*Log\.[dewiv]\([^)]*\n[^)]*\n[^)]*\n[^)]*\)\s*\n',
# android.util.Log
r'^\s*android\.util\.Log\.[dewiv]\([^)]*\)\s*\n',
]
for pattern in patterns:
content = re.sub(pattern, '', content, flags=re.MULTILINE)
# Более агрессивный паттерн для оставшихся логов
# Находит Log.X( и удаляет до закрывающей скобки
def remove_log_call(match):
return ''
# Паттерн который находит Log.X(...) учитывая вложенные скобки
log_pattern = r'^\s*(?:android\.util\.)?Log\.[dewiv]\s*\([^()]*(?:\([^()]*\)[^()]*)*\)\s*\n?'
content = re.sub(log_pattern, '', content, flags=re.MULTILINE)
if content != original_content:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
return True
return False
def find_kotlin_files(directory):
"""Находит все .kt файлы в директории"""
kotlin_files = []
for root, dirs, files in os.walk(directory):
# Пропускаем build директории
dirs[:] = [d for d in dirs if d not in ['build', '.gradle', '.idea']]
for file in files:
if file.endswith('.kt'):
kotlin_files.append(os.path.join(root, file))
return kotlin_files
def count_logs_in_file(filepath):
"""Считает количество Log вызовов в файле"""
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
pattern = r'(?:android\.util\.)?Log\.[dewiv]\s*\('
matches = re.findall(pattern, content)
return len(matches)
def main():
# Директория с исходниками
src_dir = '/Users/ruslanmakhmatov/Desktop/Work/rosette-app/rosetta-android/app/src/main/java/com/rosetta/messenger'
if not os.path.exists(src_dir):
print(f"Директория не найдена: {src_dir}")
sys.exit(1)
kotlin_files = find_kotlin_files(src_dir)
print(f"Найдено {len(kotlin_files)} Kotlin файлов")
# Сначала считаем логи
total_logs_before = 0
files_with_logs = []
for filepath in kotlin_files:
count = count_logs_in_file(filepath)
if count > 0:
total_logs_before += count
files_with_logs.append((filepath, count))
print(f"Найдено {total_logs_before} Log вызовов в {len(files_with_logs)} файлах")
if '--dry-run' in sys.argv:
print("\n[DRY RUN] Файлы с логами:")
for filepath, count in sorted(files_with_logs, key=lambda x: -x[1]):
print(f" {count:3d} логов: {os.path.basename(filepath)}")
return
# Удаляем логи
modified_count = 0
for filepath in kotlin_files:
if remove_logs_from_file(filepath):
modified_count += 1
print(f"{os.path.basename(filepath)}")
# Считаем оставшиеся
total_logs_after = 0
for filepath in kotlin_files:
total_logs_after += count_logs_in_file(filepath)
print(f"\n{'='*50}")
print(f"Изменено файлов: {modified_count}")
print(f"Логов до: {total_logs_before}")
print(f"Логов после: {total_logs_after}")
print(f"Удалено: {total_logs_before - total_logs_after}")
if total_logs_after > 0:
print(f"\n⚠️ Осталось {total_logs_after} логов (возможно сложные многострочные)")
if __name__ == '__main__':
main()