manage_themes.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """
  2. 主题管理工具 - 管理themes.yaml文件
  3. """
  4. import sys
  5. import yaml
  6. from pathlib import Path
  7. from typing import List
  8. # 设置控制台编码为UTF-8(Windows)
  9. # 注意:只在作为主脚本运行时重定向,避免在被导入时冲突
  10. if sys.platform == 'win32' and __name__ == "__main__":
  11. import io
  12. if not isinstance(sys.stdout, io.TextIOWrapper):
  13. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
  14. if not isinstance(sys.stderr, io.TextIOWrapper):
  15. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
  16. def load_themes(themes_file: Path) -> List[str]:
  17. """从themes.yaml加载themes"""
  18. if not themes_file.exists():
  19. return []
  20. try:
  21. with open(themes_file, 'r', encoding='utf-8') as f:
  22. data = yaml.safe_load(f)
  23. if data is None:
  24. return []
  25. return data.get('themes', [])
  26. except Exception as e:
  27. print(f"⚠️ 读取themes.yaml失败: {e}")
  28. return []
  29. def save_themes(themes_file: Path, themes: List[str]):
  30. """保存themes到themes.yaml"""
  31. themes_file.parent.mkdir(parents=True, exist_ok=True)
  32. data = {'themes': themes}
  33. try:
  34. with open(themes_file, 'w', encoding='utf-8') as f:
  35. yaml.dump(data, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
  36. print(f"✅ themes已保存到: {themes_file}")
  37. return True
  38. except Exception as e:
  39. print(f"❌ 保存失败: {e}")
  40. return False
  41. def add_theme(themes_file: Path, theme: str) -> bool:
  42. """添加theme"""
  43. themes = load_themes(themes_file)
  44. if theme in themes:
  45. print(f"⚠️ theme '{theme}' 已存在")
  46. return False
  47. themes.append(theme)
  48. return save_themes(themes_file, themes)
  49. def remove_theme(themes_file: Path, theme: str) -> bool:
  50. """删除theme"""
  51. themes = load_themes(themes_file)
  52. if theme not in themes:
  53. print(f"⚠️ theme '{theme}' 不存在")
  54. return False
  55. themes.remove(theme)
  56. return save_themes(themes_file, themes)
  57. def list_themes(themes_file: Path):
  58. """列出所有themes"""
  59. themes = load_themes(themes_file)
  60. if not themes:
  61. print("📋 当前没有themes")
  62. return
  63. print(f"📋 当前themes ({len(themes)}个):")
  64. print("-" * 70)
  65. for i, theme in enumerate(themes, 1):
  66. print(f" {i}. {theme}")
  67. print("-" * 70)
  68. def interactive_theme_management(base_dir: Path):
  69. """交互式主题管理"""
  70. themes_file = base_dir / "themes.yaml"
  71. while True:
  72. print("\n" + "=" * 70)
  73. print("主题管理")
  74. print("=" * 70)
  75. list_themes(themes_file)
  76. print("\n请选择操作:")
  77. print(" 1. 添加theme")
  78. print(" 2. 删除theme")
  79. print(" 3. 查看themes")
  80. print(" 0. 退出")
  81. choice = input("\n请选择 (0-3): ").strip()
  82. if choice == "0":
  83. break
  84. elif choice == "1":
  85. theme = input("请输入要添加的theme: ").strip()
  86. if theme:
  87. if add_theme(themes_file, theme):
  88. print(f"✅ 已添加theme: {theme}")
  89. elif choice == "2":
  90. theme = input("请输入要删除的theme: ").strip()
  91. if theme:
  92. confirm = input(f"确认删除 '{theme}'? (y/n): ").strip().lower()
  93. if confirm in ['y', 'yes', '是']:
  94. if remove_theme(themes_file, theme):
  95. print(f"✅ 已删除theme: {theme}")
  96. elif choice == "3":
  97. list_themes(themes_file)
  98. else:
  99. print("⚠️ 无效选择,请重试")
  100. if __name__ == "__main__":
  101. import argparse
  102. parser = argparse.ArgumentParser(description="主题管理工具")
  103. parser.add_argument("--add", type=str, help="添加theme")
  104. parser.add_argument("--remove", type=str, help="删除theme")
  105. parser.add_argument("--list", action="store_true", help="列出所有themes")
  106. parser.add_argument("--interactive", action="store_true", help="交互式管理")
  107. parser.add_argument("--base-dir", type=str, help="基础目录路径(默认为脚本所在目录)")
  108. args = parser.parse_args()
  109. base_dir = Path(args.base_dir) if args.base_dir else Path(__file__).parent
  110. themes_file = base_dir / "themes.yaml"
  111. if args.list:
  112. list_themes(themes_file)
  113. elif args.add:
  114. add_theme(themes_file, args.add)
  115. elif args.remove:
  116. remove_theme(themes_file, args.remove)
  117. elif args.interactive:
  118. interactive_theme_management(base_dir)
  119. else:
  120. # 默认交互式
  121. interactive_theme_management(base_dir)