All files / src/utils inject-prompt-diagnostic-with-callback.ts

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

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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165                                                                                                                                                                                                                                                                                                                                         
import * as fs from 'node:fs'
import path from 'node:path'
import * as vscode from 'vscode'
import { DIAGNOSTIC_COLLECTION_NAME } from '../constants'
 
/**
 * 解析包含行号和列号信息的文件路径
 * 例如: "src/components/UserInfo.vue:21:7" -> { filePath: "src/components/UserInfo.vue", line: 21, column: 7 }
 */
function parseFilePathWithLineInfo(pathWithLineInfo: string): {
  filePath: string
  line?: number
  column?: number
} {
  // 使用正则表达式匹配文件路径和行号、列号
  const match = pathWithLineInfo.match(/^(.+?):(\d+)(?::(\d+))?$/)
 
  if (match) {
    const [, filePath, lineStr, columnStr] = match
    return {
      filePath: filePath.trim(),
      line: Number.parseInt(lineStr, 10),
      column: columnStr ? Number.parseInt(columnStr, 10) : undefined,
    }
  }
 
  // 如果没有匹配到行号信息,返回原始路径
  return {
    filePath: pathWithLineInfo.trim(),
  }
}
 
/**
 * 注入提示诊断并执行回调函数
 *
 * 该函数的主要作用是创建一个假的诊断信息(diagnostic),将用户的提示作为错误信息显示在编辑器中,
 * 然后触发回调函数(通常是AI编辑命令)。这种方式可以让AI助手获取到用户的提示内容。
 *
 * @param params 包含提示文本和回调函数的参数对象
 */
export async function injectPromptDiagnosticWithCallback(params: {
  prompt: string // 提示文本,将作为诊断信息显示
  fileContextPath?: string // 上下文文件路径
  callback: () => Promise<any> // 注入提示后要执行的回调函数
}): Promise<void> {
  let editor = vscode.window.activeTextEditor
  let document = null
  const fileContext = params.fileContextPath
  try {
    // 如果没有活动的编辑器,则尝试打开工作区中的第一个文件
    const files = await vscode.workspace.findFiles(
      '**/*',
      '**/node_modules/**', // 排除node_modules目录
    )
 
    if (files.length === 0) {
      vscode.window.showErrorMessage('No files found in workspace to open.')
      return
    }
 
    // 打开找到的第一个文件
    document = await vscode.workspace.openTextDocument(files[0])
    editor = await vscode.window.showTextDocument(document)
  }
  catch (error: any) {
    console.error(error)
    vscode.window.showErrorMessage(
      'Failed to open existing file for prompt injection.',
    )
    return
  }
 
  /**
   * 如果提供了文件上下文路径,则打开文件
   */
  if (fileContext) {
    try {
      // 解析文件路径,移除行号和列号信息
      const parsedPath = parseFilePathWithLineInfo(fileContext)
      // 这里需要判断是相对路径还是绝对路径
      const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath
 
      let fullPath = parsedPath.filePath
 
      if (!parsedPath.filePath.startsWith('/')) {
        fullPath = path.resolve(workspaceRoot, parsedPath.filePath)
      }
      // 检查文件是否存在
      const fileUri = vscode.Uri.file(fullPath)
      try {
        await vscode.workspace.fs.stat(fileUri)
        document = await vscode.workspace.openTextDocument(fileUri)
        editor = await vscode.window.showTextDocument(document)
        // 如果有行号信息,打开文档后跳转到指定行
        if (document && parsedPath.line !== undefined) {
          const line = Math.max(0, parsedPath.line - 1) // VSCode行号从0开始
          console.log('line', line, 'column', 0)
          const end = new vscode.Position(line + 1, 0)
          editor.selection = new vscode.Selection(new vscode.Position(line, 0), end)
          editor.revealRange(new vscode.Range(new vscode.Position(line, 0), end), vscode.TextEditorRevealType.InCenter)
        }
      }
      // eslint-disable-next-line unused-imports/no-unused-vars
      catch (_: any) {
        console.error('File does not exist:', fullPath)
        vscode.window.showErrorMessage(`文件不存在: ${fileContext}`)
      }
    }
    catch (error) {
      console.error('Failed to open fileContextPath:', fileContext, error)
      vscode.window.showErrorMessage(`无法打开文件: ${fileContext}`)
      // 继续执行,不中断流程
    }
  }
  // 等待200毫秒确保编辑器已准备就绪
 
  await new Promise(resolve => setTimeout(resolve, 200))
 
  // 创建诊断集合,用于设置和清除诊断信息
  const fakeDiagCollection = vscode.languages.createDiagnosticCollection(
    DIAGNOSTIC_COLLECTION_NAME,
  )
 
  try {
    // 使用当前选择范围或整个文档范围
    const selectionOrFullDocRange = editor.selection.isEmpty
      ? new vscode.Range(0, 0, document?.lineCount || 0, 0) // 如果没有选择,则使用整个文档
      : editor.selection // 使用实际选择的范围
    // 1. 创建假的诊断对象
    const fakeDiagnostic = new vscode.Diagnostic(
      selectionOrFullDocRange,
      params.prompt, // 使用提示文本作为诊断消息
      vscode.DiagnosticSeverity.Error, // 设置为错误级别
    )
    fakeDiagnostic.source = DIAGNOSTIC_COLLECTION_NAME
 
    // 2. 设置诊断信息
    fakeDiagCollection.set(document.uri, [fakeDiagnostic])
 
    // 3. 确保光标位于诊断范围内(例如,起始位置)
    editor.selection = new vscode.Selection(
      selectionOrFullDocRange.start,
      selectionOrFullDocRange.start,
    )
    // 4. 执行回调函数(通常是触发AI编辑命令)
    vscode.window.showInformationMessage(`Triggered agent for prompt.`) // 简化的消息
  }
  catch (error) {
    vscode.window.showErrorMessage(`Failed to inject prompt: ${error}`)
  }
  setTimeout(async () => {
    await params.callback()
    if (document) {
      // 检查文档是否仍然有效(应该是有效的)
      // 从集合中清除此URI的特定诊断
      fakeDiagCollection.delete(document.uri)
    }
    else {
      fakeDiagCollection.clear() // 如果URI丢失,则清除所有内容
    }
    // 释放集合以清理资源
    fakeDiagCollection.dispose()
  }, 300)
}