#!/usr/bin/env python3 """Поиск и удаление недоступных симуляторов Xcode.""" from __future__ import annotations import argparse import json import subprocess import sys from pathlib import Path def simctl(*args: str) -> subprocess.CompletedProcess[str]: return subprocess.run( ["xcrun", "simctl", *args], capture_output=True, text=True, check=False, ) def main() -> int: parser = argparse.ArgumentParser(description="Удалить недоступные симуляторы") parser.add_argument("--apply", action="store_true", help="Удалить найденные устройства") parser.add_argument("--yes", action="store_true", help="Не задавать вопросов") parser.add_argument("--json", type=Path, help="Сохранить отчёт") args = parser.parse_args() result = simctl("list", "devices", "--json") if result.returncode != 0: print(f"xcrun simctl завершился с ошибкой: {result.stderr.strip()}", file=sys.stderr) return 2 try: data = json.loads(result.stdout) except json.JSONDecodeError as error: print(f"Не удалось разобрать JSON simctl: {error}", file=sys.stderr) return 2 runtimes = data.get("devices", {}) devices: list[dict] = [] for runtime, items in runtimes.items(): for item in items: item = dict(item) item["runtime"] = runtime devices.append(item) unavailable = [item for item in devices if not item.get("isAvailable", True)] report = { "runtimes": len(runtimes), "devices": len(devices), "unavailable": [ { "name": item.get("name", "?"), "udid": item.get("udid", ""), "runtime": item.get("runtime", ""), "state": item.get("state", ""), "error": item.get("availabilityError", ""), } for item in unavailable ], } if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Runtime: {report['runtimes']}. Устройств: {report['devices']}. Недоступных: {len(unavailable)}.") for item in report["unavailable"]: print(f" {item['name']} [{item['runtime']}] {item['udid']}") if item["error"]: print(f" причина: {item['error']}") if not unavailable: return 0 if not args.apply: print("Это предпросмотр. Добавьте --apply для удаления.") return 0 if not args.yes: answer = input("Удалить недоступные симуляторы? [y/N]: ").strip().lower() if answer not in {"y", "yes", "д", "да"}: print("Отменено.") return 1 errors = 0 for item in unavailable: udid = item.get("udid", "") if not udid: continue deleted = simctl("delete", udid) if deleted.returncode == 0: print(f"Удалён: {item.get('name', udid)}") else: errors += 1 print(f"Ошибка удаления {item.get('name', udid)}: {deleted.stderr.strip()}") print(f"Готово. Ошибок: {errors}.") return 0 if errors == 0 else 1 if __name__ == "__main__": raise SystemExit(main())