/
Manifest
/
Real_Texture
Обзор
Документация
Войти
/
Manifest
/
Real_Texture
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
ToolsForUE/1_Cleaner.py
228 строк
9 KB
m.samodurov
init commit for The Invaders
17 фев 2026, 04:57
17 фев 2026, 04:57
4a668d4
Код
Авторство
О чём код?
import os import shutil import json from pathlib import Path import sys # Конфигурационный файл (будет храниться рядом со скриптом) CONFIG_FILE = os.path.join(os.path.dirname(__file__), "ue_cleaner_config.json") # Стандартные настройки по умолчанию DEFAULT_CONFIG = { "folders_to_remove": [ "Intermediate", "DerivedDataCache", "Binaries", "Build", "Saved", ".vs", ".idea" ], "files_to_remove": [ ".vsconfig", "*.sln", "*.suo", "*.user" ], "exclude": [ "Saved/Config", "Saved/Cooked" ] } def find_project_root(): script_dir = os.path.dirname(os.path.abspath(__file__)) project_root = Path(script_dir).parent # Изменено с parent.parent на parent # Проверяем, что есть .uproject файл uproject_files = list(project_root.glob("*.uproject")) if not uproject_files: raise FileNotFoundError(f"Не найден .uproject файл в {project_root}") return project_root def load_config(): try: with open(CONFIG_FILE, 'r', encoding='utf-8') as f: return json.load(f) except (FileNotFoundError, json.JSONDecodeError): return DEFAULT_CONFIG.copy() def save_config(config): with open(CONFIG_FILE, 'w', encoding='utf-8') as f: json.dump(config, f, indent=4, ensure_ascii=False) def show_config_menu(config): """Показывает меню конфигурации""" print("\nТекущие настройки очистки:") print(f"1. Папки для удаления: {', '.join(config['folders_to_remove'])}") print(f"2. Файлы для удаления: {', '.join(config['files_to_remove'])}") print(f"3. Исключения: {', '.join(config['exclude'])}") print("4. Начать очистку") print("5. Выход") def edit_config(config): """Редактирование конфигурации""" while True: show_config_menu(config) choice = input("\nВыберите действие (1-5): ") if choice == '1': print("\nТекущие папки для удаления:") for i, folder in enumerate(config['folders_to_remove'], 1): print(f"{i}. {folder}") action = input("\nДобавить (a) или удалить (d) папку? (a/d): ").lower() if action == 'a': folder = input("Введите имя папки для добавления: ").strip() if folder and folder not in config['folders_to_remove']: config['folders_to_remove'].append(folder) elif action == 'd': try: num = int(input("Введите номер папки для удаления: ")) if 1 <= num <= len(config['folders_to_remove']): removed = config['folders_to_remove'].pop(num-1) print(f"Удалено: {removed}") except ValueError: print("Некорректный ввод") elif choice == '2': print("\nТекущие файлы для удаления:") for i, file_pattern in enumerate(config['files_to_remove'], 1): print(f"{i}. {file_pattern}") action = input("\nДобавить (a) или удалить (d) шаблон? (a/d): ").lower() if action == 'a': pattern = input("Введите шаблон файла (можно использовать *): ").strip() if pattern and pattern not in config['files_to_remove']: config['files_to_remove'].append(pattern) elif action == 'd': try: num = int(input("Введите номер шаблона для удаления: ")) if 1 <= num <= len(config['files_to_remove']): removed = config['files_to_remove'].pop(num-1) print(f"Удалено: {removed}") except ValueError: print("Некорректный ввод") elif choice == '3': print("\nТекущие исключения:") for i, exclusion in enumerate(config['exclude'], 1): print(f"{i}. {exclusion}") action = input("\nДобавить (a) или удалить (d) исключение? (a/d): ").lower() if action == 'a': exclusion = input("Введите исключение (например, Saved/Config): ").strip() if exclusion and exclusion not in config['exclude']: config['exclude'].append(exclusion) elif action == 'd': try: num = int(input("Введите номер исключения для удаления: ")) if 1 <= num <= len(config['exclude']): removed = config['exclude'].pop(num-1) print(f"Удалено: {removed}") except ValueError: print("Некорректный ввод") elif choice == '4': save_config(config) return True # Начать очистку elif choice == '5': save_config(config) return False # Выход else: print("Некорректный выбор") def clean_project(project_path, config): """Очищает проект по указанной конфигурации""" total_size = 0 total_removed = 0 print(f"\nНачинаем очистку проекта: {project_path}") for root, dirs, files in os.walk(project_path): # Удаляем папки for dir_name in dirs[:]: dir_path = os.path.join(root, dir_name) rel_path = os.path.relpath(dir_path, project_path) #Исключения!!!!!!!!!!! skip = any( rel_path.replace(os.sep, '/').startswith(exc.replace("/", os.sep)) for exc in config['exclude'] ) if not skip and dir_name in config['folders_to_remove']: try: dir_size = sum(f.stat().st_size for f in os.scandir(dir_path) if f.is_file()) shutil.rmtree(dir_path) print(f"Удалено: {rel_path} ({dir_size/1024/1024:.2f} MB)") total_size += dir_size total_removed += 1 except Exception as e: print(f"Ошибка при удалении {rel_path}: {e}") # Удаляем файлы for file_name in files: file_path = os.path.join(root, file_name) rel_path = os.path.relpath(file_path, project_path) for pattern in config['files_to_remove']: if (file_name == pattern or (pattern.startswith('*') and file_name.endswith(pattern[1:]))): try: file_size = os.path.getsize(file_path) os.remove(file_path) print(f"Удалено: {rel_path} ({file_size/1024:.2f} KB)") total_size += file_size total_removed += 1 break except Exception as e: print(f"Ошибка при удалении {rel_path}: {e}") # Очищаем плагины plugins_path = os.path.join(project_path, "Plugins") if os.path.exists(plugins_path): for plugin in os.listdir(plugins_path): plugin_path = os.path.join(plugins_path, plugin) if os.path.isdir(plugin_path): size, count = clean_project(plugin_path, config) total_size += size total_removed += count return total_size, total_removed def main(): try: # Автоматически определяем корень проекта project_root = find_project_root() print("=== Unreal Engine Project Cleaner ===") print(f"Автоматически определен корень проекта: {project_root}") # Загружаем конфигурацию config = load_config() while True: start_clean = edit_config(config) if start_clean: confirm = input("\nВы уверены, что хотите продолжить? (y/n): ") if confirm.lower() == 'y': total_size, total_removed = clean_project(project_root, config) print("\n" + "="*50) print(f"Очистка завершена! Удалено {total_removed} объектов.") print(f"Освобождено места: {total_size/1024/1024:.2f} MB") input("\nНажмите Enter для продолжения...") else: print("Очистка отменена") else: print("Выход из программы") break except Exception as e: print(f"\nОшибка: {str(e)}") sys.exit(1) if __name__ == "__main__": main()