init_wizard.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. #!/usr/bin/env python3
  2. """
  3. AceFlow 快速初始化向导
  4. 支持轻量级、标准和完整三种模式的项目初始化
  5. """
  6. import os
  7. import sys
  8. import yaml
  9. import json
  10. from typing import Dict, List, Optional
  11. from pathlib import Path
  12. import questionary
  13. from datetime import datetime
  14. class AceFlowInitWizard:
  15. """AceFlow项目初始化向导"""
  16. def __init__(self):
  17. self.project_root = Path.cwd()
  18. self.aceflow_dir = self.project_root / ".aceflow"
  19. self.config = {}
  20. self.templates_dir = Path(__file__).parent.parent / "templates"
  21. def run(self):
  22. """运行初始化向导"""
  23. print("🚀 AceFlow 项目初始化向导")
  24. print("=" * 50)
  25. # 检查是否已经初始化
  26. if self.aceflow_dir.exists():
  27. if not questionary.confirm(
  28. "当前目录已经包含 AceFlow 配置,是否重新初始化?",
  29. default=False
  30. ).ask():
  31. print("初始化已取消")
  32. return
  33. # 收集项目信息
  34. project_info = self._collect_project_info()
  35. # 选择流程模式
  36. flow_mode = self._select_flow_mode(project_info)
  37. # 配置敏捷集成
  38. agile_config = self._configure_agile_integration()
  39. # 生成项目配置
  40. self._generate_project_config(project_info, flow_mode, agile_config)
  41. # 创建项目结构
  42. self._create_project_structure(flow_mode)
  43. # 生成初始模板
  44. self._generate_initial_templates(flow_mode)
  45. # 显示完成信息
  46. self._show_completion_info(flow_mode)
  47. def _collect_project_info(self) -> Dict:
  48. """收集项目基本信息"""
  49. print("\\n📋 项目信息收集")
  50. print("-" * 20)
  51. project_info = {
  52. 'name': questionary.text(
  53. "项目名称:",
  54. default=self.project_root.name
  55. ).ask(),
  56. 'description': questionary.text(
  57. "项目描述:",
  58. default=""
  59. ).ask(),
  60. 'team_size': questionary.select(
  61. "团队规模:",
  62. choices=[
  63. "1-3人 (小型团队)",
  64. "4-8人 (中型团队)",
  65. "9-15人 (大型团队)",
  66. "15+人 (企业团队)"
  67. ]
  68. ).ask(),
  69. 'project_duration': questionary.select(
  70. "项目周期:",
  71. choices=[
  72. "1-7天 (快速迭代)",
  73. "1-4周 (短期项目)",
  74. "1-3个月 (中期项目)",
  75. "3+个月 (长期项目)"
  76. ]
  77. ).ask(),
  78. 'project_type': questionary.select(
  79. "项目类型:",
  80. choices=[
  81. "Web应用",
  82. "移动应用",
  83. "桌面应用",
  84. "API/微服务",
  85. "数据分析",
  86. "机器学习",
  87. "其他"
  88. ]
  89. ).ask(),
  90. 'tech_stack': self._detect_tech_stack()
  91. }
  92. # 提取数字用于决策
  93. project_info['team_size_num'] = int(project_info['team_size'].split('-')[0])
  94. project_info['is_short_term'] = '1-7天' in project_info['project_duration'] or '1-4周' in project_info['project_duration']
  95. return project_info
  96. def _detect_tech_stack(self) -> Dict:
  97. """自动检测技术栈"""
  98. tech_stack = {
  99. 'frontend': [],
  100. 'backend': [],
  101. 'database': [],
  102. 'tools': []
  103. }
  104. # 检测前端技术
  105. if (self.project_root / "package.json").exists():
  106. try:
  107. with open(self.project_root / "package.json", 'r') as f:
  108. package_json = json.load(f)
  109. deps = {**package_json.get('dependencies', {}), **package_json.get('devDependencies', {})}
  110. if 'react' in deps:
  111. tech_stack['frontend'].append('React')
  112. if 'vue' in deps:
  113. tech_stack['frontend'].append('Vue.js')
  114. if 'angular' in deps:
  115. tech_stack['frontend'].append('Angular')
  116. if 'next' in deps:
  117. tech_stack['frontend'].append('Next.js')
  118. except Exception:
  119. pass
  120. # 检测后端技术
  121. if (self.project_root / "requirements.txt").exists():
  122. tech_stack['backend'].append('Python')
  123. if (self.project_root / "pom.xml").exists():
  124. tech_stack['backend'].append('Java')
  125. if (self.project_root / "go.mod").exists():
  126. tech_stack['backend'].append('Go')
  127. if (self.project_root / "Cargo.toml").exists():
  128. tech_stack['backend'].append('Rust')
  129. # 检测数据库
  130. config_files = ['.env', 'docker-compose.yml', 'config.yml']
  131. for config_file in config_files:
  132. if (self.project_root / config_file).exists():
  133. try:
  134. with open(self.project_root / config_file, 'r') as f:
  135. content = f.read().lower()
  136. if 'mysql' in content:
  137. tech_stack['database'].append('MySQL')
  138. if 'postgresql' in content or 'postgres' in content:
  139. tech_stack['database'].append('PostgreSQL')
  140. if 'mongodb' in content:
  141. tech_stack['database'].append('MongoDB')
  142. if 'redis' in content:
  143. tech_stack['database'].append('Redis')
  144. except Exception:
  145. pass
  146. return tech_stack
  147. def _select_flow_mode(self, project_info: Dict) -> str:
  148. """选择流程模式"""
  149. print("\\n🔄 流程模式选择")
  150. print("-" * 20)
  151. # 智能推荐
  152. recommended_mode = self._recommend_flow_mode(project_info)
  153. mode_choices = [
  154. {
  155. 'name': f"轻量级模式 (P→D→R) {'✅ 推荐' if recommended_mode == 'minimal' else ''}",
  156. 'value': 'minimal'
  157. },
  158. {
  159. 'name': f"标准模式 (P1→P2→D1→D2→R1) {'✅ 推荐' if recommended_mode == 'standard' else ''}",
  160. 'value': 'standard'
  161. },
  162. {
  163. 'name': f"完整模式 (S1→S2→S3→S4→S5→S6→S7→S8) {'✅ 推荐' if recommended_mode == 'complete' else ''}",
  164. 'value': 'complete'
  165. }
  166. ]
  167. print(f"基于项目信息,推荐使用: {self._get_mode_name(recommended_mode)}")
  168. selected_mode = questionary.select(
  169. "选择流程模式:",
  170. choices=mode_choices
  171. ).ask()
  172. return selected_mode
  173. def _recommend_flow_mode(self, project_info: Dict) -> str:
  174. """基于项目信息推荐流程模式"""
  175. team_size = project_info['team_size_num']
  176. is_short_term = project_info['is_short_term']
  177. if team_size <= 5 and is_short_term:
  178. return 'minimal'
  179. elif team_size <= 10 and not '3+个月' in project_info['project_duration']:
  180. return 'standard'
  181. else:
  182. return 'complete'
  183. def _get_mode_name(self, mode: str) -> str:
  184. """获取模式显示名称"""
  185. mode_names = {
  186. 'minimal': '轻量级模式',
  187. 'standard': '标准模式',
  188. 'complete': '完整模式'
  189. }
  190. return mode_names.get(mode, mode)
  191. def _configure_agile_integration(self) -> Dict:
  192. """配置敏捷集成"""
  193. print("\\n🏃 敏捷集成配置")
  194. print("-" * 20)
  195. enable_agile = questionary.confirm(
  196. "是否启用敏捷开发集成?",
  197. default=True
  198. ).ask()
  199. if not enable_agile:
  200. return {'enabled': False}
  201. framework = questionary.select(
  202. "选择敏捷框架:",
  203. choices=[
  204. "Scrum",
  205. "Kanban",
  206. "自定义",
  207. "暂不配置"
  208. ]
  209. ).ask()
  210. config = {
  211. 'enabled': True,
  212. 'framework': framework.lower()
  213. }
  214. if framework == "Scrum":
  215. config.update({
  216. 'iteration_length': questionary.select(
  217. "Sprint长度:",
  218. choices=["1周", "2周", "3周", "4周"]
  219. ).ask(),
  220. 'ceremonies': {
  221. 'planning': True,
  222. 'daily_standup': True,
  223. 'review': True,
  224. 'retrospective': True
  225. }
  226. })
  227. elif framework == "Kanban":
  228. config.update({
  229. 'lanes': ["待办", "进行中", "评审", "完成"],
  230. 'wip_limits': {
  231. '进行中': 3,
  232. '评审': 2
  233. }
  234. })
  235. return config
  236. def _generate_project_config(self, project_info: Dict, flow_mode: str, agile_config: Dict):
  237. """生成项目配置文件"""
  238. config = {
  239. 'project': {
  240. 'name': project_info['name'],
  241. 'description': project_info['description'],
  242. 'created_at': datetime.now().isoformat(),
  243. 'team_size': project_info['team_size'],
  244. 'project_duration': project_info['project_duration'],
  245. 'project_type': project_info['project_type'],
  246. 'tech_stack': project_info['tech_stack']
  247. },
  248. 'flow': {
  249. 'mode': flow_mode,
  250. 'auto_switch': True,
  251. 'current_stage': self._get_initial_stage(flow_mode)
  252. },
  253. 'agile': agile_config,
  254. 'ai': {
  255. 'enabled': True,
  256. 'decision_support': True,
  257. 'auto_recommendations': True
  258. },
  259. 'memory': {
  260. 'enabled': True,
  261. 'retention_days': 30,
  262. 'auto_cleanup': True
  263. }
  264. }
  265. self.config = config
  266. # 保存配置
  267. self.aceflow_dir.mkdir(parents=True, exist_ok=True)
  268. with open(self.aceflow_dir / "config.yaml", 'w', encoding='utf-8') as f:
  269. yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
  270. def _get_initial_stage(self, flow_mode: str) -> str:
  271. """获取初始阶段"""
  272. initial_stages = {
  273. 'minimal': 'P',
  274. 'standard': 'P1',
  275. 'complete': 'S1'
  276. }
  277. return initial_stages.get(flow_mode, 'P')
  278. def _create_project_structure(self, flow_mode: str):
  279. """创建项目目录结构"""
  280. # 创建基础目录
  281. directories = [
  282. self.aceflow_dir / "templates",
  283. self.aceflow_dir / "memory_pool",
  284. self.aceflow_dir / "config",
  285. self.aceflow_dir / "scripts"
  286. ]
  287. for directory in directories:
  288. directory.mkdir(parents=True, exist_ok=True)
  289. # 创建状态文件
  290. initial_state = {
  291. 'current_stage': self._get_initial_stage(flow_mode),
  292. 'flow_mode': flow_mode,
  293. 'stage_status': {},
  294. 'progress': {},
  295. 'memory_ids': [],
  296. 'created_at': datetime.now().isoformat(),
  297. 'last_updated': datetime.now().isoformat()
  298. }
  299. with open(self.aceflow_dir / "current_state.json", 'w') as f:
  300. json.dump(initial_state, f, indent=2)
  301. def _generate_initial_templates(self, flow_mode: str):
  302. """生成初始模板文件"""
  303. templates_dir = self.aceflow_dir / "templates"
  304. if flow_mode == 'minimal':
  305. self._create_minimal_templates(templates_dir)
  306. elif flow_mode == 'standard':
  307. self._create_standard_templates(templates_dir)
  308. else:
  309. self._create_complete_templates(templates_dir)
  310. def _create_minimal_templates(self, templates_dir: Path):
  311. """创建轻量级模板"""
  312. # P阶段模板
  313. p_template = """# 规划阶段 (Planning)
  314. ## 项目概述
  315. - **项目名称**: {project_name}
  316. - **负责人**:
  317. - **预计工期**:
  318. - **优先级**:
  319. ## 需求描述
  320. ### 用户故事
  321. 作为 [用户角色],我希望 [功能描述],以便 [价值/目标]。
  322. ### 验收标准
  323. - [ ] 标准1
  324. - [ ] 标准2
  325. - [ ] 标准3
  326. ## 任务清单
  327. - [ ] 任务1
  328. - [ ] 任务2
  329. - [ ] 任务3
  330. ## 风险评估
  331. - **技术风险**:
  332. - **时间风险**:
  333. - **资源风险**:
  334. ---
  335. *创建时间: {created_at}*
  336. *模板版本: minimal-v1.0*
  337. """
  338. # D阶段模板
  339. d_template = """# 开发阶段 (Development)
  340. ## 开发计划
  341. - **开始时间**:
  342. - **预计完成**:
  343. - **开发人员**:
  344. ## 技术方案
  345. ### 架构设计
  346. - **技术栈**:
  347. - **核心组件**:
  348. - **数据结构**:
  349. ### 实现计划
  350. - [ ] 环境搭建
  351. - [ ] 核心功能开发
  352. - [ ] 单元测试
  353. - [ ] 集成测试
  354. ## 开发日志
  355. ### [日期]
  356. - **进展**:
  357. - **问题**:
  358. - **解决方案**:
  359. ## 代码提交
  360. - **分支**:
  361. - **提交记录**:
  362. - **代码评审**:
  363. ---
  364. *创建时间: {created_at}*
  365. *模板版本: minimal-v1.0*
  366. """
  367. # R阶段模板
  368. r_template = """# 评审阶段 (Review)
  369. ## 功能验证
  370. ### 验收测试
  371. - [ ] 功能测试通过
  372. - [ ] 性能测试通过
  373. - [ ] 兼容性测试通过
  374. - [ ] 安全测试通过
  375. ### 问题清单
  376. | 问题描述 | 严重程度 | 状态 | 负责人 |
  377. |----------|----------|------|--------|
  378. | | | | |
  379. ## 代码质量
  380. - **代码覆盖率**:
  381. - **静态分析**:
  382. - **代码规范**:
  383. ## 部署准备
  384. - [ ] 部署文档更新
  385. - [ ] 配置文件准备
  386. - [ ] 数据库迁移
  387. - [ ] 回滚方案
  388. ## 交付物
  389. - [ ] 功能代码
  390. - [ ] 测试报告
  391. - [ ] 部署文档
  392. - [ ] 用户手册
  393. ---
  394. *创建时间: {created_at}*
  395. *模板版本: minimal-v1.0*
  396. """
  397. # 写入模板文件
  398. templates = {
  399. 'P_planning.md': p_template,
  400. 'D_development.md': d_template,
  401. 'R_review.md': r_template
  402. }
  403. for filename, content in templates.items():
  404. with open(templates_dir / filename, 'w', encoding='utf-8') as f:
  405. f.write(content.format(
  406. project_name=self.config['project']['name'],
  407. created_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  408. ))
  409. def _create_standard_templates(self, templates_dir: Path):
  410. """创建标准模板"""
  411. # TODO: 实现标准模式模板
  412. pass
  413. def _create_complete_templates(self, templates_dir: Path):
  414. """创建完整模板"""
  415. # TODO: 实现完整模式模板
  416. pass
  417. def _show_completion_info(self, flow_mode: str):
  418. """显示完成信息"""
  419. print("\\n🎉 AceFlow 项目初始化完成!")
  420. print("=" * 50)
  421. print(f"✅ 流程模式: {self._get_mode_name(flow_mode)}")
  422. print(f"✅ 项目名称: {self.config['project']['name']}")
  423. print(f"✅ 配置文件: {self.aceflow_dir / 'config.yaml'}")
  424. print(f"✅ 状态文件: {self.aceflow_dir / 'current_state.json'}")
  425. print("\\n🚀 快速开始:")
  426. print("1. aceflow status # 查看当前状态")
  427. print("2. aceflow next # 获取下一步建议")
  428. print("3. aceflow progress # 更新进度")
  429. if self.config['agile']['enabled']:
  430. print("\\n🏃 敏捷集成:")
  431. print(f"- 框架: {self.config['agile']['framework']}")
  432. if self.config['agile']['framework'] == 'scrum':
  433. print(f"- Sprint长度: {self.config['agile']['iteration_length']}")
  434. print("\\n📖 更多帮助:")
  435. print("- aceflow help # 查看帮助")
  436. print("- aceflow docs # 打开文档")
  437. def main():
  438. """主函数"""
  439. import argparse
  440. parser = argparse.ArgumentParser(description='AceFlow 项目初始化向导')
  441. parser.add_argument('--mode', choices=['minimal', 'standard', 'complete'],
  442. help='直接指定流程模式')
  443. parser.add_argument('--non-interactive', action='store_true',
  444. help='非交互式模式')
  445. args = parser.parse_args()
  446. try:
  447. wizard = AceFlowInitWizard()
  448. if args.non_interactive:
  449. # TODO: 实现非交互式初始化
  450. print("非交互式模式尚未实现")
  451. sys.exit(1)
  452. else:
  453. wizard.run()
  454. except KeyboardInterrupt:
  455. print("\\n\\n用户取消初始化")
  456. sys.exit(1)
  457. except Exception as e:
  458. print(f"\\n❌ 初始化失败: {e}")
  459. sys.exit(1)
  460. if __name__ == "__main__":
  461. main()