feat:实现读取本地文件的功能

This commit is contained in:
Roe-xin
2025-12-11 14:29:56 +08:00
parent 565f4afe46
commit 49b3e34101
5 changed files with 315 additions and 7 deletions

View File

@ -1,4 +1,5 @@
import * as vscode from "vscode";
import { readFileContent } from "./readFiles";
/**
* 处理用户消息
@ -16,6 +17,28 @@ export function handleUserMessage(panel: vscode.WebviewPanel, text: string) {
}, 500);
}
/**
* 处理文件读取请求
*/
export async function handleReadFile(
panel: vscode.WebviewPanel,
filePath: string
) {
try {
const content = await readFileContent(filePath);
panel.webview.postMessage({
command: "fileContent",
content: content,
filePath: filePath,
});
} catch (error) {
panel.webview.postMessage({
command: "fileError",
error: error instanceof Error ? error.message : "读取文件失败",
});
}
}
/**
* 获取模拟回复
*/

164
src/utils/readFiles.ts Normal file
View File

@ -0,0 +1,164 @@
import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
/**
* 读取文件内容
*/
export async function readFileContent(filePath: string): Promise<string> {
try {
// 如果是相对路径,转换为绝对路径
let absolutePath = filePath;
if (!path.isAbsolute(filePath)) {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (workspaceFolders && workspaceFolders.length > 0) {
absolutePath = path.join(workspaceFolders[0].uri.fsPath, filePath);
}
}
// 检查文件是否存在
if (!fs.existsSync(absolutePath)) {
throw new Error(`文件不存在: ${absolutePath}`);
}
// 检查是否是文件
const stats = fs.statSync(absolutePath);
if (!stats.isFile()) {
throw new Error(`路径不是文件: ${absolutePath}`);
}
// 读取文件内容
const content = fs.readFileSync(absolutePath, "utf-8");
return content;
} catch (error) {
throw error;
}
}
/**
* 读取多个文件内容
*/
export async function readMultipleFiles(
filePaths: string[]
): Promise<{ path: string; content: string; error?: string }[]> {
const results = [];
for (const filePath of filePaths) {
try {
const content = await readFileContent(filePath);
results.push({ path: filePath, content });
} catch (error) {
results.push({
path: filePath,
content: "",
error: error instanceof Error ? error.message : "未知错误",
});
}
}
return results;
}
/**
* 读取目录下所有文件
*/
export async function readDirectory(
dirPath: string,
extensions?: string[]
): Promise<{ path: string; content: string }[]> {
try {
// 如果是相对路径,转换为绝对路径
let absolutePath = dirPath;
if (!path.isAbsolute(dirPath)) {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (workspaceFolders && workspaceFolders.length > 0) {
absolutePath = path.join(workspaceFolders[0].uri.fsPath, dirPath);
}
}
// 检查目录是否存在
if (!fs.existsSync(absolutePath)) {
throw new Error(`目录不存在: ${absolutePath}`);
}
const stats = fs.statSync(absolutePath);
if (!stats.isDirectory()) {
throw new Error(`路径不是目录: ${absolutePath}`);
}
// 读取目录内容
const files = fs.readdirSync(absolutePath);
const results = [];
for (const file of files) {
const filePath = path.join(absolutePath, file);
const fileStats = fs.statSync(filePath);
if (fileStats.isFile()) {
// 如果指定了扩展名过滤
if (extensions && extensions.length > 0) {
const ext = path.extname(file);
if (!extensions.includes(ext)) {
continue;
}
}
try {
const content = fs.readFileSync(filePath, "utf-8");
results.push({ path: file, content });
} catch (error) {
// 跳过无法读取的文件
continue;
}
}
}
return results;
} catch (error) {
throw error;
}
}
/**
* 获取文件信息
*/
export function getFileInfo(filePath: string): {
exists: boolean;
isFile: boolean;
isDirectory: boolean;
size?: number;
extension?: string;
} {
try {
let absolutePath = filePath;
if (!path.isAbsolute(filePath)) {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (workspaceFolders && workspaceFolders.length > 0) {
absolutePath = path.join(workspaceFolders[0].uri.fsPath, filePath);
}
}
if (!fs.existsSync(absolutePath)) {
return {
exists: false,
isFile: false,
isDirectory: false,
};
}
const stats = fs.statSync(absolutePath);
return {
exists: true,
isFile: stats.isFile(),
isDirectory: stats.isDirectory(),
size: stats.size,
extension: path.extname(absolutePath),
};
} catch (error) {
return {
exists: false,
isFile: false,
isDirectory: false,
};
}
}

View File

@ -1,177 +0,0 @@
/**
* 获取 WebView 面板的 HTML 内容
*/
export function getWebviewContent(): string {
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IC Coder 助手</title>
<style>
body {
font-family: var(--vscode-font-family);
background: var(--vscode-editor-background);
color: var(--vscode-foreground);
margin: 0;
padding: 20px;
height: 100vh;
display: flex;
flex-direction: column;
}
.header {
text-align: center;
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 1px solid var(--vscode-panel-border);
}
.header h1 {
color: var(--vscode-button-background);
margin: 0 0 8px 0;
}
.chat-container {
flex: 1;
display: flex;
flex-direction: column;
}
.messages {
flex: 1;
overflow-y: auto;
margin-bottom: 15px;
}
.message {
margin-bottom: 12px;
padding: 10px 15px;
border-radius: 8px;
max-width: 80%;
}
.user-message {
background: var(--vscode-button-secondaryBackground);
margin-left: auto;
}
.bot-message {
background: var(--vscode-button-background);
color: var(--vscode-button-foreground);
margin-right: auto;
}
.input-area {
border-top: 1px solid var(--vscode-panel-border);
padding-top: 15px;
}
.input-group {
display: flex;
gap: 10px;
}
textarea {
flex: 1;
padding: 10px;
background: var(--vscode-input-background);
color: var(--vscode-input-foreground);
border: 1px solid var(--vscode-input-border);
border-radius: 4px;
font-family: inherit;
resize: none;
min-height: 40px;
}
button {
padding: 0 20px;
background: var(--vscode-button-background);
color: var(--vscode-button-foreground);
border: none;
border-radius: 4px;
cursor: pointer;
}
.quick-actions {
display: flex;
gap: 8px;
margin-top: 10px;
flex-wrap: wrap;
}
.quick-btn {
padding: 6px 12px;
background: var(--vscode-button-secondaryBackground);
color: var(--vscode-button-secondaryForeground);
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
}
</style>
</head>
<body>
<div class="header">
<h1>IC Coder</h1>
<p>专注于真实FPGA研发的Verilog智能体编程平台</p>
</div>
<div class="chat-container">
<div id="messages" class="messages">
<div class="message bot-message">
👋 你好!我是 IC Coder 助手,可以帮你生成代码、回答问题。
</div>
</div>
<div class="quick-actions">
<button class="quick-btn" onclick="quickAction('counter')">生成计数器</button>
<button class="quick-btn" onclick="quickAction('fsm')">生成状态机</button>
<button class="quick-btn" onclick="quickAction('testbench')">生成测试平台</button>
</div>
<div class="input-area">
<div class="input-group">
<textarea
id="messageInput"
placeholder="输入您的问题..."
onkeydown="if(event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); sendMessage(); }"
></textarea>
<button onclick="sendMessage()">发送</button>
</div>
</div>
</div>
<script>
const vscode = acquireVsCodeApi();
const messagesEl = document.getElementById('messages');
const messageInput = document.getElementById('messageInput');
function sendMessage() {
const text = messageInput.value.trim();
if (!text) return;
addMessage(text, 'user');
vscode.postMessage({ command: 'sendMessage', text: text });
messageInput.value = '';
messageInput.focus();
}
function quickAction(type) {
const questions = {
counter: '生成一个4位同步计数器',
fsm: '生成一个状态机',
testbench: '生成测试平台'
};
if (questions[type]) {
messageInput.value = questions[type];
sendMessage();
}
}
function addMessage(text, sender) {
const div = document.createElement('div');
div.className = \`message \${sender}-message\`;
div.textContent = text;
messagesEl.appendChild(div);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
window.addEventListener('message', event => {
if (event.data.command === 'receiveMessage') {
addMessage(event.data.text, 'bot');
}
});
messageInput.focus();
</script>
</body>
</html>`;
}