All files / src/services code-generation-service.ts

0% Statements 0/73
0% Branches 0/1
0% Functions 0/1
0% Lines 0/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143                                                                                                                                                                                                                                                                                             
import * as vscode from 'vscode'
import * as path from 'path'
import * as fs from 'fs/promises'
import { logger } from '../utils/logger-adapter'
 
// 代码生成结果的文件接口
export interface GeneratedFile {
  filePath: string
  content: string
  fileType: string
  description: string
  isDirectory: boolean
}
 
// 代码生成结果数据接口
export interface CodeGenerationResult {
  files: GeneratedFile[]
  installCommands: string[]
  runCommands: string[]
  summary: string
  techStackInfo: {
    framework: string
    version: string
    features: string[]
  }
  generationStats: {
    totalFiles: number
    totalDirectories: number
    generationTime: number
  }
}
 
export class CodeGenerationService {
  constructor(private context: vscode.ExtensionContext) {}
 
  /**
   * 写入生成的文件到工作区
   */
  async writeGeneratedFiles(data: CodeGenerationResult): Promise<void> {
    const workspaceFolder = vscode.workspace.workspaceFolders?.[0]
    if (!workspaceFolder) {
      throw new Error('未找到工作区文件夹')
    }
 
    const workspacePath = workspaceFolder.uri.fsPath
    logger.info(`开始写入生成的文件到工作区: ${workspacePath}`)
 
    try {
      // 创建目录和写入文件
      const createdFiles: string[] = []
      const createdDirectories: string[] = []
 
      for (const file of data.files) {
        const fullPath = path.join(workspacePath, file.filePath)
        
        if (file.isDirectory) {
          // 创建目录
          await this.ensureDirectoryExists(fullPath)
          createdDirectories.push(file.filePath)
          logger.info(`创建目录: ${file.filePath}`)
        } else {
          // 确保父目录存在
          const parentDir = path.dirname(fullPath)
          await this.ensureDirectoryExists(parentDir)
          
          // 写入文件
          await fs.writeFile(fullPath, file.content, 'utf8')
          createdFiles.push(file.filePath)
          logger.info(`创建文件: ${file.filePath}`)
        }
      }
 
      // 显示成功消息
      const message = `代码生成完成!\n创建了 ${createdFiles.length} 个文件和 ${createdDirectories.length} 个目录\n\n${data.summary}`
      vscode.window.showInformationMessage(message)
 
      // 在VSCode中打开主要文件
      await this.openMainFiles(data.files, workspacePath)
 
    } catch (error) {
      logger.error('写入文件失败:', error)
      throw error
    }
  }
 
  /**
   * 确保目录存在
   */
  private async ensureDirectoryExists(dirPath: string): Promise<void> {
    try {
      await fs.access(dirPath)
    } catch {
      await fs.mkdir(dirPath, { recursive: true })
    }
  }
 
 
  /**
   * 在VSCode中打开主要文件
   */
  private async openMainFiles(files: GeneratedFile[], workspacePath: string): Promise<void> {
    // 筛选出主要的代码文件(通常是.vue, .ts, .js 等)
    const mainFiles = files.filter(file => 
      !file.isDirectory && 
      (file.filePath.endsWith('.vue') || 
       file.filePath.endsWith('.ts') || 
       file.filePath.endsWith('.tsx') ||
       file.filePath.endsWith('.js') ||
       file.filePath.endsWith('.jsx') ||
       file.filePath.includes('index.'))
    ).slice(0, 3) // 最多打开3个文件
 
    for (const file of mainFiles) {
      try {
        const fullPath = path.join(workspacePath, file.filePath)
        const document = await vscode.workspace.openTextDocument(fullPath)
        await vscode.window.showTextDocument(document, vscode.ViewColumn.One)
      } catch (error) {
        logger.warn(`无法打开文件: ${file.filePath}`, error)
      }
    }
  }
 
  /**
   * 验证生成的文件路径安全性
   */
  private validateFilePath(filePath: string): boolean {
    // 防止路径遍历攻击
    const normalizedPath = path.normalize(filePath)
    return !normalizedPath.startsWith('../') && !path.isAbsolute(normalizedPath)
  }
 
  /**
   * 获取文件写入统计信息
   */
  getStats(): { totalFiles: number, lastGeneration?: Date } {
    // 这里可以实现统计功能
    return {
      totalFiles: 0,
      lastGeneration: undefined
    }
  }
}