强烈建议统一格式。这是工程实践中的关键决策,直接影响系统的可维护性、准确性和扩展性。以下是详细分析:
一、为什么必须统一格式
1. 大模型的稳定性问题
虽然大模型能理解多种格式,但在生产环境中存在风险:
- 输出不稳定:相同问题不同格式可能导致不同判断(如ESLint的JSON和TSC的文本格式描述同一个未使用变量,模型可能给出不同结论)
- Token浪费:需要在每个prompt中解释多种格式,增加API成本
- 错误传播:格式解析错误会导致整个判断失效
2. 工程化的必要性
原始报告 → 统一中间层 → 大模型 → 结构化输出
↓ ↓ ↓ ↓
多格式 标准Schema 稳定处理 可追溯
统一格式是构建可靠数据管道的基础,便于:
- 数据验证(Schema validation)
- 错误定位(哪个工具的哪条规则出错)
- 增量更新(只处理变化的部分)
二、推荐的统一格式设计
标准化Schema示例(TypeScript定义):
interface UnifiedCodeIssue {
// 核心标识
id: string; // 唯一ID,如 "eslint-no-unused-vars-src/utils/helper.ts-12-5"
type: 'unused' | 'duplicate' | 'dead-code' | 'dependency';
severity: 'error' | 'warning' | 'info';
// 位置信息
location: {
file: string; // 相对路径,如 "src/components/UserCard.tsx"
startLine: number;
startColumn: number;
endLine?: number;
endColumn?: number;
};
// 问题描述
description: string; // 统一的问题描述
code: string; // 相关代码片段
identifier?: string; // 变量/函数/组件名
// 元信息
source: {
tool: 'eslint' | 'tsc' | 'jscpd' | 'depcheck';
rule: string; // 如 "no-unused-vars"
originalMessage: string; // 工具原始信息
};
// 上下文增强(关键!)
context: {
references: string[]; // 引用位置列表
dynamicPatterns: string[]; // 可能的动态调用模式,如 "obj[identifier]"
comments: string[]; // 相关注释,如 "// TODO: 待实现"
importedFrom: string[]; // 被哪些文件导入
exportType?: 'default' | 'named' | 'namespace';
};
// 去重标识
fingerprint: string; // 基于type+location+identifier生成的哈希
}
格式转换示例:
// ESLint原始输出
{
"filePath": "/src/utils/helper.ts",
"messages": [{
"ruleId": "no-unused-vars",
"severity": 2,
"message": "'calculateTax' is defined but never used.",
"line": 12,
"column": 5
}]
}
// 转换为统一格式
{
"id": "eslint-no-unused-vars-src/utils/helper.ts-12-5",
"type": "unused",
"severity": "error",
"location": {
"file": "src/utils/helper.ts",
"startLine": 12,
"startColumn": 5
},
"description": "Function 'calculateTax' is defined but never used",
"identifier": "calculateTax",
"source": {
"tool": "eslint",
"rule": "no-unused-vars",
"originalMessage": "'calculateTax' is defined but never used."
},
"context": {
"references": [],
"dynamicPatterns": ["utils[functionName]", "this.calculateTax"],
"comments": ["// Legacy function, might be used in old reports"],
"importedFrom": []
},
"fingerprint": "unused-function-calculateTax-helper.ts-12"
}
三、实现统一格式的最佳实践
1. 构建适配器模式
// 适配器接口
interface ReportAdapter<T> {
parse(rawReport: T): UnifiedCodeIssue[];
validate(rawReport: T): boolean;
}
// ESLint适配器实现
class ESLintAdapter implements ReportAdapter<ESLintReport> {
parse(report: ESLintReport): UnifiedCodeIssue[] {
return report.results.flatMap(file =>
file.messages.map(msg => this.convertMessage(file.filePath, msg))
);
}
private convertMessage(filePath: string, msg: ESLintMessage): UnifiedCodeIssue {
// 转换逻辑
}
}
// 统一处理器
class UnifiedReportProcessor {
private adapters = {
eslint: new ESLintAdapter(),
tsc: new TSCAdapter(),
jscpd: new JSCPDAdapter(),
depcheck: new DepcheckAdapter()
};
process(reports: RawReports): UnifiedCodeIssue[] {
const allIssues = [
...this.adapters.eslint.parse(reports.eslint),
...this.adapters.tsc.parse(reports.tsc),
...this.adapters.jscpd.parse(reports.jscpd),
...this.adapters.depcheck.parse(reports.depcheck)
];
return this.deduplicate(allIssues);
}
private deduplicate(issues: UnifiedCodeIssue[]): UnifiedCodeIssue[] {
// 基于fingerprint去重
const seen = new Set<string>();
return issues.filter(issue => {
if (seen.has(issue.fingerprint)) return false;
seen.add(issue.fingerprint);
return true;
});
}
}
2. 增强上下文信息
统一格式时必须补充静态工具缺失的上下文:
class ContextEnhancer {
enhance(issue: UnifiedCodeIssue, codebase: CodebaseIndex): UnifiedCodeIssue {
return {
...issue,
context: {
...issue.context,
// 查找所有可能的动态引用
dynamicPatterns: this.findDynamicPatterns(issue.identifier, codebase),
// 提取相关注释
comments: this.extractComments(issue.location, codebase),
// 查找导入关系
importedFrom: this.findImports(issue.identifier, issue.location.file, codebase)
}
};
}
}
3. 优化大模型输入
统一格式后,可以批量处理同类问题:
// 批量处理未使用的函数
const unusedFunctions = issues.filter(i => i.type === 'unused' && i.identifier);
const prompt = `
以下是项目中检测到的未使用函数列表(JSON格式):
${JSON.stringify(unusedFunctions, null, 2)}
请分析每个函数,返回JSON格式的判断结果:
{
"decisions": [{
"id": "issue-id",
"action": "delete" | "keep" | "need-review",
"reason": "判断理由",
"suggestion": "具体修改建议"
}]
}
`;
四、格式统一的额外收益
1. 可视化与监控
统一格式便于构建监控面板:
// 技术债务趋势图数据
const trendData = issues.reduce((acc, issue) => {
const date = issue.detectedAt;
acc[date] = acc[date] || { unused: 0, duplicate: 0, dead: 0 };
acc[date][issue.type]++;
return acc;
}, {});
2. 规则优先级管理
// 基于统一格式设置处理优先级
const priorityRules = {
'unused-global-component': 10, // 全局组件优先处理
'duplicate-api-call': 8, // API调用重复次之
'unused-local-variable': 3 // 局部变量最后
};
issues.sort((a, b) => {
const priorityA = getPriority(a);
const priorityB = getPriority(b);
return priorityB - priorityA;
});
3. 增量处理支持
// 基于fingerprint实现增量
const processedIssues = await db.getProcessedFingerprints();
const newIssues = issues.filter(i => !processedIssues.has(i.fingerprint));
五、实施建议
-
分阶段实施:
- Phase 1:实现基础适配器,支持最常用的工具(ESLint、TSC)
- Phase 2:增加上下文增强,提高判断准确性
- Phase 3:优化去重算法,支持跨工具去重
-
保留原始信息:
在source.originalMessage中保留原始信息,便于调试和追溯
-
版本控制:
统一格式也需要版本管理,便于后续升级:
{
"version": "1.0.0",
"issues": [...]
}
总结:统一格式是构建可靠、可扩展的冗余代码检测系统的基石。虽然初期需要投入开发适配器,但长期收益远大于成本,特别是在处理百万行代码的规模时,格式统一带来的稳定性和可维护性至关重要。