|
| 1 | +import { promises as fs } from "fs" |
| 2 | +import * as path from "path" |
| 3 | +import * as os from "os" |
| 4 | +import { PROJECT_WIKI_TEMPLATE } from "./wiki-prompts/project-wiki" |
| 5 | +import { PROJECT_OVERVIEW_ANALYSIS_TEMPLATE } from "./wiki-prompts/subtasks/01_Project_Overview_Analysis" |
| 6 | +import { OVERALL_ARCHITECTURE_ANALYSIS_TEMPLATE } from "./wiki-prompts/subtasks/02_Overall_Architecture_Analysis" |
| 7 | +import { SERVICE_DEPENDENCIES_ANALYSIS_TEMPLATE } from "./wiki-prompts/subtasks/03_Service_Dependencies_Analysis" |
| 8 | +import { DATA_FLOW_INTEGRATION_ANALYSIS_TEMPLATE } from "./wiki-prompts/subtasks/04_Data_Flow_Integration_Analysis" |
| 9 | +import { SERVICE_ANALYSIS_TEMPLATE } from "./wiki-prompts/subtasks/05_Service_Analysis_Template" |
| 10 | +import { DATABASE_SCHEMA_ANALYSIS_TEMPLATE } from "./wiki-prompts/subtasks/06_Database_Schema_Analysis" |
| 11 | +import { API_INTERFACE_ANALYSIS_TEMPLATE } from "./wiki-prompts/subtasks/07_API_Interface_Analysis" |
| 12 | +import { DEPLOY_ANALYSIS_TEMPLATE } from "./wiki-prompts/subtasks/08_Deploy_Analysis" |
| 13 | +import { PROJECT_RULES_GENERATION_TEMPLATE } from "./wiki-prompts/subtasks/09_Project_Rules_Generation" |
| 14 | +import { ILogger, createLogger } from "../../../utils/logger" |
| 15 | + |
| 16 | +// Safely get home directory |
| 17 | +function getHomeDir(): string { |
| 18 | + const homeDir = os.homedir() |
| 19 | + if (!homeDir) { |
| 20 | + throw new Error("Unable to determine home directory") |
| 21 | + } |
| 22 | + return homeDir |
| 23 | +} |
| 24 | + |
| 25 | +// Get global commands directory path |
| 26 | +function getGlobalCommandsDir(): string { |
| 27 | + return path.join(getHomeDir(), ".roo", "commands") |
| 28 | +} |
| 29 | + |
| 30 | +export const projectWikiCommandName = "project-wiki" |
| 31 | +export const projectWikiCommandDescription = `Analyze project deeply and generate a comprehensive project wiki.` |
| 32 | + |
| 33 | +const logger: ILogger = createLogger("ProjectWikiHelpers") |
| 34 | + |
| 35 | +// Unified error handling function, preserving stack information |
| 36 | +function formatError(error: unknown): string { |
| 37 | + if (error instanceof Error) { |
| 38 | + return error.stack || error.message |
| 39 | + } |
| 40 | + return String(error) |
| 41 | +} |
| 42 | + |
| 43 | +const mainFileName: string = projectWikiCommandName + ".md" |
| 44 | +// Template data mapping |
| 45 | +const TEMPLATES = { |
| 46 | + [mainFileName]: PROJECT_WIKI_TEMPLATE, |
| 47 | + "01_Project_Overview_Analysis.md": PROJECT_OVERVIEW_ANALYSIS_TEMPLATE, |
| 48 | + "02_Overall_Architecture_Analysis.md": OVERALL_ARCHITECTURE_ANALYSIS_TEMPLATE, |
| 49 | + "03_Service_Dependencies_Analysis.md": SERVICE_DEPENDENCIES_ANALYSIS_TEMPLATE, |
| 50 | + "04_Data_Flow_Integration_Analysis.md": DATA_FLOW_INTEGRATION_ANALYSIS_TEMPLATE, |
| 51 | + "05_Service_Analysis_Template.md": SERVICE_ANALYSIS_TEMPLATE, |
| 52 | + "06_Database_Schema_Analysis.md": DATABASE_SCHEMA_ANALYSIS_TEMPLATE, |
| 53 | + "07_API_Interface_Analysis.md": API_INTERFACE_ANALYSIS_TEMPLATE, |
| 54 | + "08_Deploy_Analysis.md": DEPLOY_ANALYSIS_TEMPLATE, |
| 55 | + "09_Project_Rules_Generation.md": PROJECT_RULES_GENERATION_TEMPLATE, |
| 56 | +} |
| 57 | + |
| 58 | +export async function ensureProjectWikiCommandExists() { |
| 59 | + const startTime = Date.now() |
| 60 | + logger.info("[projectWikiHelpers] Starting ensureProjectWikiCommandExists...") |
| 61 | + |
| 62 | + try { |
| 63 | + const globalCommandsDir = getGlobalCommandsDir() |
| 64 | + await fs.mkdir(globalCommandsDir, { recursive: true }) |
| 65 | + |
| 66 | + const projectWikiFile = path.join(globalCommandsDir, `${projectWikiCommandName}.md`) |
| 67 | + const subTaskDir = path.join(globalCommandsDir, "subtasks") |
| 68 | + |
| 69 | + // Check if setup is needed |
| 70 | + const needsSetup = await checkIfSetupNeeded(projectWikiFile, subTaskDir) |
| 71 | + if (!needsSetup) { |
| 72 | + logger.info("[projectWikiHelpers] project-wiki command already exists") |
| 73 | + return |
| 74 | + } |
| 75 | + |
| 76 | + logger.info("[projectWikiHelpers] Setting up project-wiki command...") |
| 77 | + |
| 78 | + // Clean up existing files |
| 79 | + await Promise.allSettled([ |
| 80 | + fs.rm(projectWikiFile, { force: true }), |
| 81 | + fs.rm(subTaskDir, { recursive: true, force: true }), |
| 82 | + ]) |
| 83 | + |
| 84 | + // Generate Wiki files |
| 85 | + await generateWikiCommandFiles(projectWikiFile, subTaskDir) |
| 86 | + |
| 87 | + const duration = Date.now() - startTime |
| 88 | + logger.info(`[projectWikiHelpers] project-wiki command setup completed in ${duration}ms`) |
| 89 | + } catch (error) { |
| 90 | + const errorMsg = formatError(error) |
| 91 | + throw new Error(`Failed to setup project-wiki command: ${errorMsg}`) |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +// Optimized file checking logic, using Promise.allSettled to improve performance |
| 96 | +async function checkIfSetupNeeded(projectWikiFile: string, subTaskDir: string): Promise<boolean> { |
| 97 | + try { |
| 98 | + const [mainFileResult, subDirResult] = await Promise.allSettled([ |
| 99 | + fs.access(projectWikiFile, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK), |
| 100 | + fs.stat(subTaskDir), |
| 101 | + ]) |
| 102 | + |
| 103 | + // If main file doesn't exist, setup is needed |
| 104 | + if (mainFileResult.status === "rejected") { |
| 105 | + logger.info("[projectWikiHelpers] projectWikiFile not accessible:", formatError(mainFileResult.reason)) |
| 106 | + return true |
| 107 | + } |
| 108 | + |
| 109 | + // If subtask directory doesn't exist or is not a directory, setup is needed |
| 110 | + if (subDirResult.status === "rejected") { |
| 111 | + logger.info("[projectWikiHelpers] subTaskDir not accessible:", formatError(subDirResult.reason)) |
| 112 | + return true |
| 113 | + } |
| 114 | + |
| 115 | + if (!subDirResult.value.isDirectory()) { |
| 116 | + logger.info("[projectWikiHelpers] subTaskDir exists but is not a directory") |
| 117 | + return true |
| 118 | + } |
| 119 | + |
| 120 | + // Check if subtask directory has .md files |
| 121 | + const subTaskFiles = await fs.readdir(subTaskDir) |
| 122 | + const mdFiles = subTaskFiles.filter((file) => file.endsWith(".md")) |
| 123 | + return mdFiles.length === 0 |
| 124 | + } catch (error) { |
| 125 | + logger.error("[projectWikiHelpers] Error checking setup status:", formatError(error)) |
| 126 | + return true |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +// Generate Wiki files |
| 131 | +async function generateWikiCommandFiles(projectWikiFile: string, subTaskDir: string): Promise<void> { |
| 132 | + try { |
| 133 | + // Generate main file |
| 134 | + const mainTemplate = TEMPLATES[mainFileName] |
| 135 | + if (!mainTemplate) { |
| 136 | + throw new Error("Main template not found") |
| 137 | + } |
| 138 | + |
| 139 | + await fs.writeFile(projectWikiFile, mainTemplate, "utf-8") |
| 140 | + logger.info(`[projectWikiHelpers] Generated main wiki file: ${projectWikiFile}`) |
| 141 | + |
| 142 | + // Create subtask directory |
| 143 | + await fs.mkdir(subTaskDir, { recursive: true }) |
| 144 | + |
| 145 | + // Generate subtask files |
| 146 | + const subTaskFiles = Object.keys(TEMPLATES).filter((file) => file !== mainFileName) |
| 147 | + const generateResults = await Promise.allSettled( |
| 148 | + subTaskFiles.map(async (file) => { |
| 149 | + const template = TEMPLATES[file as keyof typeof TEMPLATES] |
| 150 | + if (!template) { |
| 151 | + throw new Error(`Template not found for file: ${file}`) |
| 152 | + } |
| 153 | + |
| 154 | + const targetFile = path.join(subTaskDir, file) |
| 155 | + await fs.writeFile(targetFile, template, "utf-8") |
| 156 | + return file |
| 157 | + }), |
| 158 | + ) |
| 159 | + |
| 160 | + // Count generation results |
| 161 | + const successful = generateResults.filter((result) => result.status === "fulfilled") |
| 162 | + const failed = generateResults.filter((result) => result.status === "rejected") |
| 163 | + |
| 164 | + logger.info(`[projectWikiHelpers] Successfully generated ${successful.length} subtask files`) |
| 165 | + |
| 166 | + if (failed.length > 0) { |
| 167 | + logger.warn(`[projectWikiHelpers] Failed to generate ${failed.length} subtask files:`) |
| 168 | + failed.forEach((result, index) => { |
| 169 | + if (result.status === "rejected") { |
| 170 | + logger.warn(` - ${subTaskFiles[generateResults.indexOf(result)]}: ${formatError(result.reason)}`) |
| 171 | + } |
| 172 | + }) |
| 173 | + } |
| 174 | + } catch (error) { |
| 175 | + const errorMsg = formatError(error) |
| 176 | + throw new Error(`Failed to generate wiki files: ${errorMsg}`) |
| 177 | + } |
| 178 | +} |
0 commit comments