Skip to content

Commit 28fc501

Browse files
committed
文件取名
1 parent fda8187 commit 28fc501

File tree

2 files changed

+107
-35
lines changed

2 files changed

+107
-35
lines changed

src/cvbManager.ts

Lines changed: 60 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as path from 'path';
33
import * as jschardet from 'jschardet'; // 编码检测库
44
import * as iconv from 'iconv-lite'; // 编码转换库
55
import * as vscode from 'vscode';
6+
import { generateFilenameFromRequest } from './deepseekApi';
67

78
// 语言映射表
89
const languageMapping: { [key: string]: string } = {
@@ -78,55 +79,79 @@ function isLikelyGBK(buffer: Buffer): boolean {
7879
return false;
7980
}
8081

82+
function generateTimestamp(): string {
83+
const now = new Date();
84+
const year = now.getFullYear().toString().slice(-2);
85+
const month = (now.getMonth() + 1).toString().padStart(2, '0');
86+
const day = now.getDate().toString().padStart(2, '0');
87+
const hour = now.getHours().toString().padStart(2, '0');
88+
const minute = now.getMinutes().toString().padStart(2, '0');
89+
const second = now.getSeconds().toString().padStart(2, '0');
90+
return `${year}${month}${day}${hour}${minute}${second}`;
91+
}
92+
8193
/**
8294
* 生成 CVB 格式的文件
8395
* @param filePaths 文件路径数组
8496
* @param workspacePath 工作目录路径
8597
* @param userRequest 用户输入的重构需求
8698
* @returns 生成的 CVB 文件路径
8799
*/
88-
export function generateCvb(filePaths: string[], workspacePath: string, userRequest: string): string {
89-
// 创建临时目录(如果不存在)
90-
const tmpDir = path.join(workspacePath, 'CodeReDesignWorkSpace', 'tmp');
91-
if (!fs.existsSync(tmpDir)) {
92-
fs.mkdirSync(tmpDir, { recursive: true });
93-
}
100+
export async function generateCvb(filePaths: string[], workspacePath: string, userRequest: string): Promise<string> {
101+
// Create temporary directory (if not exists)
102+
const tmpDir = path.join(workspacePath, 'CodeReDesignWorkSpace', 'tmp');
103+
if (!fs.existsSync(tmpDir)) {
104+
fs.mkdirSync(tmpDir, { recursive: true });
105+
}
94106

95-
// 生成 CVB 头部
96-
const timestamp = new Date().toISOString();
97-
let cvbContent = `## BEGIN_CVB\n`;
98-
cvbContent += `## META\n`;
99-
cvbContent += `@用户需求: ${userRequest}\n`;
100-
cvbContent += `@时间戳: ${timestamp}\n`;
101-
cvbContent += `## END_META\n\n`;
102-
103-
// 生成 CVB 正文(文件内容)
104-
filePaths.forEach(filePath => {
105-
try {
106-
const fileContent = readFileWithEncoding(filePath);
107-
const ext = path.extname(filePath).slice(1).toLowerCase();
108-
const lang = languageMapping[ext] || 'text';
109-
cvbContent += `## FILE:${filePath}\n`;
110-
cvbContent += '```' + lang + '\n';
111-
cvbContent += fileContent + '\n';
112-
cvbContent += '```\n\n';
113-
} catch (error) {
114-
console.error(`Failed to read file ${filePath}:`, error);
107+
// Generate CVB header
108+
const timestamp = generateTimestamp();
109+
let cvbContent = `## BEGIN_CVB\n`;
110+
cvbContent += `## META\n`;
111+
cvbContent += `@用户需求: ${userRequest}\n`;
112+
cvbContent += `@时间戳: ${timestamp}\n`;
113+
cvbContent += `## END_META\n\n`;
114+
115+
// Generate CVB body (file contents)
116+
for (const filePath of filePaths) {
117+
try {
118+
const fileContent = readFileWithEncoding(filePath);
119+
const ext = path.extname(filePath).slice(1).toLowerCase();
120+
const lang = languageMapping[ext] || 'text';
121+
cvbContent += `## FILE:${filePath}\n`;
122+
cvbContent += '```' + lang + '\n';
123+
cvbContent += fileContent + '\n';
124+
cvbContent += '```\n\n';
125+
} catch (error) {
126+
console.error(`Failed to read file ${filePath}:`, error);
127+
}
115128
}
116-
});
117129

118-
// 添加 CVB 结束标记
119-
cvbContent += `## END_CVB\n`;
130+
// Get summary of user request for filename
131+
let summary = await generateFilenameFromRequest (userRequest);
132+
if (!summary || summary.length === 0) {
133+
summary = 'default';
134+
}
120135

121-
// 生成 CVB 文件名(使用时间戳)
122-
const cvbFilePath = path.join(tmpDir, `${new Date().getTime()}.cvb`);
136+
// Create the base filename
137+
let baseFileName = `${timestamp}_${summary}.cvb`;
123138

124-
// 将 CVB 内容写入文件
125-
fs.writeFileSync(cvbFilePath, cvbContent, 'utf-8');
139+
// Ensure the filename is unique
140+
let fileName = baseFileName;
141+
let i = 1;
142+
while (fs.existsSync(path.join(tmpDir, fileName))) {
143+
fileName = `${timestamp}_${summary}_${i}.cvb`;
144+
i++;
145+
}
126146

127-
return cvbFilePath;
128-
}
147+
// Full path for the CVB file
148+
const cvbFilePath = path.join(tmpDir, fileName);
129149

150+
// Write CVB content to file
151+
fs.writeFileSync(cvbFilePath, cvbContent, 'utf-8');
152+
153+
return cvbFilePath;
154+
}
130155
/**
131156
* 解析 CVB 格式内容
132157
* @param cvbContent CVB 内容

src/deepseekApi.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,51 @@ ${cvbContent}
8686
vscode.window.showErrorMessage('Failed to call DeepSeek API: ' + (error as Error).message);
8787
return null;
8888
}
89+
}
90+
91+
function cleanFilename(str: string) {
92+
// Replace invalid filename characters for Windows with underscores
93+
return str.replace(/[\\/:*?"<>|]/g, '_');
94+
}
95+
96+
export async function generateFilenameFromRequest(userRequest: string): Promise<string> {
97+
const apiKey = getDeepSeekApiKey();
98+
if (!apiKey) {
99+
return 'default';
100+
}
101+
102+
try {
103+
const openai = new OpenAI({
104+
apiKey: apiKey,
105+
baseURL: 'https://api.deepseek.com',
106+
});
107+
108+
const summaryResponse = await openai.chat.completions.create({
109+
model: 'deepseek-chat',
110+
messages: [
111+
{ role: 'system', content: '你是一个工具函数,接收请求,只返回纯结果,不要有附加说明.' },
112+
{ role: 'user', content: `请简单概括一下需求,输出字符串作为文件名。如果描述里有版本名称,这个名称一定要保留并放在开头。 需求:"${userRequest}"` },
113+
],
114+
max_tokens: 100,
115+
temperature: 0,
116+
});
117+
118+
let summary = summaryResponse.choices[0]?.message?.content || '';
119+
console.log('Raw Summary:', summary);
120+
121+
// Clean the summary
122+
summary = cleanFilename(summary);
123+
summary = summary.replace(/^\.+|\.+$/g, ''); // Remove leading/trailing dots
124+
summary = summary.replace(/^ +| +$/g, ''); // Remove leading/trailing spaces
125+
summary = summary.substring(0, 15); // Truncate to 5 characters
126+
127+
if (summary.length === 0) {
128+
summary = 'summary';
129+
}
130+
131+
return summary;
132+
} catch (error) {
133+
vscode.window.showErrorMessage('Failed to summarize request: ' + (error as Error).message);
134+
return 'error';
135+
}
89136
}

0 commit comments

Comments
 (0)