codec-ai
Version:
Codec AI - 智能代码生成和编程助手,支持多语言代码生成、项目脚手架、代码转换和优化
133 lines • 5.16 kB
JavaScript
import fs from 'fs-extra';
import path from 'path';
export class CodeConverter {
conversionRules = {
'javascript': {
'typescript': (code) => this.jsToTs(code),
'python': (code) => this.jsToPython(code)
},
'typescript': {
'javascript': (code) => this.tsToJs(code),
'python': (code) => this.tsToPython(code)
},
'python': {
'javascript': (code) => this.pythonToJs(code),
'typescript': (code) => this.pythonToTs(code)
}
};
async convertCode(options) {
const { sourcePath, fromLanguage, toLanguage, outputPath } = options;
// 检查源文件是否存在
if (!await fs.pathExists(sourcePath)) {
throw new Error(`源文件不存在: ${sourcePath}`);
}
// 检查转换支持
const fromRules = this.conversionRules[fromLanguage];
if (!fromRules) {
throw new Error(`不支持源语言: ${fromLanguage}`);
}
const converter = fromRules[toLanguage];
if (!converter) {
throw new Error(`不支持从 ${fromLanguage} 转换到 ${toLanguage}`);
}
// 读取源文件
const sourceCode = await fs.readFile(sourcePath, 'utf8');
// 执行转换
const startTime = Date.now();
const convertedCode = converter(sourceCode);
const conversionTime = Date.now() - startTime;
// 确定输出路径
let finalOutputPath = outputPath;
if (!finalOutputPath) {
const extMap = {
javascript: '.js',
typescript: '.ts',
python: '.py',
java: '.java',
go: '.go',
rust: '.rs'
};
const ext = extMap[toLanguage] || '.txt';
const baseName = path.basename(sourcePath, path.extname(sourcePath));
finalOutputPath = path.join(path.dirname(sourcePath), `${baseName}${ext}`);
}
// 写入输出文件
await fs.writeFile(finalOutputPath, convertedCode, 'utf8');
return {
code: convertedCode,
outputPath: finalOutputPath,
stats: {
lineCount: convertedCode.split('\n').length,
conversionTime
}
};
}
jsToTs(code) {
// 简单的 JS 到 TS 转换规则
let tsCode = code;
// 添加基本类型注解
tsCode = tsCode.replace(/function\s+(\w+)\(([^)]*)\)/g, 'function $1($2): any');
tsCode = tsCode.replace(/const\s+(\w+)\s*=/g, 'const $1: any =');
tsCode = tsCode.replace(/let\s+(\w+)\s*=/g, 'let $1: any =');
// 添加 export 语句
if (!tsCode.includes('export') && tsCode.includes('module.exports')) {
tsCode = tsCode.replace(/module\.exports\s*=\s*{([^}]*)}/g, 'export { $1 }');
}
return `// 由 JavaScript 自动转换为 TypeScript
${tsCode}`;
}
tsToJs(code) {
// 简单的 TS 到 JS 转换规则
let jsCode = code;
// 移除类型注解
jsCode = jsCode.replace(/:\s*\w+(?:<[^>]*>)?\s*(?=\=|\{|\n|,|\))/g, '');
jsCode = jsCode.replace(/<[^>]*>/g, '');
// 转换 export 语句
jsCode = jsCode.replace(/export\s+(?:default\s+)?(?:class|function|const|let|var)\s+(\w+)/g, '$1');
jsCode = jsCode.replace(/export\s*{\s*([^}]+)\s*}/g, 'module.exports = { $1 }');
return `// 由 TypeScript 自动转换为 JavaScript
${jsCode}`;
}
jsToPython(code) {
// 简单的 JS 到 Python 转换规则
let pythonCode = code;
// 转换函数定义
pythonCode = pythonCode.replace(/function\s+(\w+)\(([^)]*)\)\s*{/g, 'def $1($2):');
// 转换变量声明
pythonCode = pythonCode.replace(/const\s+/g, '');
pythonCode = pythonCode.replace(/let\s+/g, '');
pythonCode = pythonCode.replace(/var\s+/g, '');
// 转换花括号
pythonCode = pythonCode.replace(/\{/g, '');
pythonCode = pythonCode.replace(/}/g, '');
// 转换分号
pythonCode = pythonCode.replace(/;/g, '');
// 转换注释
pythonCode = pythonCode.replace(/\/\//g, '#');
pythonCode = pythonCode.replace(/\/\*\*/g, '"""');
return `""" 由 JavaScript 自动转换为 Python """
${pythonCode}`;
}
pythonToJs(code) {
// 简单的 Python 到 JS 转换规则
let jsCode = code;
// 转换函数定义
jsCode = jsCode.replace(/def\s+(\w+)\(([^)]*)\):/g, 'function $1($2) {');
// 转换注释
jsCode = jsCode.replace(/#/g, '//');
jsCode = jsCode.replace(/"""/g, '/**');
// 添加花括号和分号
jsCode = jsCode.replace(/\n(\s*\w)/g, '\n$1');
return `// 由 Python 自动转换为 JavaScript
${jsCode}`;
}
tsToPython(code) {
const jsCode = this.tsToJs(code);
return this.jsToPython(jsCode);
}
pythonToTs(code) {
const jsCode = this.pythonToJs(code);
return this.jsToTs(jsCode);
}
}
//# sourceMappingURL=converter.js.map