init_project_safe.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. AI驱动的企业级软件开发工作流程 - 项目初始化脚本 (安全版本)
  5. 版本: 1.1
  6. 描述: 自动创建新项目的目录结构和固定文档,修复编码问题
  7. """
  8. import os
  9. import sys
  10. import json
  11. import shutil
  12. import argparse
  13. import locale
  14. from datetime import datetime
  15. from pathlib import Path
  16. # 设置系统编码环境
  17. def setup_encoding():
  18. """设置系统编码环境"""
  19. try:
  20. # 设置locale为UTF-8
  21. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  22. except locale.Error:
  23. try:
  24. locale.setlocale(locale.LC_ALL, 'C.UTF-8')
  25. except locale.Error:
  26. pass # 忽略locale设置错误
  27. # 确保环境变量支持UTF-8
  28. os.environ['LANG'] = 'en_US.UTF-8'
  29. os.environ['LC_ALL'] = 'en_US.UTF-8'
  30. os.environ['PYTHONIOENCODING'] = 'utf-8'
  31. # Windows特殊处理
  32. if sys.platform.startswith('win'):
  33. import codecs
  34. if hasattr(sys.stdout, 'buffer'):
  35. sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)
  36. if hasattr(sys.stderr, 'buffer'):
  37. sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer)
  38. # 初始化编码设置
  39. setup_encoding()
  40. class Colors:
  41. """终端颜色定义"""
  42. RED = '\033[91m'
  43. GREEN = '\033[92m'
  44. YELLOW = '\033[93m'
  45. BLUE = '\033[94m'
  46. MAGENTA = '\033[95m'
  47. CYAN = '\033[96m'
  48. WHITE = '\033[97m'
  49. BOLD = '\033[1m'
  50. UNDERLINE = '\033[4m'
  51. RESET = '\033[0m'
  52. def print_message(color, message):
  53. """打印带颜色的消息"""
  54. print(f"{color}{message}{Colors.RESET}")
  55. def print_success(message):
  56. print_message(Colors.GREEN, f"✓ {message}")
  57. def print_info(message):
  58. print_message(Colors.BLUE, f"ℹ {message}")
  59. def print_warning(message):
  60. print_message(Colors.YELLOW, f"⚠ {message}")
  61. def print_error(message):
  62. print_message(Colors.RED, f"✗ {message}")
  63. def safe_input(prompt, default=""):
  64. """安全的用户输入函数,处理编码问题"""
  65. try:
  66. if default:
  67. full_prompt = f"{prompt} (默认: {default}): "
  68. else:
  69. full_prompt = f"{prompt}: "
  70. # 使用bytes处理输入以避免编码问题
  71. print(full_prompt, end='', flush=True)
  72. # 直接从stdin读取bytes并解码
  73. if hasattr(sys.stdin, 'buffer'):
  74. line = sys.stdin.buffer.readline()
  75. user_input = line.decode('utf-8', errors='replace').strip()
  76. else:
  77. user_input = input().strip()
  78. return user_input if user_input else default
  79. except (UnicodeDecodeError, UnicodeError) as e:
  80. print_error(f"输入编码错误: {e}")
  81. print_warning("请确保终端支持UTF-8编码")
  82. return default
  83. except KeyboardInterrupt:
  84. print_error("\n用户中断操作")
  85. sys.exit(1)
  86. except EOFError:
  87. print_error("\n输入结束")
  88. return default
  89. except Exception as e:
  90. print_error(f"输入错误: {e}")
  91. return default
  92. def safe_yes_no_input(prompt, default_no=True):
  93. """安全的是/否输入函数"""
  94. try:
  95. suffix = "(y/N)" if default_no else "(Y/n)"
  96. response = safe_input(f"{prompt} {suffix}", "").lower()
  97. if default_no:
  98. return response in ['y', 'yes', '是', '1', 'true']
  99. else:
  100. return response not in ['n', 'no', '否', '0', 'false']
  101. except Exception as e:
  102. print_error(f"输入处理错误: {e}")
  103. return not default_no
  104. def get_ui_design_style():
  105. """获取UI设计风格选择"""
  106. print_info("请选择UI设计风格 (12种专业设计风格):")
  107. print_info("专业商务类型:")
  108. print(" 1. 企业商务风格 (Corporate) - 默认推荐")
  109. print(" 2. 包豪斯风格 (Bauhaus) - 功能主义设计")
  110. print(" 3. 艺术装饰风格 (ArtDeco) - 奢华几何美学")
  111. print_info("现代科技类型:")
  112. print(" 4. 暗黑科技风格 (Cyberpunk) - 科技感强烈")
  113. print(" 5. 未来科技风格 (Futuristic) - 数字未来美学")
  114. print(" 6. 大胆现代风格 (Bold) - 视觉冲击力强")
  115. print_info("极简清新类型:")
  116. print(" 7. 极简主义风格 (Minimal) - 简洁专注")
  117. print(" 8. 日式极简风格 (Japanese) - 禅意侘寂")
  118. print(" 9. 斯堪的纳维亚风格 (Scandinavian) - 北欧简约")
  119. print_info("创意艺术类型:")
  120. print(" 10. 孟菲斯风格 (Memphis) - 后现代叛逆")
  121. print(" 11. 波普艺术风格 (PopArt) - 大众文化美学")
  122. print(" 12. 优雅复古风格 (Elegant) - 经典印刷美学")
  123. styles = [
  124. ("1", "corporate", "企业商务风格"),
  125. ("2", "bauhaus", "包豪斯风格"),
  126. ("3", "artdeco", "艺术装饰风格"),
  127. ("4", "cyberpunk", "暗黑科技风格"),
  128. ("5", "futuristic", "未来科技风格"),
  129. ("6", "bold", "大胆现代风格"),
  130. ("7", "minimal", "极简主义风格"),
  131. ("8", "japanese", "日式极简风格"),
  132. ("9", "scandinavian", "斯堪的纳维亚风格"),
  133. ("10", "memphis", "孟菲斯风格"),
  134. ("11", "popart", "波普艺术风格"),
  135. ("12", "elegant", "优雅复古风格")
  136. ]
  137. while True:
  138. choice = safe_input("请输入选择 (1-12)", "1")
  139. try:
  140. choice_num = int(choice)
  141. if 1 <= choice_num <= 12:
  142. return styles[choice_num - 1][1] # 返回key
  143. else:
  144. print_warning("请输入1-12之间的数字")
  145. except ValueError:
  146. print_warning("请输入有效的数字")
  147. def get_generation_mode():
  148. """获取生成模式"""
  149. print_info("请选择生成模式:")
  150. print(" 1. fast - 快速验证模式 (5个核心页面)")
  151. print(" 2. full - 完整生产模式 (10个完整页面)")
  152. while True:
  153. choice = safe_input("请输入选择 (1-2)", "1")
  154. if choice in ["1", "fast"]:
  155. return "fast"
  156. elif choice in ["2", "full"]:
  157. return "full"
  158. else:
  159. print_warning("请输入1或2")
  160. def create_config_file(title, short_title, ui_style, mode, front_tech, backend_tech):
  161. """创建配置文件"""
  162. config = {
  163. "_comment_init": "=== 项目初始化配置(用户设置) ===",
  164. "front": front_tech,
  165. "backend": backend_tech,
  166. "title": title,
  167. "short_title": short_title,
  168. "requirements_description": "requires_docs/需求文档.md",
  169. "dev_tech_stack": "requires_docs/技术栈说明文档.md",
  170. "ui_design_style": ui_style,
  171. "_comment_fixed": "=== 固定配置(不变) ===",
  172. "system_prompt_dir": "system_prompts",
  173. "ui_design_spec_default": f"specs_docs/ui_design_specs/01-UI设计规范_默认_Corporate.md",
  174. "ui_design_spec": "requires_docs/UI设计规范.md",
  175. "_comment_generation": "=== 生成配置(可调整) ===",
  176. "page_count_fast": 5,
  177. "page_count_full": 10,
  178. "api_count_min": 8,
  179. "api_count_max": 35,
  180. "generation_mode": mode,
  181. "_comment_generated": "=== 流程生成配置(自动生成) ===",
  182. "framework_design": "process_docs/框架设计文档.md",
  183. "page_list": "process_docs/页面清单.md",
  184. "database_schema": "output_sourcecode/db/database_schema.sql",
  185. "copyright_application": "output_docs/软件著作权登记信息表.md"
  186. }
  187. try:
  188. with open("ai-copyright-config.json", "w", encoding="utf-8") as f:
  189. json.dump(config, f, ensure_ascii=False, indent=2)
  190. print_success("配置文件创建完成: ai-copyright-config.json")
  191. return True
  192. except Exception as e:
  193. print_error(f"创建配置文件失败: {e}")
  194. return False
  195. def create_directories():
  196. """创建项目目录结构"""
  197. dirs = [
  198. "requires_docs",
  199. "process_docs",
  200. "output_docs",
  201. "output_sourcecode/front",
  202. "output_sourcecode/backend",
  203. "output_sourcecode/db"
  204. ]
  205. for dir_path in dirs:
  206. try:
  207. os.makedirs(dir_path, exist_ok=True)
  208. print_success(f"创建目录: {dir_path}")
  209. except Exception as e:
  210. print_error(f"创建目录失败 {dir_path}: {e}")
  211. def main():
  212. """主函数"""
  213. print_message(Colors.BOLD + Colors.CYAN, "🚀 AI驱动的软件著作权申请材料生成系统 - 项目初始化")
  214. print_message(Colors.CYAN, "=" * 70)
  215. try:
  216. # 获取项目信息
  217. print_info("请输入项目配置信息:")
  218. system_title = safe_input("系统完整名称", "我的软件系统")
  219. if not system_title:
  220. system_title = "我的软件系统"
  221. short_title = safe_input("系统简称", system_title[:10] if len(system_title) > 10 else system_title)
  222. if not short_title:
  223. short_title = system_title[:10] if len(system_title) > 10 else system_title
  224. # 获取技术选择
  225. print_info("请选择技术栈:")
  226. front_tech = safe_input("前端技术 (vue/react/angular)", "vue")
  227. if not front_tech:
  228. front_tech = "vue"
  229. backend_tech = safe_input("后端技术 (java/nodejs/python)", "java")
  230. if not backend_tech:
  231. backend_tech = "java"
  232. # 获取UI风格
  233. ui_style = get_ui_design_style()
  234. # 获取生成模式
  235. mode = get_generation_mode()
  236. # 确认信息
  237. print_info("项目配置信息确认:")
  238. print(f" 系统名称: {system_title}")
  239. print(f" 系统简称: {short_title}")
  240. print(f" 前端技术: {front_tech}")
  241. print(f" 后端技术: {backend_tech}")
  242. print(f" UI风格: {ui_style}")
  243. print(f" 生成模式: {mode}")
  244. if not safe_yes_no_input("确认以上信息是否正确?", default_no=False):
  245. print_warning("用户取消操作")
  246. return
  247. # 创建目录结构
  248. print_info("创建项目目录结构...")
  249. create_directories()
  250. # 创建配置文件
  251. print_info("创建项目配置文件...")
  252. if create_config_file(system_title, short_title, ui_style, mode, front_tech, backend_tech):
  253. print_success("项目初始化完成!")
  254. print_info("下一步请:")
  255. print(" 1. 编辑 requires_docs/需求文档.md 文件")
  256. print(" 2. 运行质量检查: python3 scripts/validators/check_project.py --quick")
  257. else:
  258. print_error("项目初始化失败")
  259. except Exception as e:
  260. print_error(f"初始化过程中发生错误: {e}")
  261. import traceback
  262. traceback.print_exc()
  263. if __name__ == "__main__":
  264. main()