import { promises as fs } from 'fs'; import path from 'path'; export class FileManager { private projectPath: string; private specDir: string; constructor(projectPath: string) { this.projectPath = this.validateAndNormalizePath(projectPath); this.specDir = path.join(this.projectPath, '.spec'); } /** * Validate and normalize project path to ensure it's absolute */ private validateAndNormalizePath(projectPath: string): string { if (!projectPath || projectPath.trim() === '') { throw new Error('projectPath is required and must be an absolute path'); } // Convert to absolute path and normalize const normalizedPath = path.resolve(projectPath); return normalizedPath; } /** * Ensure .spec directory exists */ async ensureSpecDir(): Promise { try { await fs.access(this.specDir); } catch { await fs.mkdir(this.specDir, { recursive: true }); } } /** * Read file content */ async readFile(filename: string): Promise { const filePath = path.join(this.specDir, filename); return await fs.readFile(filePath, 'utf-8'); } /** * Write file content */ async writeFile(filename: string, content: string): Promise { await this.ensureSpecDir(); const filePath = path.join(this.specDir, filename); await fs.writeFile(filePath, content, 'utf-8'); } /** * Delete file */ async deleteFile(filename: string): Promise { const filePath = path.join(this.specDir, filename); try { await fs.unlink(filePath); } catch (error: any) { if (error.code !== 'ENOENT') { throw error; } } } /** * Check if file exists */ async fileExists(filename: string): Promise { const filePath = path.join(this.specDir, filename); try { await fs.access(filePath); return true; } catch { return false; } } /** * List files in .spec directory */ async listFiles(): Promise { await this.ensureSpecDir(); const files = await fs.readdir(this.specDir); return files.filter(file => file.endsWith('.md')); } /** * Create archive directory */ async createArchiveDir(archiveName: string): Promise { const archiveDir = path.join(this.specDir, 'archives', archiveName); await fs.mkdir(archiveDir, { recursive: true }); return archiveDir; } /** * Copy file to archive */ async copyToArchive(filename: string, archiveDir: string): Promise { const sourcePath = path.join(this.specDir, filename); const destPath = path.join(archiveDir, filename); try { await fs.copyFile(sourcePath, destPath); } catch (error: any) { if (error.code !== 'ENOENT') { throw error; } } } /** * Get project name from path */ getProjectName(): string { return path.basename(this.projectPath); } /** * Get current timestamp */ getCurrentTimestamp(): string { return new Date().toISOString(); } }