Skip to content

Commit e6cbbd5

Browse files
committed
fix:修正一系列格式解析问题
1 parent c717e9b commit e6cbbd5

File tree

4 files changed

+112
-80
lines changed

4 files changed

+112
-80
lines changed

prompt/testdata2.txt

Lines changed: 87 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,107 @@
1-
```TCVB
1+
```markdown
22
## BEGIN_TCVB
3-
4-
## FILE:k:\lab\CodeReDesign-dummy\src\siderBar.ts
5-
## OPERATION:INSERT
6-
## BEFORE_ANCHOR
3+
## FILE:k:\lab\CodeReDesign-dummy\src\extension.ts
4+
## OPERATION:GLOBAL-REPLACE
5+
## OLD_CONTENT
76
```typescript
8-
export function registerCvbContextMenu(context: vscode.ExtensionContext) {
7+
let apiResponse = await queryCodeReDesign(cvbContent, userPrompt, outputChannel, getCurrentOperationController().signal);
8+
let processSuccess = true;
9+
do{
10+
try {
11+
if (apiResponse) {
12+
const tcvb = new TCVB(apiResponse);
13+
const oldCvb = new Cvb(cvbContent);
14+
const cvb = mergeCvb(oldCvb, tcvb);
915

10-
// 注册右键菜单命令
11-
const applyCvbCommand = vscode.commands.registerCommand('codeReDesign.applyThisCvb', (cvb: CvbFile) => {
12-
```
13-
## AFTER_ANCHOR
14-
```typescript
15-
const workspaceFolders = vscode.workspace.workspaceFolders;
16-
if (workspaceFolders) {
17-
const targetFolder = path.join(workspaceFolders[0].uri.fsPath, '.CodeReDesignWorkSpace'); // 替换为你的子文件夹名称
16+
processSuccess = true;
1817

19-
// 创建文件系统监听器
18+
cvb.setMetaData("用户需求", userPrompt);
19+
const newCvbFilePath = path.join(tmpDir, fileName);
20+
fs.writeFileSync(newCvbFilePath, cvb.toString(), 'utf-8');
21+
vscode.window.showInformationMessage(`API response saved as CVB file: ${newCvbFilePath}`);
22+
}
23+
} catch (err : any){
24+
apiResponse = await callDeepSeekFixApi(err.message, outputChannel, true, getCurrentOperationController().signal);
25+
processSuccess = false;
26+
}
27+
} while (!processSuccess);
2028
```
21-
## INSERT_CONTENT
29+
## NEW_CONTENT
2230
```typescript
23-
// 监听 .tcvb 和 .md 文件变化
24-
const markdownWatcher = vscode.workspace.createFileSystemWatcher(
25-
new vscode.RelativePattern(targetFolder, '**/*.md')
26-
);
31+
let apiResponse = await queryCodeReDesign(cvbContent, userPrompt, outputChannel, getCurrentOperationController().signal);
32+
let processSuccess = true;
33+
do{
34+
try {
35+
if (apiResponse) {
36+
const tcvb = new TCVB(apiResponse);
37+
const oldCvb = new Cvb(cvbContent);
38+
const tcvbFilePath = path.join(tmpDir, `${fileName}.tcvb`);
39+
fs.writeFileSync(tcvbFilePath, tcvb.toString(), 'utf-8');
2740

28-
const tcvbWatcher = vscode.workspace.createFileSystemWatcher(
29-
new vscode.RelativePattern(targetFolder, '**/*.tcvb')
30-
);
41+
const cvb = mergeCvb(oldCvb, tcvb);
3142

32-
// 当文件变化时刷新视图
33-
markdownWatcher.onDidCreate(() => cvbViewProvider.refresh());
34-
markdownWatcher.onDidDelete(() => cvbViewProvider.refresh());
35-
markdownWatcher.onDidChange(() => cvvViewProvider.refresh());
43+
processSuccess = true;
3644

37-
tcvbWatcher.onDidCreate(() => cvbViewProvider.refresh());
38-
tcvbWatcher.onDidDelete(() => cvbViewProvider.refresh());
39-
tcvbWatcher.onDidChange(() => cvbViewProvider.refresh());
45+
cvb.setMetaData("用户需求", userPrompt);
46+
const newCvbFilePath = path.join(tmpDir, fileName);
47+
fs.writeFileSync(newCvbFilePath, cvb.toString(), 'utf-8');
48+
vscode.window.showInformationMessage(`API response saved as CVB file: ${newCvbFilePath}`);
49+
}
50+
} catch (err : any){
51+
apiResponse = await callDeepSeekFixApi(err.message, outputChannel, true, getCurrentOperationController().signal);
52+
processSuccess = false;
53+
}
54+
} while (!processSuccess);
55+
```
56+
## OPERATION:GLOBAL-REPLACE
57+
## OLD_CONTENT
58+
```typescript
59+
const analysisResult = await analyzeCode(cvbContent, userRequest, outputChannel, getCurrentOperationController().signal);
60+
if (analysisResult) {
61+
vscode.window.showInformationMessage('Analysis completed. Check the output channel for details.');
62+
}
4063

41-
// 将监听器添加到订阅中,确保扩展销毁时清理资源
42-
context.subscriptions.push(markdownWatcher, tcvbWatcher);
43-
}
64+
vscode.window.showInformationMessage('解析完毕');
4465
```
66+
## NEW_CONTENT
67+
```typescript
68+
const analysisResult = await analyzeCode(cvbContent, userRequest, outputChannel, getCurrentOperationController().signal);
69+
if (analysisResult) {
70+
const analysisFilePath = path.join(tmpDir, `${fileName}.md`);
71+
fs.writeFileSync(analysisFilePath, analysisResult, 'utf-8');
72+
vscode.window.showInformationMessage(`Analysis result saved as file: ${analysisFilePath}`);
73+
}
4574

46-
## FILE:k:\lab\CodeReDesign-dummy\src\deepseekApi.ts
47-
## OPERATION:INSERT
48-
## BEFORE_ANCHOR
75+
vscode.window.showInformationMessage('解析完毕');
76+
```
77+
78+
## FILE:k:\lab\CodeReDesign-dummy\src\siderBar.ts
79+
## OPERATION:EXACT-REPLACE
80+
## OLD_CONTENT
4981
```typescript
50-
if (apiResponse) {
51-
apiResponse = apiResponse.replace(/\r\n?/g, "\n");
52-
const tcvb = new TCVB(apiResponse);
82+
if (file.endsWith('.cvb')) {
83+
const filePath = path.join(targetFolder, file);
84+
cvbFiles.push(new CvbFile(file, vscode.Uri.file(filePath)));
85+
}
5386
```
54-
## AFTER_ANCHOR
87+
## NEW_CONTENT
88+
```typescript
89+
if (file.endsWith('.cvb') || file.endsWith('.tcvb') || file.endsWith('.md')) {
90+
const filePath = path.join(targetFolder, file);
91+
cvbFiles.push(new CvbFile(file, vscode.Uri.file(filePath)));
92+
}
93+
```
94+
## BEFORE_ANCHOR
5595
```typescript
56-
cvb.setMetaData("用户需求", userPrompt);
57-
const newCvbFilePath = path.join(tmpDir, fileName);
58-
fs.writeFileSync(newCvbFilePath, cvb.toString(), 'utf-8');
96+
const files = fs.readdirSync(targetFolder);
97+
files.forEach(file => {
5998
```
60-
## INSERT_CONTENT
99+
## AFTER_ANCHOR
61100
```typescript
62-
// 保存 TCVB 文件
63-
const tcvbFilename = path.join(tmpDir, `${path.basename(fileName, '.cvb')}.tcvb`);
64-
fs.writeFileSync(tcvbFilename, apiResponse, 'utf-8');
65-
66-
// 保存分析结果
67-
const analysisFilename = path.join(tmpDir, `${path.basename(fileName, '.cvb')}_analysis.md`);
68-
fs.writeFileSync(analysisFilename, '分析结果\n\n' + analysisResult, 'utf-8');
101+
// 新增排序逻辑
102+
cvbFiles.sort((a, b) =>
103+
a.label.localeCompare(b.label, undefined, { sensitivity: 'base' })
104+
);
69105
```
70-
71106
## END_TCVB
72107
```

src/cvbManager.ts

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -48,19 +48,19 @@ export class Cvb
4848

4949
public getUserRequest() : string
5050
{
51-
return this.m_recMetadata['@用户需求'] || '';
51+
return this.m_recMetadata['用户需求'] || '';
5252
}
5353

5454
public getTimestamp() : string
5555
{
56-
return this.m_recMetadata['@时间戳'] || '';
56+
return this.m_recMetadata['时间戳'] || '';
5757
}
5858

5959
public toString(): string {
6060
// 将元数据转换成字符串
6161
let metaStr = '## META\n';
6262
for (const key in this.m_recMetadata) {
63-
metaStr += `${key}: ${this.m_recMetadata[key]}\n`;
63+
metaStr += `@${key}: ${this.m_recMetadata[key]}\n`;
6464
}
6565
metaStr += '## END_META\n';
6666

@@ -72,25 +72,22 @@ export class Cvb
7272
}
7373

7474
// 重新组装整个 CVB 内容
75-
const cvbContent = `## BEGIN_CVB
76-
${metaStr}
77-
${filesStr}
78-
## END_CVB`;
75+
const cvbContent = `## BEGIN_CVB\n${metaStr}\n${filesStr}\n## END_CVB`;
7976
return cvbContent;
8077
}
8178

8279
private parse(strCvbContent: string) : { cvbContent: string, metadata: Record<string, string>, files: Record<string, string> }
8380
{
8481
// 查找 CVB 开始与结束标记
85-
const regCvbStart: RegExp = /^## BEGIN_CVB(\s|$)/m;
82+
const regCvbStart: RegExp = /^## BEGIN_CVB$/m;
8683
const arrStartMatch = regCvbStart.exec(strCvbContent);
8784
if (!arrStartMatch)
8885
{
8986
throw new Error('Invalid CVB format: missing BEGIN_CVB marker.');
9087
}
91-
const iCvbStartIndex = arrStartMatch.index;
88+
const iCvbStartIndex = arrStartMatch.index + arrStartMatch[0].length;
9289

93-
const regCvbEnd: RegExp = /^## END_CVB(\s|$)/m;
90+
const regCvbEnd: RegExp = /^## END_CVB$/m;
9491
const arrEndMatch = regCvbEnd.exec(strCvbContent);
9592
if (!arrEndMatch)
9693
{
@@ -99,7 +96,7 @@ export class Cvb
9996
const iCvbEndIndex = arrEndMatch.index;
10097

10198
// 提取 CVB 部分内容
102-
const strCvbContentPart = strCvbContent.slice(iCvbStartIndex, iCvbEndIndex + arrEndMatch[0].length);
99+
const strCvbContentPart = strCvbContent.slice(iCvbStartIndex, iCvbEndIndex);
103100

104101
// 解析 META 部分
105102
const regMeta: RegExp = /^## META\n([\s\S]*?)^## END_META(\s|$)/m;
@@ -108,25 +105,23 @@ export class Cvb
108105
{
109106
throw new Error('Invalid CVB format: missing META section.');
110107
}
111-
const recMetadata: Record<string, string> = { };
112-
const arrMetaLines = arrMetaMatch[1].trim().split('\n');
113-
for (const strLine of arrMetaLines)
108+
109+
const recMetadata: Record<string, string> = {};
110+
const strMetaData = arrMetaMatch[1].trim();
111+
112+
const regex = /^@([^:\n]+):([\s\S]*?)(?=^@|(?![\s\S]))/gm;
113+
let match;
114+
115+
while ((match = regex.exec(strMetaData)) !== null)
114116
{
115-
const arrParts = strLine.split(':');
116-
if (arrParts.length >= 2)
117-
{
118-
const strKey = arrParts.shift()?.trim();
119-
const strValue = arrParts.join(':').trim();
120-
if (strKey)
121-
{
122-
recMetadata[strKey] = strValue;
123-
}
124-
}
117+
const strKey = match[1].trim();
118+
const strValue = match[2].trim();
119+
recMetadata[strKey] = strValue;
125120
}
126121

127122
// 解析文件部分
128123
const recFiles: Record<string, string> = { };
129-
const regFile: RegExp = /^## FILE:([^<\r\n]+)\n([\s\S]*?)(?=^## FILE:|^## END_CVB)/gm;
124+
const regFile: RegExp = /^## FILE:([^<\r\n]+)\n([\s\S]*?)(?=^## FILE:([^<\r\n]+)|(?![\s\S]))/gm;
130125
let arrFileMatch: RegExpExecArray | null;
131126
while ((arrFileMatch = regFile.exec(strCvbContentPart)) !== null)
132127
{
@@ -566,7 +561,7 @@ function rebuildCvb(baseCvb: Cvb, mapFiles: Map<string, string>) : Cvb
566561
const recMetadata = baseCvb.getMetadata();
567562
for (const [strKey, strValue] of Object.entries(recMetadata))
568563
{
569-
strNewContent += `${strKey}: ${strValue}\n`;
564+
strNewContent += `@${strKey}: ${strValue}\n`;
570565
}
571566
strNewContent += `## END_META\n\n`;
572567

src/extension.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ export async function doUploadCommand(cvbFilePath: string, userPrompt: string, o
7272
vscode.window.showInformationMessage(`API response saved as CVB file: ${newCvbFilePath}`);
7373
}
7474
} catch (err : any){
75+
vscode.window.showInformationMessage(`API response have error, try fix ...`);
7576
apiResponse = await callDeepSeekFixApi(err.message, outputChannel, true, getCurrentOperationController().signal);
7677
processSuccess = false;
7778
}

src/siderBar.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ function applyThisCvb(filePath: string) {
160160
* @param filePath .cvb 文件的路径
161161
*/
162162
async function uploadThisCvb(filePath: string) {
163-
/*
163+
164164
// 测试 begin
165165
{
166166
const workspaceFolders = vscode.workspace.workspaceFolders;
@@ -177,9 +177,10 @@ async function uploadThisCvb(filePath: string) {
177177
cvbContent = cvbContent.replace(/\r\n?/g, "\n");
178178
const oldCvb = new Cvb(cvbContent);
179179
const cvb = mergeCvb(oldCvb, tcvb);
180+
console.log(cvb.toString());
180181
}
181182
// 测试 end
182-
*/
183+
183184
const userPrompt = await vscode.window.showInputBox({
184185
prompt: 'Enter your prompt for the refactoring',
185186
placeHolder: 'e.g., Refactor the code to improve readability',

0 commit comments

Comments
 (0)