refactor.js
3.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env node
/**
* code-refactor - 代码重构与优化分析脚本
* Agent: evolver-youtube-crawler
*/
const fs = require('fs');
const path = require('path');
function parseArgs() {
const args = process.argv.slice(2);
const opts = {
target: '../../../../../system/templates/youtube-crawler/code/youtube_crawler.js',
report: '../../../workspace/evolver-youtube-crawler/refactor_report.md'
};
for (let i = 0; i < args.length; i++) {
if (args[i] === '--target') opts.target = args[i + 1];
if (args[i] === '--report') opts.report = args[i + 1];
}
return opts;
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
function analyzeCode(filepath) {
if (!fs.existsSync(filepath)) return { error: `Target file not found: ${filepath}` };
const code = fs.readFileSync(filepath, 'utf-8');
const lines = code.split('\n');
const hasModuleExports = code.includes('module.exports');
const hasJSDoc = code.includes('/**') && code.includes('*/');
const hasTryCatch = (code.match(/try\s*\{/g) || []).length;
const hasInputValidation = code.includes('throw') || code.includes('Error') || code.includes('validation');
const functionCount = (code.match(/function\s+\w+\s*\(/g) || []).length;
const arrowFunctionCount = (code.match(/\)\s*=>/g) || []).length;
const commentRatio = lines.filter(l => l.trim().startsWith('//') || l.trim().startsWith('*')).length / lines.length;
return {
filepath,
lines: lines.length,
functions: functionCount + arrowFunctionCount,
hasModuleExports,
hasJSDoc,
tryCatchBlocks: hasTryCatch,
hasInputValidation,
commentRatio: (commentRatio * 100).toFixed(1) + '%',
issues: []
.concat(!hasModuleExports ? ['缺少模块化导出 (module.exports)'] : [])
.concat(!hasJSDoc ? ['缺少 JSDoc 注释'] : [])
.concat(hasTryCatch < 2 ? ['错误处理覆盖不足,建议增加 try-catch'] : [])
.concat(!hasInputValidation ? ['缺少输入验证逻辑'] : [])
.concat(commentRatio < 0.05 ? ['注释率过低 (< 5%)'] : [])
};
}
function generateReport(analysis) {
if (analysis.error) return `# Refactor Report\n\n**Error:** ${analysis.error}\n`;
return `# Refactor Report - ${path.basename(analysis.filepath)}\n\n## 基础统计\n- **文件路径**: ${analysis.filepath}\n- **代码行数**: ${analysis.lines}\n- **函数数量**: ${analysis.functions}\n- **注释率**: ${analysis.commentRatio}\n\n## 检查项\n| 检查项 | 状态 |\n|--------|------|\n| 模块化导出 | ${analysis.hasModuleExports ? 'PASS' : 'FAIL'} |\n| JSDoc 注释 | ${analysis.hasJSDoc ? 'PASS' : 'FAIL'} |\n| 输入验证 | ${analysis.hasInputValidation ? 'PASS' : 'FAIL'} |\n| 错误处理 (>=2 try-catch) | ${analysis.tryCatchBlocks >= 2 ? 'PASS' : 'FAIL'} |\n\n## 待改进问题\n${analysis.issues.map(i => `- ${i}`).join('\n') || '- 暂无重大问题'}\n\n## 建议\n1. 将大函数拆分为单一职责的小函数。\n2. 为所有公共 API 添加 JSDoc。\n3. 统一错误处理策略,避免 swallow error。\n4. 增加单元测试覆盖边缘分支。\n`;
}
function main() {
const opts = parseArgs();
const targetPath = path.resolve(__dirname, opts.target);
const reportPath = path.resolve(__dirname, opts.report);
ensureDir(path.dirname(reportPath));
const analysis = analyzeCode(targetPath);
const report = generateReport(analysis);
fs.writeFileSync(reportPath, report, 'utf-8');
console.log(`Refactor report saved to: ${reportPath}`);
console.log(`Issues found: ${analysis.issues ? analysis.issues.length : 0}`);
}
main();