Files
wwjcloud-nest-v1/wwjcloud-nest-v1/tools/java-to-nestjs-migration/fix-service-files.js
wanwu 5c1647df7c feat: 完善所有TODO功能
- 实现CloudBuildService.clearBuildTask()方法
- 实现CoreAddonInstallService.handleAddonInstall()方法
- 实现QuartzJobManager动态Job加载机制
- 创建WwjcloudService和CloudBuildService接口和实现
- 实现zip解压功能(ZipUtils)
- 完善addon-service-impl.service.ts中的download和getIndexAddonList方法
- 添加JobProvider接口和注册机制
- 修复所有编译错误,代码编译通过
2025-11-01 21:29:54 +08:00

216 lines
6.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Service文件批量修复脚本
* 对照Java源码修复方法体不改业务逻辑只换V1写法
*/
const fs = require('fs');
const path = require('path');
const ServiceMethodConverter = require('./converters/service-method-converter');
// 读取映射数据
const mappingData = JSON.parse(
fs.readFileSync('./tools/java-to-nestjs-migration/service-mapping-data.json', 'utf-8')
);
const converter = new ServiceMethodConverter();
// 修复单个文件
function fixServiceFile(javaFile, nestjsFile) {
try {
// 读取Java源码
const javaContent = fs.readFileSync(javaFile, 'utf-8');
// 读取NestJS文件
let nestjsContent = fs.readFileSync(nestjsFile, 'utf-8');
// 提取Java方法体并修复
// 找到所有方法
const methodRegex = /@Override\s+public\s+([\w<>]+)\s+(\w+)\s*\([^)]*\)\s*\{([^}]+(?:\{[^}]*\}[^}]*)*)\}/g;
const javaMethods = [];
let match;
while ((match = methodRegex.exec(javaContent)) !== null) {
javaMethods.push({
returnType: match[1],
methodName: match[2],
methodBody: match[3]
});
}
// 如果正则没匹配到,尝试另一种方式
if (javaMethods.length === 0) {
// 简单的行扫描方式
const lines = javaContent.split('\n');
let inMethod = false;
let currentMethod = null;
let braceDepth = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// 检测方法开始
if (/public\s+[\w<>]+\s+\w+\s*\(/.test(line) ||
/@Override\s*\n\s*public\s+[\w<>]+\s+\w+\s*\(/.test(lines.slice(Math.max(0, i-1), i+1).join('\n'))) {
const methodMatch = line.match(/public\s+([\w<>]+)\s+(\w+)\s*\(/);
if (methodMatch) {
currentMethod = {
returnType: methodMatch[1],
methodName: methodMatch[2],
methodBody: '',
startLine: i
};
inMethod = true;
braceDepth = (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length;
if (!line.includes('{')) {
currentMethod.methodBody = line + '\n';
continue;
}
}
}
if (inMethod && currentMethod) {
currentMethod.methodBody += line + '\n';
braceDepth += (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length;
if (braceDepth === 0) {
javaMethods.push(currentMethod);
currentMethod = null;
inMethod = false;
}
}
}
}
// 修复每个方法
javaMethods.forEach(javaMethod => {
try {
// 转换方法体
const context = {
className: path.basename(javaFile, '.java'),
returnType: javaMethod.returnType
};
let convertedBody = converter.convertMethodBody(
javaMethod.methodBody,
context
);
// 应用手动修复规则
convertedBody = applyManualFixes(convertedBody, javaMethod.methodBody);
// 在NestJS文件中找到对应方法并替换
const nestjsMethodRegex = new RegExp(
`async\\s+${javaMethod.methodName}\\s*\\([^)]*\\)\\s*:\\s*Promise<[^>]+>\\s*\\{([^}]+(?:\\{[^}]*\\}[^}]*)*)\\}`,
's'
);
if (nestjsMethodRegex.test(nestjsContent)) {
nestjsContent = nestjsContent.replace(
nestjsMethodRegex,
(match, oldBody) => {
return match.replace(oldBody, '\n' + convertedBody.split('\n').map(l => ' ' + l).join('\n') + '\n ');
}
);
}
} catch (e) {
console.warn(` 警告: 修复方法 ${javaMethod.methodName} 失败: ${e.message}`);
}
});
// 保存修复后的文件
fs.writeFileSync(nestjsFile, nestjsContent, 'utf-8');
return true;
} catch (e) {
console.error(`修复文件失败 ${nestjsFile}: ${e.message}`);
return false;
}
}
// 应用手动修复规则
function applyManualFixes(convertedBody, originalJavaBody) {
let fixed = convertedBody;
// 1. 修复 ModuleListVo.const app → const app
fixed = fixed.replace(/ModuleListVo\.const\s+(\w+):/g, 'const $1:');
// 2. 修复方法调用xxx.yyy → xxx.getYyy()
// 但要小心,不能把所有属性访问都改了
// 这个需要更智能的判断
// 3. 修复Map操作list.put(key, value) → list[key] = value
fixed = fixed.replace(/(\w+)\.put\(([^,]+),\s*([^)]+)\)/g, '$1[$2] = $3');
// 4. 修复Map操作list.get(key) → list[key]
fixed = fixed.replace(/(\w+)\.get\(([^)]+)\)/g, '$1[$2]');
// 5. 修复属性访问item.getApp() → item.app (如果是简单getter)
fixed = fixed.replace(/(\w+)\.get([A-Z]\w+)\(\)/g, (match, obj, prop) => {
// 转换为camelCase
const propName = prop.charAt(0).toLowerCase() + prop.slice(1);
return `${obj}.${propName}`;
});
// 6. 修复JSON操作info.getStr("key") → info["key"] 或 info.key
fixed = fixed.replace(/(\w+)\.getStr\(["']([^"']+)["']\)/g, '$1["$2"]');
fixed = fixed.replace(/(\w+)\.get(?:Int|Bool|Obj|Array)\(["']([^"']+)["']\)/g, '$1["$2"]');
// 7. 修复数组访问windowLogo[0] → windowLogo?.[0] (如果可能为undefined)
// 这个先不处理,保持原样
// 8. 修复变量赋值xxx.yyy → xxx.yyy (保持)
// 9. 修复异常处理e.printStackTrace() → console.error(e)
fixed = fixed.replace(/(\w+)\.printStackTrace\(\)/g, 'console.error($1)');
// 10. 修复文件路径file + "/resource/icon.png" → path.join(file, "resource/icon.png")
fixed = fixed.replace(/(\w+)\s*\+\s*["']\/([^"']+)["']/g, 'path.join($1, "$2")');
return fixed;
}
// 主函数
function main() {
console.log(`开始修复 ${mappingData.length} 个Service文件...\n`);
let successCount = 0;
let failCount = 0;
mappingData.forEach((item, index) => {
const { javaFile, nestjsFile } = item;
if (!fs.existsSync(javaFile)) {
console.log(`❌ [${index + 1}/${mappingData.length}] Java文件不存在: ${javaFile}`);
failCount++;
return;
}
if (!fs.existsSync(nestjsFile)) {
console.log(`❌ [${index + 1}/${mappingData.length}] NestJS文件不存在: ${nestjsFile}`);
failCount++;
return;
}
console.log(`🔧 [${index + 1}/${mappingData.length}] 修复: ${path.basename(nestjsFile)}`);
if (fixServiceFile(javaFile, nestjsFile)) {
successCount++;
console.log(` ✅ 成功\n`);
} else {
failCount++;
console.log(` ❌ 失败\n`);
}
});
console.log(`\n修复完成!`);
console.log(`成功: ${successCount}`);
console.log(`失败: ${failCount}`);
}
if (require.main === module) {
main();
}
module.exports = { fixServiceFile, applyManualFixes };