/** * 上下文管理模块 * 功能:处理文件、文件夹、图片、文档上下文添加 * 依赖:vscode, fs, path * 使用场景:用户添加上下文项时 */ import * as vscode from "vscode"; export async function handleAddContextFile(panel: vscode.WebviewPanel) { const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; if (!workspaceFolder) { vscode.window.showWarningMessage("请先打开一个工作区"); return; } const files = await vscode.workspace.findFiles( "**/*", "**/node_modules/**", ); panel.webview.postMessage({ command: "showWorkspaceFileList", files: files.map((uri) => ({ path: uri.fsPath, relativePath: vscode.workspace.asRelativePath(uri), })), }); } export async function handleAddContextFolder(panel: vscode.WebviewPanel) { const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; if (!workspaceFolder) { vscode.window.showWarningMessage("请先打开一个工作区"); return; } const fs = require("fs"); const path = require("path"); const folders: Array<{ path: string; relativePath: string }> = []; function scanFolders(dir: string, baseDir: string) { try { const items = fs.readdirSync(dir, { withFileTypes: true }); for (const item of items) { if ( item.isDirectory() && item.name !== "node_modules" && !item.name.startsWith(".") ) { const fullPath = path.join(dir, item.name); const relativePath = path.relative(baseDir, fullPath); folders.push({ path: fullPath, relativePath }); scanFolders(fullPath, baseDir); } } } catch (error) { console.error("扫描文件夹失败:", error); } } scanFolders(workspaceFolder.uri.fsPath, workspaceFolder.uri.fsPath); panel.webview.postMessage({ command: "showWorkspaceFolderList", folders: folders, }); } export async function handleAddContextImage(panel: vscode.WebviewPanel) { const imageUris = await vscode.window.showOpenDialog({ canSelectFiles: true, canSelectFolders: false, canSelectMany: true, openLabel: "选择图片", filters: { 图片文件: ["png", "jpg", "jpeg", "gif", "bmp", "svg", "webp"], }, }); if (imageUris && imageUris.length > 0) { panel.webview.postMessage({ command: "contextImagesSelected", images: imageUris.map((uri) => uri.fsPath), }); } } export async function handleAddContextDocument(panel: vscode.WebviewPanel) { const docUris = await vscode.window.showOpenDialog({ canSelectFiles: true, canSelectFolders: false, canSelectMany: true, openLabel: "选择文档", filters: { 文档文件: ["pdf", "doc", "docx", "txt", "md"], 所有文件: ["*"], }, }); if (docUris && docUris.length > 0) { panel.webview.postMessage({ command: "contextDocumentsSelected", documents: docUris.map((uri) => uri.fsPath), }); } }