!454 fix codecheck

Merge pull request !454 from wshikh/OpenHarmony-4.0-Release
This commit is contained in:
openharmony_ci 2024-09-10 10:12:58 +00:00 committed by Gitee
commit ca5a3051c2
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
25 changed files with 1591 additions and 1444 deletions

View File

@ -43,28 +43,28 @@ function activate(context) {
context.subscriptions.push(disposable);
context.subscriptions.push(disposableMenu);
var platform = detectPlatform();
if (platform == 'win') {
exeFilePath = __dirname + "/search-win.exe";
} else if (platform == 'mac') {
exeFilePath = __dirname + "/search-macos";
} else if (platform == 'Linux') {
exeFilePath = __dirname + "/search-linux";
if (platform === 'win') {
exeFilePath = __dirname + '/search-win.exe';
} else if (platform === 'mac') {
exeFilePath = __dirname + '/search-macos';
} else if (platform === 'Linux') {
exeFilePath = __dirname + '/search-linux';
}
}
function executorApiscan(name, genDir) {
if (genDir == "" || genDir == null) {
if (genDir === '' || genDir === null) {
genDir = name;
}
var command = exeFilePath + " -d " + name + " -o " + genDir;
var command = exeFilePath + ' -d ' + name + ' -o ' + genDir;
var exec = require('child_process').exec;
exec(command, function (error, stdout, stderr) {
VsPluginLog.logInfo('VsPlugin: stdout =' + stdout + ", stderr =" + stderr);
if (error || stdout.indexOf("errno") > 0) {
vscode.window.showErrorMessage("genError:" + (error != null ? error : "") + stdout);
return VsPluginLog.logError("VsPlugin:" + error + stdout);
VsPluginLog.logInfo('VsPlugin: stdout =' + stdout + ', stderr =' + stderr);
if (error || stdout.indexOf('errno') > 0) {
vscode.window.showErrorMessage('genError:' + (error !== null ? error : '') + stdout);
return VsPluginLog.logError('VsPlugin:' + error + stdout);
}
vscode.window.showInformationMessage("Api Scan Successfully");
vscode.window.showInformationMessage('Api Scan Successfully');
});
}
@ -75,6 +75,28 @@ function exeFileExit() {
return false;
}
function checkLoop(items, myExtensionId, boolValue) {
for (let i = 0; i < items.length; i++) {
if (myExtensionId === items[i] && (i === items.length - 1)) {
importToolChain = false;
} else if (myExtensionId === items[i] && (i !== items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
function checkBoolAndItems(boolValue, items) {
if (typeof(boolValue) === 'boolean' && Array.isArray(items)) {
if (boolValue === true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.ApiScan';
checkLoop(items, myExtensionId, boolValue);
}
}
}
function register(context, command) {
let disposable = vscode.commands.registerCommand(command, function (uri, boolValue, items) {
// The code you place here will be executed every time your command is executed
@ -89,40 +111,26 @@ function register(context, command) {
}
);
if (typeof(boolValue) == 'boolean' && Array.isArray(items)) {
if (boolValue == true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.ApiScan';
for (let i = 0; i < items.length; i++) {
if (myExtensionId == items[i] && (i == items.length - 1)) {
importToolChain = false;
} else if (myExtensionId == items[i] && (i != items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
}
checkBoolAndItems(boolValue, items);
globalPanel.webview.html = getWebviewContent(context, importToolChain);
let msg;
globalPanel.webview.onDidReceiveMessage(message => {
msg = message.msg;
if (msg == "cancel") {
if (msg === 'cancel') {
globalPanel.dispose();
}
else if (msg == "api_scan") {
else if (msg === 'api_scan') {
checkReceiveMsg(message);
} else {
selectPath(globalPanel, message);
}
}, undefined, context.subscriptions);
let fn = re.getFileInPath(uri.fsPath);
let tt = re.match("[a-zA-Z_0-9]", fn);
let tt = re.match('[a-zA-Z_0-9]', fn);
var result = {
msg: "selectASFilePath",
path: tt ? uri.fsPath : ""
msg: 'selectASFilePath',
path: tt ? uri.fsPath : ''
}
globalPanel.webview.postMessage(result);
});
@ -133,18 +141,18 @@ function checkReceiveMsg(message) {
let name = message.fileNames;
let genDir = message.genDir;
let buttonName = message.buttonName;
name = re.replaceAll(name, " ", "");
if ("" == name) {
vscode.window.showErrorMessage("Please enter the path!");
name = re.replaceAll(name, ' ', '');
if ('' === name) {
vscode.window.showErrorMessage('Please enter the path!');
return;
}
if (exeFileExit()) {
executorApiscan(name, genDir);
if (buttonName == 'Next') {
if (buttonName === 'Next') {
startNextPlugin();
}
} else {
vscode.window.showInformationMessage("Copy executable program to " + __dirname);
vscode.window.showInformationMessage('Copy executable program to ' + __dirname);
}
}
@ -152,15 +160,15 @@ function checkReceiveMsg(message) {
* 获取插件执行命令
*/
function nextPluginExeCommand(nextPluginId) {
if (nextPluginId == "kaihong.ApiScan") {
if (nextPluginId === 'kaihong.ApiScan') {
return 'api_scan';
} else if (nextPluginId == "kaihong.gn-gen") {
} else if (nextPluginId === 'kaihong.gn-gen') {
return 'generate_gn';
} else if (nextPluginId == "kaihong.service-gen") {
} else if (nextPluginId === 'kaihong.service-gen') {
return 'generate_service';
} else if (nextPluginId == "kaihong.ts-gen") {
} else if (nextPluginId === 'kaihong.ts-gen') {
return 'generate_ts';
} else if (nextPluginId == "kaihong.napi-gen") {
} else if (nextPluginId === 'kaihong.napi-gen') {
return 'generate_napi';
} else {
return null;
@ -195,9 +203,9 @@ function selectPath(panel, message) {
return vscode.window.showOpenDialog(options).then(fileUri => {
if (fileUri && fileUri[0]) {
console.log('Selected file: ' + fileUri[0].fsPath);
let filePath = "";
let filePath = '';
for (let index = 0; index < fileUri.length; index++) {
filePath += fileUri[index].fsPath.concat(",");
filePath += fileUri[index].fsPath.concat(',');
}
var result = {
msg: message.msg,
@ -227,7 +235,7 @@ function getWebViewContent(context, templatePath) {
const dirPath = path.dirname(resourcePath);
let html = fs.readFileSync(resourcePath, 'utf-8');
html = html.replace(/(<link.+?href="|<script.+?src="|<iframe.+?src="|<img.+?src=")(.+?)"/g, (m, $1, $2) => {
if ($2.indexOf("https://") < 0) {
if ($2.indexOf('https://') < 0) {
return $1 + globalPanel.webview.asWebviewUri(vscode.Uri.file(path.resolve(dirPath, $2))) + '"';
} else {
return $1 + $2 + '"';

View File

@ -54,24 +54,24 @@ function activate(context) {
let msg;
globalPanel.webview.onDidReceiveMessage(message => {
msg = message.msg;
if (msg == "cancel") {
if (msg === "cancel") {
globalPanel.dispose();
} else if (msg == "startApi") {
} else if (msg === "startApi") {
const extensionId = 'kaihong.ApiScan';
installStartExtension(extensionId);
} else if (msg == "startGn") {
} else if (msg === "startGn") {
const extensionId = 'kaihong.gn-gen';
installStartExtension(extensionId);
} else if (msg == "startService") {
} else if (msg === "startService") {
const extensionId = 'kaihong.service-gen';
installStartExtension(extensionId);
} else if (msg == "startTs") {
} else if (msg === "startTs") {
const extensionId = 'kaihong.ts-gen';
installStartExtension(extensionId);
} else if (msg == "startNapi") {
} else if (msg === "startNapi") {
const extensionId = 'kaihong.napi-gen';
installStartExtension(extensionId);
} else if (msg == "param") {
} else if (msg === "param") {
let isSelectToolChain = installExtensions(message);
startExtensions(isSelectToolChain);
}
@ -91,22 +91,22 @@ function installExtensions(message) {
let checkTs = message.checkTs;
let checkNapi = message.checkNapi;
if (importCheck) {
if (extensionIds.length != 0) {
if (extensionIds.length !== 0) {
extensionIds.length = 0;
}
if (checkApi == 'true') {
if (checkApi === 'true') {
extensionIds.push('kaihong.ApiScan')
}
if (checkGn == 'true') {
if (checkGn === 'true') {
extensionIds.push('kaihong.gn-gen')
}
if (checkService == 'true') {
if (checkService === 'true') {
extensionIds.push('kaihong.service-gen')
}
if (checkTs == 'true') {
if (checkTs === 'true') {
extensionIds.push('kaihong.ts-gen')
}
if (checkNapi == 'true') {
if (checkNapi === 'true') {
extensionIds.push('kaihong.napi-gen')
}
}
@ -134,15 +134,15 @@ async function startInstallExtensions(extensionIds) {
* 执行完毕后启动工具链中下一个插件
*/
function nextPluginExeCommand(nextPluginId) {
if (nextPluginId == "kaihong.ApiScan") {
if (nextPluginId === "kaihong.ApiScan") {
return 'api_scan';
} else if (nextPluginId == "kaihong.gn-gen") {
} else if (nextPluginId === 'kaihong.gn-gen') {
return 'generate_gn';
} else if (nextPluginId == "kaihong.service-gen") {
} else if (nextPluginId === 'kaihong.service-gen') {
return 'generate_service';
} else if (nextPluginId == "kaihong.ts-gen") {
} else if (nextPluginId === 'kaihong.ts-gen') {
return 'generate_ts';
} else if (nextPluginId == "kaihong.napi-gen") {
} else if (nextPluginId === 'kaihong.napi-gen') {
return 'generate_napi';
} else {
return null;
@ -168,16 +168,14 @@ function wait(ms) {
return new Promise(resolve => setTimeout(() => resolve(), ms));
};
async function installStartExtension(extensionId) {
const extension = vscode.extensions.getExtension(extensionId);
if (!extension) {
try {
async function checkInstallStartExtension(extensionId) {
try {
// 下载插件
vscode.window.showInformationMessage(`Extension ${extensionId} installing...`);
setTimeout(() => {
const active = vscode.window.activeInformationMessage;
if (active && active.message === `Extension ${extensionId} installing...`) {
active.dispose();
active.dispose();
}
}, 8000);
await vscode.commands.executeCommand('workbench.extensions.installExtension', extensionId);
@ -190,24 +188,30 @@ async function installStartExtension(extensionId) {
vscode.window.showInformationMessage(`Extension ${extensionId} activated successfully.`);
console.log(`Extension ${extensionId} activated successfully.`);
} else {
console.log('请等待插件初始化完成')
console.log('请等待插件初始化完成');
await wait(1000);
}
} catch (error) {
} catch (error) {
console.log(`Failed to install extension ${extensionId}: ${error.message}`);
}
}
}
async function installStartExtension(extensionId) {
const extension = vscode.extensions.getExtension(extensionId);
if (!extension) {
checkInstallStartExtension(extensionId);
}
// 启动扩展
if (extensionId == "kaihong.ApiScan") {
if (extensionId === 'kaihong.ApiScan') {
vscode.commands.executeCommand('api_scan', '', false, '');
} else if (extensionId == "kaihong.gn-gen") {
} else if (extensionId === 'kaihong.gn-gen') {
vscode.commands.executeCommand('generate_gn', '', false, '');
} else if (extensionId == "kaihong.service-gen") {
} else if (extensionId === 'kaihong.service-gen') {
vscode.commands.executeCommand('generate_service', '', false, '');
} else if (extensionId == "kaihong.ts-gen") {
} else if (extensionId === 'kaihong.ts-gen') {
vscode.commands.executeCommand('generate_ts', '', false, '');
} else if (extensionId == "kaihong.napi-gen") {
} else if (extensionId === 'kaihong.napi-gen') {
vscode.commands.executeCommand('generate_napi', '', false, '');
}
else {
@ -241,4 +245,4 @@ function deactivate() {}
module.exports = {
activate,
deactivate
}
};

View File

@ -23,9 +23,9 @@ class AnalyzeCommand {
}
static isCmd(cmd, name) {
let cmdName = cmd.split(" ")[0];
let cmdName = cmd.split(' ')[0];
let v1 = cmdName.endsWith(name);
let v2 = cmdName.endsWith(name + ".exe");
let v2 = cmdName.endsWith(name + '.exe');
return v1 || v2;
}
@ -37,13 +37,13 @@ class AnalyzeCommand {
static COLLECT_COMMANDS = [];
static storeCommands() {
fs.writeFileSync(path.join(Tool.CURRENT_TOOL_PATH, "cmds.txt"),
AnalyzeCommand.COLLECT_COMMANDS.join("\n"), { encoding: "utf8" });
fs.writeFileSync(path.join(Tool.CURRENT_TOOL_PATH, 'cmds.txt'),
AnalyzeCommand.COLLECT_COMMANDS.join('\n'), { encoding: 'utf8' });
}
static getCompileCmdId(cmd) {
let cmdName = cmd.split(" ")[0];
let cmdName = cmd.split(' ')[0];
for (let c in AnalyzeCommand.COMPILE_CMDS) {
if (cmdName.endsWith(c) || cmdName.endsWith(c + ".exe")) {
if (cmdName.endsWith(c) || cmdName.endsWith(c + '.exe')) {
return AnalyzeCommand.COMPILE_CMDS[c];//返回命令ID
}
}
@ -51,8 +51,8 @@ class AnalyzeCommand {
}
static analyze(cmd) {
let cmds;
if (cmd.indexOf("&&") >= 0) {
cmds = cmd.split("&&");
if (cmd.indexOf('&&') >= 0) {
cmds = cmd.split('&&');
}
else {
cmds = [cmd];
@ -69,19 +69,19 @@ class AnalyzeCommand {
return result;
}
static exAnalyzeCmake(cmd) {
let ss = cmd.split(" ");
if (ss.indexOf("-P") > 0) {//需要 cmake执行脚本在这里直接执行 or 移到BUILD.gn里面执行
const childProcess = require("child_process");
let ss = cmd.split(' ');
if (ss.indexOf('-P') > 0) {//需要 cmake执行脚本在这里直接执行 or 移到BUILD.gn里面执行
const childProcess = require('child_process');
childProcess.execSync(cmd);
AnalyzeCommand.COLLECT_COMMANDS.push(cmd);
return false;
}
let cmakeLinkScriptOffset = ss.indexOf("cmake_link_script");
let cmakeLinkScriptOffset = ss.indexOf('cmake_link_script');
if (cmakeLinkScriptOffset >= 0) {//需要 这里可能要做一些错误判断
let cmakeLinkScriptFile = ss[cmakeLinkScriptOffset + 1];
let cmakeLinkScriptData = fs.readFileSync(path.join(process.cwd(), cmakeLinkScriptFile),
{ encoding: "utf8" });
let cmds = cmakeLinkScriptData.split("\n");//link.txt中可能有多条命令链接
{ encoding: 'utf8' });
let cmds = cmakeLinkScriptData.split('\n');//link.txt中可能有多条命令链接
let rets = []
for (let c of cmds) {
let r = AnalyzeCommand.analyzeOneCmd(c);
@ -99,53 +99,53 @@ class AnalyzeCommand {
return false;
}
static isCmdScriptWithVersion(cmd, cmdType) {
let cmdName = cmd.split(" ")[0];
let pos = cmdName.lastIndexOf("/");
let cmdName = cmd.split(' ')[0];
let pos = cmdName.lastIndexOf('/');
let scrType = cmdName.substring(pos + 1, cmdName.length);
return scrType.startsWith(cmdType)
}
static analyzeOneCmd(cmd) {
while (cmd.startsWith("\n") || cmd.startsWith(" ")) {
while (cmd.startsWith('\n') || cmd.startsWith(' ')) {
cmd = cmd.substring(1);
}
if (cmd.length <= 0) {
return false;
}
if (cmd.match("^make(\\[\\d+\\]:)|: (Entering)|(Leaving) directory")) {//跳过进出目录的log
if (cmd.match('^make(\\[\\d+\\]:)|: (Entering)|(Leaving) directory')) {//跳过进出目录的log
//需要 改变工作目录
return false;
}
if (cmd.startsWith("cd ")) {
if (cmd.startsWith('cd ')) {
let t = AnalyzeCommand.splitString(cmd);
Tool.pushd(t[1]);//改变工作目录
return false;
}
if (AnalyzeCommand.isCmd(cmd, "ccache")) {//去掉ccache头
cmd = cmd.substring(cmd.indexOf("ccache") + "ccache".length);
if (AnalyzeCommand.isCmd(cmd, 'ccache')) {//去掉ccache头
cmd = cmd.substring(cmd.indexOf('ccache') + 'ccache'.length);
return AnalyzeCommand.analyzeOneCmd(cmd);
}
if (AnalyzeCommand.isCmd(cmd, "cmake")) {//跳过cmake的log需要解析link命令行
if (AnalyzeCommand.isCmd(cmd, 'cmake')) {//跳过cmake的log需要解析link命令行
return AnalyzeCommand.exAnalyzeCmake(cmd);
}
if (AnalyzeCommand.isCmd(cmd, "make") ||
AnalyzeCommand.isCmd(cmd, "ranlib")) {//跳过这些命令
if (AnalyzeCommand.isCmd(cmd, 'make') ||
AnalyzeCommand.isCmd(cmd, 'ranlib')) {//跳过这些命令
return false;
}
if (AnalyzeCommand.getCompileCmdId(cmd) >= 0) {//解析编译命令行
AnalyzeCommand.COLLECT_COMMANDS.push(cmd);
return [AnalyzeCommand.analyzeCompileCommand(cmd)];
}
if (AnalyzeCommand.isCmd(cmd, "perl") ||
AnalyzeCommand.isCmd(cmd, "autoreconf") ||
AnalyzeCommand.isCmdScriptWithVersion(cmd, "python")) {
if (AnalyzeCommand.isCmd(cmd, 'perl') ||
AnalyzeCommand.isCmd(cmd, 'autoreconf') ||
AnalyzeCommand.isCmdScriptWithVersion(cmd, 'python')) {
// 需要即时执行(可能会生成依赖源文件),如果不执行,后续编译命令可能会报错,找不到源文件
Logger.info(cmd);
const childProcess = require("child_process");
const childProcess = require('child_process');
childProcess.execSync(cmd);
return false;
}
Logger.err("未解析的命令行:" + cmd);
Logger.err('未解析的命令行:' + cmd);
return false;
}
@ -153,26 +153,26 @@ class AnalyzeCommand {
return {
type: 0,//0 compile command,1 other command
workDir: process.cwd(),
command: "",
command: '',
inputs: [],
target: "",
target: '',
isLink: false,//是否编译,.a/.o/可执行程序,需要生成目标
includes: [],
defines: [
"_XOPEN_SOURCE=600",//ohos的编译环境缺失宏
"FE_TONEAREST=0x00000000",
"FE_UPWARD=0x00400000",
"FE_DOWNWARD=0x00800000",
"FE_TOWARDZERO=0x00c00000",
'_XOPEN_SOURCE=600',//ohos的编译环境缺失宏
'FE_TONEAREST=0x00000000',
'FE_UPWARD=0x00400000',
'FE_DOWNWARD=0x00800000',
'FE_TOWARDZERO=0x00c00000',
],
cflags: [
"-Wno-implicit-function-declaration",
"-Wno-unused-function",
"-Wno-comments",//允许注释后面有个\
"-Wno-string-conversion",//允许char*当做bool使用
"-Wno-header-hygiene",//不检测命名空间污染
"-frtti",//支持typeid(xxx)
"-fexceptions",//支持try catch
'-Wno-implicit-function-declaration',
'-Wno-unused-function',
'-Wno-comments',//允许注释后面有个\
'-Wno-string-conversion',//允许char*当做bool使用
'-Wno-header-hygiene',//不检测命名空间污染
'-frtti',//支持typeid(xxx)
'-fexceptions',//支持try catch
],//c和c++选项
cflagsCc: [],//c++选项
cflagsC: [],//c选项
@ -184,7 +184,7 @@ class AnalyzeCommand {
let startp = -1;
let isContinuChar = 0;
for (let p = 0; p < s.length; p++) {
if (s[p] == "\"" && s[p-1] != "\\") {
if (s[p] == '\"' && s[p-1] != '\\') {
isContinuChar = 1 - isContinuChar;
}
if (startp >= 0) {
@ -205,45 +205,45 @@ class AnalyzeCommand {
static mockTarget(t) {
if (t.target) {
fs.writeFileSync(t.target, " ");
fs.writeFileSync(t.target, ' ');
}
}
static clangCheck1(e) {
let ss = ["--sysroot=",
"-pthread",
"-Qunused-arguments",
"-ffunction-sections",
"-fdata-sections",
"-fvisibility=hidden",
"-fvisibility-inlines-hidden",
"-O3",
"-Os",
"-fPIC",
"-pedantic",
"-fwrapv",
"-shared",
"-lm",
"-lpthread",
"-lz",
"-MD",
"-isystem"
let ss = ['--sysroot=',
'-pthread',
'-Qunused-arguments',
'-ffunction-sections',
'-fdata-sections',
'-fvisibility=hidden',
'-fvisibility-inlines-hidden',
'-O3',
'-Os',
'-fPIC',
'-pedantic',
'-fwrapv',
'-shared',
'-lm',
'-lpthread',
'-lz',
'-MD',
'-isystem'
];
for (let s of ss) {
if (e.startsWith(s) || e == "-w") {
if (e.startsWith(s) || e == '-w') {
return true;
}
}
return false;
}
static clangCheck2(local, e) {
if (e.startsWith("-MT") || e.startsWith("-MF")) {
if (e.startsWith('-MT') || e.startsWith('-MF')) {
if (e.length == 3) {
local.p++;
}
return true;
}
if (e.startsWith("-s")) {
if (e.startsWith('-s')) {
if (e.length == 2) {
local.p++;
}
@ -252,7 +252,7 @@ class AnalyzeCommand {
return false;
}
static clangCheck3(local, e) {
if (e.startsWith("-D")) {//需要记录到defines里面的参数
if (e.startsWith('-D')) {//需要记录到defines里面的参数
//需要 是否-D开头的全部记录到defines里面
if (e.length == 2) {//-D xxx
local.ret.defines.push(local.eles[local.p++]);
@ -265,7 +265,7 @@ class AnalyzeCommand {
return false;
}
static clangCheck4(local, e) {
if (e.startsWith("-I")) {//需要记录到includes的参数
if (e.startsWith('-I')) {//需要记录到includes的参数
if (e.length == 2) {//-I xxx
local.ret.includes.push(local.eles[local.p++]);
}
@ -285,23 +285,23 @@ class AnalyzeCommand {
return false;
}
static clangCheck5(local, e) {
if (this.validCFlag(e, Tool.getAllowedC().compileflag) || (e == "-D__clang__")) {
if (this.validCFlag(e, Tool.getAllowedC().compileflag) || (e == '-D__clang__')) {
local.ret.cflags.push(e); //需要记录到flags里面的参数
return true;
}
return false;
}
static clangCheck6(local, e) {
if (e == "-o") {
if (e == '-o') {
if (e.length == 2) {//-o xxx
local.ret.target = local.eles[local.p++];
}
else {//-oxxx
local.ret.target = e.substring(2);
}
if (local.ret.target.endsWith(".a") ||
local.ret.target.endsWith(".so") ||
(!e.endsWith(".c") && !e.endsWith(".o"))) {
if (local.ret.target.endsWith('.a') ||
local.ret.target.endsWith('.so') ||
(!e.endsWith('.c') && !e.endsWith('.o'))) {
local.ret.isLink = true;
}
return true;
@ -309,26 +309,30 @@ class AnalyzeCommand {
return false;
}
static checkDataLocal(local, data) {
let datas = data.split(' ');
for (let d of datas) {
for (let s of ss) {
if (d.endsWith(s)) {
local.ret.inputs.push(d);
}
}
}
}
static clangCheck7(local, e) {
if (this.validSuffix(e, Tool.getAllowedC().fileSuffix)) {
local.ret.inputs.push(e);
return true;
}
if (e.endsWith(".rsp")) {
if (e.endsWith('.rsp')) {
console.log(Tool.CURRENT_DIR);
let rspth = path.join(Tool.CURRENT_DIR, e.substring(1));
let data = fs.readFileSync(rspth, { encoding: "utf8" });
if (data.endsWith("\r\n")) {
let data = fs.readFileSync(rspth, { encoding: 'utf8' });
if (data.endsWith('\r\n')) {
data = data.substring(0, data.length - 2);
}
let datas = data.split(" ");
for (let d of datas) {
for (let s of ss) {
if (d.endsWith(s)) {
local.ret.inputs.push(d);
}
}
}
AnalyzeCommand.checkDataLocal(local, data);
return true;
}
return false;
@ -343,40 +347,40 @@ class AnalyzeCommand {
while (local.p < local.eles.length) {
let e = local.eles[local.p++];
if (e.endsWith("clang") || e.endsWith("clang.exe")) {
if (e.endsWith('clang') || e.endsWith('clang.exe')) {
local.ret.command = e;
}
else if (AnalyzeCommand.clangCheck1(e)) { }
else if (AnalyzeCommand.clangCheck2(local, e)) { }
else if (e.startsWith("-Wl,--dynamic-linker,") || e.startsWith("-rdynamic")) {//-----直接忽略的链接参数
else if (e.startsWith('-Wl,--dynamic-linker,') || e.startsWith('-rdynamic')) {//-----直接忽略的链接参数
local.ret.isLink = true;
}
else if (AnalyzeCommand.clangCheck3(local, e)) { }
else if (AnalyzeCommand.clangCheck4(local, e)) { }
else if (AnalyzeCommand.clangCheck5(local, e)) { }
else if (e.startsWith("-std=")) {
else if (e.startsWith('-std=')) {
local.ret.cflagsCc.push(e);
}
else if (e.startsWith("-W")) {//需要 -W开头的怎么处理,-W -Wall -Werror=return-type -Wno-unnamed-type-template-args
if (e.startsWith("-Wno-")) {
else if (e.startsWith('-W')) {//需要 -W开头的怎么处理,-W -Wall -Werror=return-type -Wno-unnamed-type-template-args
if (e.startsWith('-Wno-')) {
local.ret.cflags.push(e);
}
}
else if (AnalyzeCommand.clangCheck6(local, e)) { }
else if (e == "-c") {//编译
else if (e == '-c') {//编译
local.ret.isLink = false;
}
else if (AnalyzeCommand.clangCheck7(local, e)) { }
else {
Logger.err(cmd + "\nclang未解析参数 " + e);
Logger.err(cmd + '\nclang未解析参数 ' + e);
process.exit();
}
}
Logger.info("----clang-----" + local.ret.workDir + "\n\t" + local.ret.isLink + "," + local.ret.target)
Logger.info('----clang-----' + local.ret.workDir + '\n\t' + local.ret.isLink + ',' + local.ret.target);
return local.ret;
}
static analyzeCcAr(cmd) {
if (cmd.endsWith("\r")) {
if (cmd.endsWith('\r')) {
cmd = cmd.substring(0, cmd.length - 1);
}
let ret = AnalyzeCommand.resultTemplete();
@ -385,61 +389,61 @@ class AnalyzeCommand {
let p = 0;
while (p < eles.length) {
let e = eles[p++];
if (e.endsWith("ar") || e.endsWith("ar.exe")) {
if (e.endsWith('ar') || e.endsWith('ar.exe')) {
ret.command = e;
}
else if (e.endsWith(".a")) {
else if (e.endsWith('.a')) {
ret.target = e;
}
else if (e.endsWith(".o")) {
else if (e.endsWith('.o')) {
ret.inputs.push(e);
}
else if (e == "qc") {
else if (e == 'qc') {
}
else {
Logger.err(cmd + "\nar未解析参数 " + e);
Logger.err(cmd + '\nar未解析参数 ' + e);
process.exit();
}
}
Logger.info("---ar----" + ret.workDir + "\n\t" + ret.isLink + "," + ret.target);
Logger.info('---ar----' + ret.workDir + '\n\t' + ret.isLink + ',' + ret.target);
return ret;
}
static clangxxCheck1(e) {
let ss = ["--sysroot=",
"-pthread",
"-Qunused-arguments",
"-ffunction-sections",
"-fdata-sections",
"-fvisibility=hidden",
"-fvisibility-inlines-hidden",
"-funwind-tables",
"-fwrapv",
"-O3",
"-fPIC",
"-shared",
"-ldl",
"-lm",
"-lpthread",
"-lrt",
"-fPIE",
"-g",
"-ftemplate-depth=1024",
"-pedantic-errors"
let ss = ['--sysroot=',
'-pthread',
'-Qunused-arguments',
'-ffunction-sections',
'-fdata-sections',
'-fvisibility=hidden',
'-fvisibility-inlines-hidden',
'-funwind-tables',
'-fwrapv',
'-O3',
'-fPIC',
'-shared',
'-ldl',
'-lm',
'-lpthread',
'-lrt',
'-fPIE',
'-g',
'-ftemplate-depth=1024',
'-pedantic-errors'
];
for (let s of ss) {
if (e.startsWith(s)) {
return true;
}
}
if (e == "-w") {//-----直接忽略的编译参数(和链接参数)
if (e == '-w') {//-----直接忽略的编译参数(和链接参数)
return true;
}
return false;
}
static clangxxCheck2(local, e) {
if (e.startsWith("-isystem")) {//需要 不清楚这个有什么用
if (e == "-isystem") {//-isystem xxxx
if (e.startsWith('-isystem')) {//需要 不清楚这个有什么用
if (e == '-isystem') {//-isystem xxxx
local.ret.includes.push(local.eles[local.p++]);
}
else {//-Ixxx
@ -450,7 +454,7 @@ class AnalyzeCommand {
return false;
}
static clangxxCheck3(local, e) {
if (e.startsWith("-D")) {//需要记录到defines里面的参数
if (e.startsWith('-D')) {//需要记录到defines里面的参数
//需要 是否-D开头的全部记录到defines里面
if (e.length == 2) {//-D xxx
local.ret.defines.push(local.eles[local.p++]);
@ -463,7 +467,7 @@ class AnalyzeCommand {
return false;
}
static clangxxCheck4(local, e) {
if (e.startsWith("-I")) {//需要记录到includes的参数
if (e.startsWith('-I')) {//需要记录到includes的参数
if (e.length == 2) {//-I xxx
local.ret.includes.push(local.eles[local.p++]);
}
@ -482,9 +486,9 @@ class AnalyzeCommand {
return false;
}
static clangxxCheck6(local, e) {
if (e.startsWith("-Xclang")) {//透传参数
if (e.startsWith('-Xclang')) {//透传参数
let v = local.eles[local.p++];
if (v != "-emit-pch") {//需要丢弃这个选项
if (v != '-emit-pch') {//需要丢弃这个选项
local.ret.cflags.push(e);
local.ret.cflags.push(v);
}
@ -493,8 +497,8 @@ class AnalyzeCommand {
return false;
}
static clangxxCheck7(local, e) {
if (e.startsWith("-W")) {//需要 -W开头的怎么处理,-W -Wall -Werror=return-type -Wno-unnamed-type-template-args
if (e.startsWith("-Wno-")) {
if (e.startsWith('-W')) {//需要 -W开头的怎么处理,-W -Wall -Werror=return-type -Wno-unnamed-type-template-args
if (e.startsWith('-Wno-')) {
local.ret.cflags.push(e);
}
return true;
@ -502,16 +506,16 @@ class AnalyzeCommand {
return false;
}
static clangxxCheck8(local, e) {
if (e == "-o") {
if (e == '-o') {
if (e.length == 2) {//-o xxx
local.ret.target = local.eles[local.p++];
}
else {//-oxxx
local.ret.target = e.substring(2);
}
if (local.ret.target.endsWith(".a") ||
local.ret.target.endsWith(".so") ||
(!e.endsWith(".c") && !e.endsWith(".o"))) {
if (local.ret.target.endsWith('.a') ||
local.ret.target.endsWith('.so') ||
(!e.endsWith('.c') && !e.endsWith('.o'))) {
local.ret.isLink = true;
}
return true;
@ -529,40 +533,43 @@ class AnalyzeCommand {
}
return false;
}
static checkDataPP(local, data) {
let datas = data.split(' ');
let pp = ['.c',
'.o',
'.o"',
'.a',
'.S',
'.so'
];
for (let d of datas) {
for (let p of pp) {
if (d.endsWith(p)) {
local.ret.inputs.push(d);
}
}
}
}
static clangxxCheck9(local, e) {
if (this.validSuffix(e, Tool.getAllowedCxx().fileSuffix) || (e.indexOf(".so.") > 0)) {
if (this.validSuffix(e, Tool.getAllowedCxx().fileSuffix) || (e.indexOf('.so.') > 0)) {
local.ret.inputs.push(e);
return true;
}
if (e.endsWith(".rsp")) {
if (e.endsWith('.rsp')) {
console.log(Tool.CURRENT_DIR);
let rspth = path.join(Tool.CURRENT_DIR, e.substring(1));
let data = fs.readFileSync(rspth, { encoding: "utf8" });
if (data.endsWith("\r\n")) {
let data = fs.readFileSync(rspth, { encoding: 'utf8' });
if (data.endsWith('\r\n')) {
data = data.substring(0, data.length - 2);
}
let datas = data.split(" ");
let pp = [".c",
".o",
'.o"',
".a",
".S",
".so"
];
for (let d of datas) {
for (let p of pp) {
if (d.endsWith(p)) {
local.ret.inputs.push(d);
}
}
}
AnalyzeCommand.checkDataPP(local, data);
return true;
}
return false;
}
static analyzeCcClangxx(cmd) {
if (cmd.indexOf("\"")) {
cmd = cmd.replace(/\"/g, "");
if (cmd.indexOf('\"')) {
cmd = cmd.replace(/\"/g, '');
}
let local = {
ret: AnalyzeCommand.resultTemplete(),
@ -571,59 +578,59 @@ class AnalyzeCommand {
}
while (local.p < local.eles.length) {
let e = local.eles[local.p++];
if (e.endsWith("clang++") || e.endsWith("clang++.exe")) {
if (e.endsWith('clang++') || e.endsWith('clang++.exe')) {
local.ret.command = e;
}
else if (AnalyzeCommand.clangxxCheck1(e)) { }
else if (e.startsWith("-fno-rtti")) {
local.ret.cflags.splice(local.ret.cflags.indexOf("-frtti"), 1);
else if (e.startsWith('-fno-rtti')) {
local.ret.cflags.splice(local.ret.cflags.indexOf('-frtti'), 1);
}
else if (e.startsWith("-fno-exceptions")) {
local.ret.cflags.splice(local.ret.cflags.indexOf("-fexceptions"), 1);
else if (e.startsWith('-fno-exceptions')) {
local.ret.cflags.splice(local.ret.cflags.indexOf('-fexceptions'), 1);
}
else if (AnalyzeCommand.clangxxCheck2(local, e)) { }
else if (AnalyzeCommand.clangxxCheck3(local, e)) { }
else if (AnalyzeCommand.clangxxCheck4(local, e)) { }
else if (AnalyzeCommand.clangxxCheck5(local, e)) { }
else if (AnalyzeCommand.clangxxCheck6(local, e)) { }
else if (e.startsWith("-std=")) {
else if (e.startsWith('-std=')) {
local.ret.cflagsCc.push(e);
}
else if (AnalyzeCommand.clangxxCheck7(local, e)) { }
else if (AnalyzeCommand.clangxxCheck8(local, e)) { }
else if (e == "-c") {//编译
else if (e == '-c') {//编译
local.ret.isLink = false;
}
else if (AnalyzeCommand.clangxxCheck9(local, e)) { }
else {
Logger.err(cmd + "\nclang++未解析参数 " + e);
Logger.err(cmd + '\nclang++未解析参数 ' + e);
process.exit();
}
}
Logger.info("---clang++----" + local.ret.workDir + "\n\t" + local.ret.isLink + "," + local.ret.target)
Logger.info('---clang++----' + local.ret.workDir + '\n\t' + local.ret.isLink + ',' + local.ret.target)
return local.ret;
}
static analyzeCompileCommand(cmd) {
//整理命令行
while (cmd.indexOf("\\\n") >= 0) {//去除\换行
cmd = cmd.replace("\\\n", "");
while (cmd.indexOf('\\\n') >= 0) {//去除\换行
cmd = cmd.replace('\\\n', '');
}
while (cmd.indexOf("\t") >= 0) {//所有tab换成空格
cmd = cmd.replace("\t", " ");
while (cmd.indexOf('\t') >= 0) {//所有tab换成空格
cmd = cmd.replace('\t', ' ');
}
while (cmd.endsWith("\n") || cmd.endsWith(" ")) {
while (cmd.endsWith('\n') || cmd.endsWith(' ')) {
cmd = cmd.substring(0, cmd.length - 1);
}
let ret = null;
switch (AnalyzeCommand.getCompileCmdId(cmd)) {
case AnalyzeCommand.COMPILE_CMDS["clang"]:
case AnalyzeCommand.COMPILE_CMDS['clang']:
ret = AnalyzeCommand.analyzeCcClang(cmd);
break;
case AnalyzeCommand.COMPILE_CMDS["ar"]:
case AnalyzeCommand.COMPILE_CMDS['ar']:
ret = AnalyzeCommand.analyzeCcAr(cmd);
break;
case AnalyzeCommand.COMPILE_CMDS["clang++"]:
case AnalyzeCommand.COMPILE_CMDS['clang++']:
ret = AnalyzeCommand.analyzeCcClangxx(cmd);
break;
}
@ -631,10 +638,10 @@ class AnalyzeCommand {
AnalyzeCommand.mockTarget(ret);//解析出的目标touch一个出来否则会出现不同Makefile中依赖无法找到的问题
return ret;
}
Logger.err("解析编译命令行失败:" + cmd);
Logger.err('解析编译命令行失败:' + cmd);
return false;
}
}
module.exports = {
AnalyzeCommand
}
};

View File

@ -63,32 +63,36 @@ class AnalyzeMake {
udpServer_.send("ok", 0, 2, rinfo.port, rinfo.address);//反馈ok给make继续执行
});
}
static checkBreakup(acmd) {
acmd += l;
if (acmd.length > 0) {
cmdlist.push(acmd);
let ret = AnalyzeCommand.analyze(acmd);
if (ret.length > 0) {
analyzeResult.push(...ret);
}
}
acmd = '';
}
static analyzeBreakup() {
let acmd = ""
let acmd = '';
for (let l of dlist) {
if (l.endsWith("\\")) { // 合并带有换行符的命令
acmd += l;
}
else {
acmd += l;
if (acmd.length > 0) {
cmdlist.push(acmd);
let ret = AnalyzeCommand.analyze(acmd);
if (ret.length > 0) {
analyzeResult.push(...ret);
}
}
acmd = "";
} else {
AnalyzeCommand.checkBreakup(acmd);
}
}
}
static analyze(makeProjectFile) {
let makeProjectPath = path.parse(makeProjectFile);
if (!fs.existsSync(makeProjectFile)) {
Logger.err("Makefile not exist in " + makeProjectPath.dir);
return;
}
if (AnalyzeMake.USE_UDP_COLLECTOR) {
} else if (AnalyzeMake.USE_UDP_COLLECTOR) {
AnalyzeMake.collectByUdp(makeProjectPath.dir);
return;
}
@ -96,7 +100,7 @@ class AnalyzeMake {
let ret = childProcess.spawn("make", ["-C", makeProjectPath.dir, "-n"]);
let cmdlist = [];
let analyzeResult = [];
let procData = "";
let procData = '';
ret.stdout.on('data', (data) => {
procData += data.toString();
let p = procData.lastIndexOf("\n");

View File

@ -23,56 +23,60 @@ function saveMockData(projectPath, analyzeResult) {
projectPath: projectPath,
analyzeResult: analyzeResult
}, null, 4);
fs.writeFileSync(path.join(Tool.CURRENT_TOOL_PATH, "mock.json"), ss)
Logger.err("save mock exit");
fs.writeFileSync(path.join(Tool.CURRENT_TOOL_PATH, 'mock.json'), ss)
Logger.err('save mock exit');
}
function checkPreProcessResult(r) {
for (let i = 0; i < r.inputs.length; i++) {
if (r.inputs[i].startsWith('"') && r.inputs[i].endsWith('"')) {
r.inputs[i] = r.inputs[i].substring(1, r.inputs[i].length - 1);
}
if (!r.inputs[i].startsWith('/')) {
if (!path.isAbsolute(r.inputs[i])) {
r.inputs[i] = path.join(r.workDir, r.inputs[i]);
}
}
}
for (let i = 0; i < r.includes.length; i++) {
if (!r.includes[i].startsWith('/')) {
if (!path.isAbsolute(r.includes[i])) {
r.includes[i] = path.join(r.workDir, r.includes[i]);
}
}
}
}
function preProcessResult(analyzeResult) {//把所有路径搞成绝对路径
for (let r of analyzeResult) {
if (!r.target.startsWith("/")) {
if (!r.target.startsWith('/')) {
if (!path.isAbsolute(r.target)) {
r.target = path.join(r.workDir, r.target);
}
}
for (let i = 0; i < r.inputs.length; i++) {
if (r.inputs[i].startsWith('"') && r.inputs[i].endsWith('"')) {
r.inputs[i] = r.inputs[i].substring(1, r.inputs[i].length - 1);
}
if (!r.inputs[i].startsWith("/")) {
if (!path.isAbsolute(r.inputs[i])) {
r.inputs[i] = path.join(r.workDir, r.inputs[i]);
}
}
}
for (let i = 0; i < r.includes.length; i++) {
if (!r.includes[i].startsWith("/")) {
if (!path.isAbsolute(r.includes[i])) {
r.includes[i] = path.join(r.workDir, r.includes[i]);
}
}
}
checkPreProcessResult(r);
}
}
function checkoutLibName(name) {//比如/home/libabc.so返回["dynamic",abc]
function checkoutLibName(name) {//比如/home/libabc.so返回['dynamic',abc]
let pn = path.parse(name);
let tname = pn.base;
if (tname.endsWith(".a")) {
if (tname.endsWith('.a')) {
tname = tname.substring(0, tname.length - 2);
if (tname.startsWith("lib")) {
if (tname.startsWith('lib')) {
tname = tname.substring(3);
}
return ["static", tname];
return ['static', tname];
}
else if (tname.endsWith(".so") || tname.indexOf(".so.") > 0) {
tname = tname.substring(0, tname.indexOf(".so"));
if (tname.startsWith("lib")) {
else if (tname.endsWith('.so') || tname.indexOf('.so.') > 0) {
tname = tname.substring(0, tname.indexOf('.so'));
if (tname.startsWith('lib')) {
tname = tname.substring(3);
}
return ["dynamic", tname];
return ['dynamic', tname];
}
else {
return ["executable", tname];
return ['executable', tname];
}
}
@ -81,14 +85,14 @@ class GenerateGn {
}
static mockGenerate() {
let ss = fs.readFileSync(path.join(Tool.CURRENT_TOOL_PATH, "mock.json"), { encoding: "utf8" });
let ss = fs.readFileSync(path.join(Tool.CURRENT_TOOL_PATH, 'mock.json'), { encoding: 'utf8' });
let ret = JSON.parse(ss);
GenerateGn.generate(ret.projectPath, ret.analyzeResult);
Logger.err("generate mock exit")
Logger.err('generate mock exit');
}
static generate(projectPath, analyzeResult) {
if (Tool.MOCK_TYPE == Tool.MOCK_ENUM.MOCK_RECORD) {
if (Tool.MOCK_TYPE === Tool.MOCK_ENUM.MOCK_RECORD) {
saveMockData(projectPath, analyzeResult);//保存mock数据
}
@ -107,12 +111,12 @@ class GenerateGn {
}
let num = 0;
for (let gnPath in genList) {//genList的key即为需要生成gn的目录
Logger.info("%d-------------------generate dir %s".format(num, gnPath));
Logger.info('%d-------------------generate dir %s'.format(num, gnPath));
GenerateGn.generateGn(gnPath, genList, projectPath);
num++;
}
GenerateGn.generateTargetGroup(projectPath);
Logger.info("-------------------generate gn ok");
Logger.info('-------------------generate gn ok');
}
static COLLECT_TARGET = {
static: [],
@ -120,23 +124,23 @@ class GenerateGn {
executable: []
}
static generateTargetGroup(projectPath) {
let gnName = path.join(projectPath, "BUILD.gn");
let gnName = path.join(projectPath, 'BUILD.gn');
let gnStr = 'import("//build/ohos.gni")\n\n';
if (fs.existsSync(gnName)) {
gnStr = fs.readFileSync(gnName, { encoding: "utf8" });
gnStr = fs.readFileSync(gnName, { encoding: 'utf8' });
}
let staticTargets = [];
for (let t of GenerateGn.COLLECT_TARGET.static) {
staticTargets.push(Tool.swapPath(t.path) + ":" + t.name);
staticTargets.push(Tool.swapPath(t.path) + ':' + t.name);
}
let dynamicTargets = [];
for (let t of GenerateGn.COLLECT_TARGET.dynamic) {
dynamicTargets.push(Tool.swapPath(t.path) + ":" + t.name);
dynamicTargets.push(Tool.swapPath(t.path) + ':' + t.name);
}
let executableTargets = [];
for (let t of GenerateGn.COLLECT_TARGET.executable) {
executableTargets.push(Tool.swapPath(t.path) + ":" + t.name);
executableTargets.push(Tool.swapPath(t.path) + ':' + t.name);
}
gnStr += `
@ -165,17 +169,17 @@ group("all_targets") {
}
`
while (gnStr.indexOf(Tool.OHOS_PROJECT_PATH) >= 0) {
gnStr = gnStr.replace(Tool.OHOS_PROJECT_PATH, "/");
gnStr = gnStr.replace(Tool.OHOS_PROJECT_PATH, '/');
}
fs.writeFileSync(gnName, gnStr, { encoding: "utf8" });
fs.writeFileSync(gnName, gnStr, { encoding: 'utf8' });
}
static genTargetStr(targetName) {
switch (targetName[0]) {
case "static":
case 'static':
return 'ohos_static_library("' + targetName[1] + '")';
case "dynamic":
case 'dynamic':
return 'ohos_shared_library("' + targetName[1] + '")';
case "executable":
case 'executable':
return 'ohos_executable("' + targetName[1] + '")';
}
}
@ -195,19 +199,19 @@ group("all_targets") {
}
static genTargetStr2(collectDetails, targetStr, targetName) {
if (collectDetails.cflags.size > 0 || collectDetails.cflagsCc.size > 0) {//放到config里面才生效
let configDetail = "";
let removeConfigs = "";
let configDetail = '';
let removeConfigs = '';
if (collectDetails.cflags.size > 0) {
configDetail += GenerateGn.genDetail("cflags", collectDetails.cflags);
configDetail += GenerateGn.genDetail('cflags', collectDetails.cflags);
}
if (collectDetails.cflagsCc.size > 0) {
configDetail += GenerateGn.genDetail("cflags_cc", collectDetails.cflagsCc);
configDetail += GenerateGn.genDetail('cflags_cc', collectDetails.cflagsCc);
}
if (collectDetails.cflags.has("-frtti")) {
removeConfigs += ` "//build/config/compiler:no_rtti",\n`
if (collectDetails.cflags.has('-frtti')) {
removeConfigs += ` "//build/config/compiler:no_rtti",\n`;
}
if (collectDetails.cflags.has("-fexceptions")) {
removeConfigs += ` "//build/config/compiler:no_exceptions",\n`
if (collectDetails.cflags.has('-fexceptions')) {
removeConfigs += ` "//build/config/compiler:no_exceptions",\n`;
}
targetStr = `config("%s_config") {%s}
@ -218,16 +222,16 @@ configs = [ ":%s_config" ]
`.format(targetName[1], configDetail, targetStr, removeConfigs, targetName[1]);
}
if (collectDetails.sources.size > 0) {
targetStr += GenerateGn.genDetail("sources", collectDetails.sources);
targetStr += GenerateGn.genDetail('sources', collectDetails.sources);
}
if (collectDetails.includeDirs.size > 0) {
targetStr += GenerateGn.genDetail("include_dirs", collectDetails.includeDirs);
targetStr += GenerateGn.genDetail('include_dirs', collectDetails.includeDirs);
}
if (collectDetails.defines.size > 0) {
targetStr += GenerateGn.genDetail("defines", collectDetails.defines);
targetStr += GenerateGn.genDetail('defines', collectDetails.defines);
}
if (collectDetails.deps.size > 0) {
targetStr += GenerateGn.genDetail("deps", collectDetails.deps);
targetStr += GenerateGn.genDetail('deps', collectDetails.deps);
}
targetStr += `
@ -263,17 +267,17 @@ subsystem_name = "%s"
}
if (targetCount > 0) {
let gnName = path.join(gnPath, "BUILD.gn");
Logger.info("输出:" + gnName + "\n" + gnStr);
fs.writeFileSync(gnName, gnStr, { encoding: "utf8" });
let gnName = path.join(gnPath, 'BUILD.gn');
Logger.info('输出:' + gnName + '\n' + gnStr);
fs.writeFileSync(gnName, gnStr, { encoding: 'utf8' });
}
else {
Logger.info(" no target");
Logger.info(' no target');
}
}
static genDetail(name, detail) {
let ss = ""
let ss = ''
for (let s of detail) {
s=Tool.swapPath(s);
if (ss.length > 0) ss += '",\n "';
@ -286,7 +290,7 @@ subsystem_name = "%s"
`.format(name, ss)
while (ret.indexOf(Tool.OHOS_PROJECT_PATH) >= 0) {
ret = ret.replace(Tool.OHOS_PROJECT_PATH, "/");
ret = ret.replace(Tool.OHOS_PROJECT_PATH, '/');
}
return ret;
}
@ -295,9 +299,9 @@ subsystem_name = "%s"
for (let gnPath in genList) {
let gens = genList[gnPath]
for (let gen of gens) {
if (gen.target == name) {
if (gen.target === name) {
let tt = checkoutLibName(gen.target);
return gen.workDir + ":" + tt[1];
return gen.workDir + ':' + tt[1];
}
}
}
@ -310,23 +314,23 @@ subsystem_name = "%s"
let badd = true;
switch (collectFileStat) {
case 0:
if (a == "-Xclang") {
if (a === '-Xclang') {
collectFileStat = 1;
badd = false;
}
break;
case 1:
if (a == "-include" || a == "-include-pch") {
if (a === '-include' || a === '-include-pch') {
collectFileStat = 2;
badd = false;
}
else {
collectDetails.cflags.add("-Xclang");
collectDetails.cflags.add('-Xclang');
collectFileStat = 0;
}
break;
case 2:
if (a == "-Xclang") {
if (a === '-Xclang') {
collectFileStat = 3;
badd = false;
}
@ -381,7 +385,7 @@ subsystem_name = "%s"
collectDetails.sources.add(name);
}
for (let gnPath in genList) {
let gens = genList[gnPath]
let gens = genList[gnPath];
for (let gen of gens) {
if (name.endsWith(gen.target)) {
GenerateGn.collectGen(gen, genList, collectDetails);
@ -393,4 +397,4 @@ subsystem_name = "%s"
module.exports = {
GenerateGn
}
};

View File

@ -162,9 +162,13 @@ public class FileUtil {
if (!isNewFile) {
LOG.info("writeTmpFile createNewFile error");
}
FileOutputStream fw = new FileOutputStream(file);
fw.write(bs, 0, bs.length);
fw.close();
try (FileOutputStream fw = new FileOutputStream(file)) {
fw.write(bs, 0, bs.length);
} catch (IOException e) {
Gen.notifyMessage(project, e.getMessage(), "Can not Find File:" + oldPath,
NotificationType.ERROR);
}
} catch (IOException e) {
GenNotification.notifyMessage(project, e.getMessage(), "Can not Find File:" + oldPath,
NotificationType.ERROR);

View File

@ -45,11 +45,11 @@ function activate(context) {
context.subscriptions.push(disposable);
context.subscriptions.push(disposableMenu);
var platform = detectPlatform();
if (platform == 'win') {
if (platform === 'win') {
exeFilePath = __dirname + "/gn-gen-win.exe";
} else if (platform == 'mac') {
} else if (platform === 'mac') {
exeFilePath = __dirname + "/gn-gen-macos";
} else if (platform == 'Linux') {
} else if (platform === 'Linux') {
exeFilePath = __dirname + "/gn-gen-linux";
}
vscode.window.onDidChangeActiveColorTheme(colorTheme => {
@ -72,7 +72,7 @@ function gnexecutor(outputCodeDir, originCodeDir, inputScriptDir, scriptType, tr
VsPluginLog.logInfo('VsPlugin: stdout =' + stdout + ", stderr =" + stderr);
if (error || stdout.indexOf("generate gn ok") < 0) {
console.log(error)
vscode.window.showErrorMessage("genError:" + (error != null ? error : "") + stdout);
vscode.window.showErrorMessage("genError:" + (error !== null ? error : "") + stdout);
return VsPluginLog.logError("VsPlugin:" + error + stdout);
}
vscode.window.showInformationMessage("Generated successfully");
@ -83,7 +83,7 @@ function genGnCommand(outputCodeDir, originCodeDir, inputScriptDir, scriptType,
transplantDir, subsystemName, componentName, compileOptions) {
var command = exeFilePath + " -o " + outputCodeDir + " -p " + originCodeDir + " -f " + inputScriptDir
+ " -t " + scriptType + " -s " + subsystemName + " -m " + componentName + " -d " + transplantDir;
if (compileOptions != "") {
if (compileOptions !== "") {
command += " -a " + "\"" + compileOptions + "\"";
}
@ -115,6 +115,28 @@ function exeFileExit() {
return false;
}
function checkLoop(items, myExtensionId, boolValue) {
for (let i = 0; i < items.length; i++) {
if (myExtensionId === items[i] && (i === items.length - 1)) {
importToolChain = false;
} else if (myExtensionId === items[i] && (i !== items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
function checkBoolAndItems(boolValue, items) {
if (typeof(boolValue) === 'boolean' && Array.isArray(items)) {
if (boolValue === true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.gn-gen';
checkLoop(items, myExtensionId, boolValue);
}
}
}
function register(context, command) {
let disposable = vscode.commands.registerCommand(command, function (uri, boolValue, items) {
// The code you place here will be executed every time your command is executed
@ -128,28 +150,15 @@ function register(context, command) {
retainContextWhenHidden: true, // Keep the WebView state when it is hidden to avoid being reset
}
);
if (typeof(boolValue) == 'boolean' && Array.isArray(items)) {
if (boolValue == true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.gn-gen';
for (let i = 0; i < items.length; i++) {
if (myExtensionId == items[i] && (i == items.length - 1)) {
importToolChain = false;
} else if (myExtensionId == items[i] && (i != items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
}
checkBoolAndItems(boolValue, items);
globalPanel.webview.html = getWebviewContent(context, importToolChain);
let msg;
globalPanel.webview.onDidReceiveMessage(message => {
msg = message.msg;
if (msg == "cancel") {
if (msg === "cancel") {
globalPanel.dispose();
} else if(msg == "gn") {
} else if(msg === "gn") {
checkReceiveMsg(message);
} else {
selectPath(globalPanel, message);
@ -181,7 +190,7 @@ function checkReceiveMsg(message) {
checkMode(outputCodeDir, originCodeDir, inputScriptDir, scriptType,
transplantDir, subsystemName, componentName, compileOptions);
if (buttonName == 'Next') {
if (buttonName === 'Next') {
startNextPlugin();
}
}
@ -190,15 +199,15 @@ function checkReceiveMsg(message) {
* 获取插件执行命令
*/
function nextPluginExeCommand(nextPluginId) {
if (nextPluginId == "kaihong.ApiScan") {
if (nextPluginId === "kaihong.ApiScan") {
return 'api_scan';
} else if (nextPluginId == "kaihong.gn-gen") {
} else if (nextPluginId === "kaihong.gn-gen") {
return 'generate_gn';
} else if (nextPluginId == "kaihong.service-gen") {
} else if (nextPluginId === "kaihong.service-gen") {
return 'generate_service';
} else if (nextPluginId == "kaihong.ts-gen") {
} else if (nextPluginId === "kaihong.ts-gen") {
return 'generate_ts';
} else if (nextPluginId == "kaihong.napi-gen") {
} else if (nextPluginId === "kaihong.napi-gen") {
return 'generate_napi';
} else {
return null;
@ -225,14 +234,14 @@ function startNextPlugin() {
*/
function selectPath(panel, message) {
let mode = 1;
if (message.mode != undefined) {
if (message.mode !== undefined) {
mode = message.mode;
}
flag = flag == "" ? '' : flag;
flag = flag === "" ? '' : flag;
const options = {
canSelectMany: false,//是否可以选择多个
canSelectFiles: mode == 0 ? true : false,//是否选择文件
canSelectFolders: mode == 0 ? false : true,//是否选择文件夹
canSelectFiles: mode === 0 ? true : false,//是否选择文件
canSelectFolders: mode === 0 ? false : true,//是否选择文件夹
defaultUri:vscode.Uri.file(flag),//默认打开本地路径
filters: {
'All files': ['*']
@ -245,7 +254,7 @@ function startNextPlugin() {
var filePath = "";
filePath = fileUri[0].fsPath.concat(',');
filePath = re.replaceAll(filePath, '\\\\', '/');
if (filePath.substring(1,2) == ":") {
if (filePath.substring(1,2) === ":") {
let filePathTemp = filePath.substring(0,1).toUpperCase()
filePath = filePathTemp + filePath.substring(1,filePath.length)
}
@ -254,7 +263,7 @@ function startNextPlugin() {
path: filePath.length > 0 ? filePath.substring(0, filePath.length - 1) : filePath
}
console.log('message.msg: ' + message.msg);
if (!isTrue && message.msg == "selectoutputCodeDir"){
if (!isTrue && message.msg === "selectoutputCodeDir"){
flag = filePath.substring(0, filePath.length - 1);
let fileTempName = "out";
let pos = flag.indexOf(fileTempName);
@ -270,17 +279,17 @@ function startNextPlugin() {
function checkMode(outputCodeDir, originCodeDir, inputScriptDir, scriptType,
transplantDir, subsystemName, componentName, compileOptions) {
outputCodeDir = re.replaceAll(outputCodeDir, " ", "");
if ("" == outputCodeDir) {
if ("" === outputCodeDir) {
vscode.window.showErrorMessage("Please enter the outputCodeDir path!");
return;
}
originCodeDir = re.replaceAll(originCodeDir, " ", "");
if ("" == originCodeDir) {
if ("" === originCodeDir) {
vscode.window.showErrorMessage("Please enter the originCodeDir path!");
return;
}
inputScriptDir = re.replaceAll(inputScriptDir, " ", "");
if ("" == inputScriptDir) {
if ("" === inputScriptDir) {
vscode.window.showErrorMessage("Please enter the inputScriptDir path!");
return;
}
@ -289,17 +298,17 @@ function checkMode(outputCodeDir, originCodeDir, inputScriptDir, scriptType,
return;
}
transplantDir = re.replaceAll(transplantDir, " ", "");
if ("" == transplantDir) {
if ("" === transplantDir) {
vscode.window.showErrorMessage("Please enter the transplantDir path!");
return;
}
subsystemName = re.replaceAll(subsystemName, " ", "");
if ("" == subsystemName) {
if ("" === subsystemName) {
vscode.window.showErrorMessage("Please enter the subsystemName!");
return;
}
componentName = re.replaceAll(componentName, " ", "");
if ("" == componentName) {
if ("" === componentName) {
vscode.window.showErrorMessage("Please enter the componentName!");
return;
}

View File

@ -57,28 +57,32 @@ function readFiles() {
}
}
function checkFileContent(files) {
(function iterator(i) {
if (i === files.length) {
return;
}
fs.stat(path.join(pathDir + '', files[i]), function (err, data) {
if (err) {
NapiLog.logError('read file error' + err);
return;
}
if (data.isFile()) {
let fileName = files[i];
checkGenerate(pathDir + '/' + fileName);
}
iterator(i + 1);
});
})(0);
}
function readDirFiles() {
fs.readdir(pathDir + '', function (err, files) {
if (err) {
NapiLog.logError('readdir file error' + err);
return;
}
(function iterator(i) {
if (i === files.length) {
return;
}
fs.stat(path.join(pathDir + '', files[i]), function (err, data) {
if (err) {
NapiLog.logError('read file error' + err);
return;
}
if (data.isFile()) {
let fileName = files[i];
checkGenerate(pathDir + '/' + fileName);
}
iterator(i + 1);
});
})(0);
checkFileContent(files);
});
}

View File

@ -42,11 +42,11 @@ function activate(context) {
context.subscriptions.push(disposable);
context.subscriptions.push(disposableMenu);
var platform = detectPlatform();
if (platform == 'win') {
if (platform === 'win') {
exeFilePath = __dirname + "/service-gen-win.exe";
} else if (platform == 'mac') {
} else if (platform === 'mac') {
exeFilePath = __dirname + "/service-gen-macos";
} else if (platform == 'Linux') {
} else if (platform === 'Linux') {
exeFilePath = __dirname + "/service-gen-linux";
}
vscode.window.onDidChangeActiveColorTheme(colorTheme => {
@ -63,7 +63,7 @@ function executorService(name, genDir, serviceId) {
exec(command, function (error, stdout, stderr) {
VsPluginLog.logInfo('VsPlugin: stdout =' + stdout + ", stderr =" + stderr);
if (error || stdout.indexOf("success") < 0) {
vscode.window.showErrorMessage("genError:" + (error != null ? error : "") + stdout);
vscode.window.showErrorMessage("genError:" + (error !== null ? error : "") + stdout);
return VsPluginLog.logError("VsPlugin:" + error + stdout);
}
vscode.window.showInformationMessage("Generated successfully");
@ -77,6 +77,22 @@ function exeFileExit() {
return false;
}
function checkBoolAndItems(boolValue, items) {
if (typeof(boolValue) === 'boolean' && Array.isArray(items) && boolValue === true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.service-gen';
for (let i = 0; i < items.length; i++) {
if (myExtensionId === items[i] && (i === items.length - 1)) {
importToolChain = false;
} else if (myExtensionId === items[i] && (i !== items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
}
function register(context, command) {
let disposable = vscode.commands.registerCommand(command, function (uri, boolValue, items) {
// The code you place here will be executed every time your command is executed
@ -90,28 +106,15 @@ function register(context, command) {
retainContextWhenHidden: true, // Keep the WebView state when it is hidden to avoid being reset
}
);
if (typeof(boolValue) == 'boolean' && Array.isArray(items)) {
if (boolValue == true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.service-gen';
for (let i = 0; i < items.length; i++) {
if (myExtensionId == items[i] && (i == items.length - 1)) {
importToolChain = false;
} else if (myExtensionId == items[i] && (i != items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
}
checkBoolAndItems(boolValue, items);
globalPanel.webview.html = getWebviewContent(context, importToolChain);
let msg;
globalPanel.webview.onDidReceiveMessage(message => {
msg = message.msg;
if (msg == "cancel") {
if (msg === "cancel") {
globalPanel.dispose();
} else if(msg == "param") {
} else if(msg === "param") {
checkReceiveMsg(message);
} else {
selectPath(globalPanel, message);
@ -134,13 +137,13 @@ function checkReceiveMsg(message) {
let serviceId = message.serviceId;
let buttonName = message.buttonName;
name = re.replaceAll(name, " ", "");
if ("" == name) {
if ("" === name) {
vscode.window.showErrorMessage("Please enter the path!");
return;
}
if (exeFileExit()) {
executorService(name, genDir, serviceId);
if (buttonName == 'Next') {
if (buttonName === 'Next') {
startNextPlugin();
}
} else {
@ -152,15 +155,15 @@ function checkReceiveMsg(message) {
* 获取插件执行命令
*/
function nextPluginExeCommand(nextPluginId) {
if (nextPluginId == "kaihong.ApiScan") {
if (nextPluginId === "kaihong.ApiScan") {
return 'api_scan';
} else if (nextPluginId == "kaihong.gn-gen") {
} else if (nextPluginId === "kaihong.gn-gen") {
return 'generate_gn';
} else if (nextPluginId == "kaihong.service-gen") {
} else if (nextPluginId === "kaihong.service-gen") {
return 'generate_service';
} else if (nextPluginId == "kaihong.ts-gen") {
} else if (nextPluginId === "kaihong.ts-gen") {
return 'generate_ts';
} else if (nextPluginId == "kaihong.napi-gen") {
} else if (nextPluginId === "kaihong.napi-gen") {
return 'generate_napi';
} else {
return null;
@ -188,14 +191,14 @@ function startNextPlugin() {
*/
function selectPath(panel, message) {
let mode = 1;
if (message.mode != undefined) {
if (message.mode !== undefined) {
mode = message.mode;
}
const options = {
canSelectFiles: mode == 0 ? true : false,//是否选择文件
canSelectFolders: mode == 0 ? false : true,//是否选择文件夹
canSelectFiles: mode === 0 ? true : false,//是否选择文件
canSelectFolders: mode === 0 ? false : true,//是否选择文件夹
defaultUri:vscode.Uri.file(message.filePath),//默认打开本地路径
filters: mode == 0 ? {
filters: mode === 0 ? {
'All files': ['h']
} : {}
};
@ -247,4 +250,4 @@ function getWebViewContent(context, templatePath) {
module.exports = {
activate,
deactivate
}
};

View File

@ -43,11 +43,11 @@ function activate(context) {
context.subscriptions.push(disposableMenu);
var platform = detectPlatform();
if (platform == 'win') {
if (platform === 'win') {
exeFilePath = __dirname + "/napi_generator-win.exe";
} else if (platform == 'mac') {
} else if (platform === 'mac') {
exeFilePath = __dirname + "/napi_generator-macos";
} else if (platform == 'Linux') {
} else if (platform === 'Linux') {
exeFilePath = __dirname + "/napi_generator-linux";
}
}
@ -58,7 +58,7 @@ function executorH2Ts(name, genDir) {
exec(command, function (error, stdout, stderr) {
VsPluginLog.logInfo('VsPlugin: stdout =' + stdout + ", stderr =" + stderr);
if (error || stdout.indexOf("success") < 0) {
vscode.window.showErrorMessage("genError:" + (error != null ? error : "") + stdout);
vscode.window.showErrorMessage("genError:" + (error !== null ? error : "") + stdout);
return VsPluginLog.logError("VsPlugin:" + error + stdout);
}
vscode.window.showInformationMessage("Generated successfully");
@ -72,6 +72,22 @@ function exeFileExit() {
return false;
}
function checkBoolAndItems(boolValue, items) {
if (typeof(boolValue) === 'boolean' && Array.isArray(items) && boolValue === true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.ts-gen';
for (let i = 0; i < items.length; i++) {
if (myExtensionId === items[i] && (i === items.length - 1)) {
importToolChain = false;
} else if (myExtensionId === items[i] && (i !== items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
}
function register(context, command) {
let disposable = vscode.commands.registerCommand(command, function (uri, boolValue, items) {
// The code you place here will be executed every time your command is executed
@ -85,29 +101,16 @@ function register(context, command) {
retainContextWhenHidden: true, // Keep the WebView state when it is hidden to avoid being reset
}
);
if (typeof(boolValue) == 'boolean' && Array.isArray(items)) {
if (boolValue == true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.ts-gen';
for (let i = 0; i < items.length; i++) {
if (myExtensionId == items[i] && (i == items.length - 1)) {
importToolChain = false;
} else if (myExtensionId == items[i] && (i != items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
}
checkBoolAndItems(boolValue, items);
globalPanel.webview.html = getWebviewContent(context, importToolChain);
let msg;
globalPanel.webview.onDidReceiveMessage(message => {
msg = message.msg;
if (msg == "cancel") {
if (msg === "cancel") {
globalPanel.dispose();
}
else if(msg == "h2ts") {
else if(msg === "h2ts") {
checkReceiveMsg(message);
}else {
selectPath(globalPanel, message);
@ -129,13 +132,13 @@ function checkReceiveMsg(message) {
let genDir = message.genDir;
let buttonName = message.buttonName;
name = re.replaceAll(name, " ", "");
if ("" == name) {
if ("" === name) {
vscode.window.showErrorMessage("Please enter the path!");
return;
}
if (exeFileExit()) {
executorH2Ts(name, genDir);
if (buttonName == 'Next') {
if (buttonName === 'Next') {
startNextPlugin();
}
} else {
@ -147,15 +150,15 @@ function checkReceiveMsg(message) {
* 获取插件执行命令
*/
function nextPluginExeCommand(nextPluginId) {
if (nextPluginId == "kaihong.ApiScan") {
if (nextPluginId === "kaihong.ApiScan") {
return 'api_scan';
} else if (nextPluginId == "kaihong.gn-gen") {
} else if (nextPluginId === "kaihong.gn-gen") {
return 'generate_gn';
} else if (nextPluginId == "kaihong.service-gen") {
} else if (nextPluginId === "kaihong.service-gen") {
return 'generate_service';
} else if (nextPluginId == "kaihong.ts-gen") {
} else if (nextPluginId === "kaihong.ts-gen") {
return 'generate_ts';
} else if (nextPluginId == "kaihong.napi-gen") {
} else if (nextPluginId === "kaihong.napi-gen") {
return 'generate_napi';
} else {
return null;
@ -182,16 +185,16 @@ function startNextPlugin() {
*/
function selectPath(panel, message) {
let mode = 1;
if (message.mode != undefined) {
if (message.mode !== undefined) {
mode = message.mode;
}
const options = {
canSelectMany: mode == 0 ? true : false,//是否可以选择多个
openLabel: mode == 0 ? '选择文件' : '选择文件夹',//打开选择的右下角按钮label
canSelectFiles: mode == 0 ? true : false,//是否选择文件
canSelectFolders: mode == 0 ? false : true,//是否选择文件夹
canSelectMany: mode === 0 ? true : false,//是否可以选择多个
openLabel: mode === 0 ? '选择文件' : '选择文件夹',//打开选择的右下角按钮label
canSelectFiles: mode === 0 ? true : false,//是否选择文件
canSelectFolders: mode === 0 ? false : true,//是否选择文件夹
defaultUri:vscode.Uri.file(''),//默认打开本地路径
filters: mode == 1 ? {} : { // 文件过滤选项在文件夹选择模式下不可设置此配置否则ubuntu系统下无法选择文件夹
filters: mode === 1 ? {} : { // 文件过滤选项在文件夹选择模式下不可设置此配置否则ubuntu系统下无法选择文件夹
'Text files': ['h']
}
};

View File

@ -42,11 +42,11 @@ function activate(context) {
context.subscriptions.push(disposable);
context.subscriptions.push(disposableMenu);
var platform = detectPlatform();
if (platform == 'win') {
if (platform === 'win') {
exeFilePath = __dirname + "/napi_generator-win.exe";
} else if (platform == 'mac') {
} else if (platform === 'mac') {
exeFilePath = __dirname + "/napi_generator-macos";
} else if (platform == 'Linux') {
} else if (platform === 'Linux') {
exeFilePath = __dirname + "/napi_generator-linux";
}
}
@ -56,7 +56,7 @@ function executor(name, genDir, mode,numberType, importIsCheck) {
exec(genCommand(name, genDir, mode,numberType, importIsCheck), function (error, stdout, stderr) {
VsPluginLog.logInfo('VsPlugin: stdout =' + stdout + ", stderr =" + stderr);
if (error || stdout.indexOf("success") < 0) {
vscode.window.showErrorMessage("genError:" + (error != null ? error : "") + stdout);
vscode.window.showErrorMessage("genError:" + (error !== null ? error : "") + stdout);
return VsPluginLog.logError("VsPlugin:" + error + stdout);
}
vscode.window.showInformationMessage("Generated successfully");
@ -64,8 +64,8 @@ function executor(name, genDir, mode,numberType, importIsCheck) {
}
function genCommand(name, genDir, mode,numberType, importIsCheck) {
var genFileMode = mode == 0 ? " -f " : " -d ";
if (genDir == ""){
var genFileMode = mode === 0 ? " -f " : " -d ";
if (genDir === ""){
return exeFilePath + genFileMode + name;
}
return exeFilePath + genFileMode + name + " -o " + genDir + " -n " + numberType + " -i " + importIsCheck;
@ -78,6 +78,28 @@ function exeFileExit() {
return false;
}
function checkLoop(items, myExtensionId, boolValue) {
for (let i = 0; i < items.length; i++) {
if (myExtensionId === items[i] && (i === items.length - 1)) {
importToolChain = false;
} else if (myExtensionId === items[i] && (i !== items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
function checkBoolAndItems(boolValue, items) {
if (typeof(boolValue) === 'boolean' && Array.isArray(items)) {
if (boolValue === true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.napi-gen';
checkLoop(items, myExtensionId, boolValue);
}
}
}
function register(context, command) {
let disposable = vscode.commands.registerCommand(command, function (uri, boolValue, items) {
// The code you place here will be executed every time your command is executed
@ -92,28 +114,14 @@ function register(context, command) {
}
);
if (typeof(boolValue) == 'boolean' && Array.isArray(items)) {
if (boolValue == true) {
//遍历数组item,查看当前插件id是数组的第几个元素并拿出下一个元素并判断当前id是否是最后一个元素并做相应处理
let myExtensionId = 'kaihong.napi-gen';
for (let i = 0; i < items.length; i++) {
if (myExtensionId == items[i] && (i == items.length - 1)) {
importToolChain = false;
} else if (myExtensionId == items[i] && (i != items.length - 1)) {
importToolChain = boolValue;
nextPluginId = items[i + 1];
}
extensionIds.push(items[i]);
}
}
}
checkBoolAndItems(boolValue, items);
globalPanel.webview.html = getWebviewContent(context, importToolChain);
let msg;
globalPanel.webview.onDidReceiveMessage(message => {
msg = message.msg;
if (msg == "cancel") {
if (msg === "cancel") {
globalPanel.dispose();
} else if(msg == "param") {
} else if(msg === "param") {
checkReceiveMsg(message);
} else {
selectPath(globalPanel, message);
@ -138,7 +146,7 @@ function checkReceiveMsg(message) {
let importIsCheck = message.importIsCheck;
let buttonName = message.buttonName;
checkMode(name, genDir, mode, numberType, importIsCheck);
if (buttonName == 'Next') {
if (buttonName === 'Next') {
startNextPlugin();
}
}
@ -147,15 +155,15 @@ function checkReceiveMsg(message) {
* 获取插件执行命令
*/
function nextPluginExeCommand(nextPluginId) {
if (nextPluginId == "kaihong.ApiScan") {
if (nextPluginId === "kaihong.ApiScan") {
return 'api_scan';
} else if (nextPluginId == "kaihong.gn-gen") {
} else if (nextPluginId === "kaihong.gn-gen") {
return 'generate_gn';
} else if (nextPluginId == "kaihong.service-gen") {
} else if (nextPluginId === "kaihong.service-gen") {
return 'generate_service';
} else if (nextPluginId == "kaihong.ts-gen") {
} else if (nextPluginId === "kaihong.ts-gen") {
return 'generate_ts';
} else if (nextPluginId == "kaihong.napi-gen") {
} else if (nextPluginId === "kaihong.napi-gen") {
return 'generate_napi';
}
else {
@ -184,17 +192,17 @@ function startNextPlugin() {
function selectPath(panel, message) {
let msg = message.msg;
let mode = 1;
if (message.mode != undefined) {
if (message.mode !== undefined) {
mode = message.mode;
}
const options = {
canSelectMany: mode == 0 ? true : false,//是否可以选择多个
openLabel: mode == 0 ? '选择文件' : '选择文件夹',//打开选择的右下角按钮label
canSelectFiles: mode == 0 ? true : false,//是否选择文件
canSelectFolders: mode == 0 ? false : true,//是否选择文件夹
canSelectMany: mode === 0 ? true : false,//是否可以选择多个
openLabel: mode === 0 ? '选择文件' : '选择文件夹',//打开选择的右下角按钮label
canSelectFiles: mode === 0 ? true : false,//是否选择文件
canSelectFolders: mode === 0 ? false : true,//是否选择文件夹
defaultUri:vscode.Uri.file(''),//默认打开本地路径
// 文件过滤选项在文件夹选择模式下不可设置此配置否则ubuntu系统下无法选择文件夹
filters: mode == 1 ? {} : { 'Text files': ['d.ts'] }
filters: mode === 1 ? {} : { 'Text files': ['d.ts'] }
};
@ -217,11 +225,11 @@ function startNextPlugin() {
function checkMode(name, genDir, mode,numberType, importIsCheck) {
name = re.replaceAll(name, " ", "");
if ("" == name) {
if ("" === name) {
vscode.window.showErrorMessage("Please enter the path!");
return;
}
if (mode == 0) {
if (mode === 0) {
if (name.indexOf(".") < 0) {
vscode.window.showErrorMessage("Please enter the correct file path!");
return;

View File

@ -17,49 +17,64 @@ const { NumberIncrease } = require("../tools/common");
const { analyzeFunction } = require("./function");
function checkMatcher1(classBody, matcher, result) {
if (matcher) {
let valueName = re.getReg(classBody, matcher.regs[1]);
let valueType = re.getReg(classBody, matcher.regs[2]);
if (valueType.indexOf('number') >= 0) {
valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease());
}
result.value.push({
name: valueName,
type: valueType
});
}
}
function checkMatcher2(matcher, classBody, result, data) {
if (matcher) {
let funcDetail = analyzeFunction(data,
re.getReg(classBody, matcher.regs[1]) !== '', re.getReg(classBody, matcher.regs[2]),
re.getReg(classBody, matcher.regs[3]), re.getReg(classBody, matcher.regs[4]));
if (funcDetail !== null) {
result.function.push(funcDetail);
}
}
}
function checkAnalyzeClass(data, body, result) {
for (let i in body) {
let classBody = body[i];
// 去除前面的空格
while (classBody.length > 0 && classBody[0] === ' ') {
classBody = classBody.substring(1, classBody.length);
}
// 去除后面的空格
while (classBody.length > 0 && classBody[-1] === ' ') {
classBody = classBody.substring(0, classBody.length - 1);
}
// 如果t为空直接返回
if (classBody === '') {
break;
}
let matcher = re.match(' *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>]+)', classBody);
checkMatcher1(classBody, matcher, result);
let rules = '(static )? *([A-Za-z0-9_]+)\\(([\n a-zA-Z:;=,_0-9?<>{}|]*)\\) *: *([A-Za-z0-9_<>{}:, .]+)';
matcher = re.match(rules, classBody);
checkMatcher2(matcher, classBody, result, data);
}
}
/**interface解析 */
function analyzeClass(data) {
// # replace(" ", "").
let body = re.replaceAll(data, "\n", "").split(";")
let body = re.replaceAll(data, '\n', '').split(";");
let result = {
value: [],
function: []
}
for (let i in body) {
let classBody = body[i]
// 去除前面的空格
while (classBody.length > 0 && classBody[0] === ' ') {
classBody = classBody.substring(1, classBody.length)
}
// 去除后面的空格
while (classBody.length > 0 && classBody[-1] === ' ') {
classBody = classBody.substring(0, classBody.length - 1)
}
// 如果t为空直接返回
if (classBody === "") break
let matcher = re.match(" *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>]+)", classBody)
if (matcher) {
let valueName = re.getReg(classBody, matcher.regs[1])
let valueType = re.getReg(classBody, matcher.regs[2])
if (valueType.indexOf("number") >= 0) {
valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
}
result.value.push({
name: valueName,
type: valueType
})
}
let rules = "(static )? *([A-Za-z0-9_]+)\\(([\n a-zA-Z:;=,_0-9?<>{}|]*)\\) *: *([A-Za-z0-9_<>{}:, .]+)";
matcher = re.match(rules, classBody)
if (matcher) {
let funcDetail = analyzeFunction(data,
re.getReg(classBody, matcher.regs[1]) !== '', re.getReg(classBody, matcher.regs[2]),
re.getReg(classBody, matcher.regs[3]), re.getReg(classBody, matcher.regs[4]))
if (funcDetail != null)
result.function.push(funcDetail)
}
}
return result
checkAnalyzeClass(data, body, result);
return result;
}
module.exports = {

View File

@ -20,185 +20,197 @@ const { NapiLog } = require("../tools/NapiLog");
const { randomInt } = require("crypto");
const { print } = require("../tools/tool");
function checkTT(tt, t, result) {
if (tt) { // 变量
let valueName = re.getReg(t, tt.regs[1]);
let valueType = re.getReg(t, tt.regs[2]);
let index = valueType.indexOf('number');
while (index !== -1) {
valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease());
index = valueType.indexOf('number');
}
result.value.push({
name: valueName,
type: valueType
});
}
}
function checkAnalyzeSubInterface(body, result) {
for (let i in body) {
let t = body[i];
while (t.length > 0 && t[0] === ' ') { // 去除前面的空格
t = t.substring(1, t.length);
}
while (t.length > 0 && t[-1] === ' ') {// 去除后面的空格
t = t.substring(0, t.length - 1);
}
if (t === '') {
break; // 如果t为空直接返回
}
let tt = re.match(' *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\] ]+)', t);
checkTT(tt, t, result);
}
}
function analyzeSubInterface(data) {
let body = re.replaceAll(data, "\n", "").split(";") // # replace(" ", "").
let body = re.replaceAll(data, '\n', '').split(';'); // # replace(" ", '').
let result = {
value: [],
function: [],
parentNameList: [],
childList: [],
parentList: []
}
for (let i in body) {
let t = body[i]
while (t.length > 0 && t[0] == ' ') // 去除前面的空格
t = t.substring(1, t.length)
while (t.length > 0 && t[-1] == ' ') // 去除后面的空格
t = t.substring(0, t.length - 1)
if (t == "") break // 如果t为空直接返回
let tt = re.match(" *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\] ]+)", t)
if (tt) { // 变量
};
let valueName = re.getReg(t, tt.regs[1])
let valueType = re.getReg(t, tt.regs[2])
let index = valueType.indexOf("number")
while (index !== -1) {
valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
index = valueType.indexOf("number")
}
result.value.push({
name: valueName,
type: valueType
})
}
}
return result
checkAnalyzeSubInterface(body, result);
return result;
}
function getFuncParaType(v, interfaceName, data) {
let arrayType = re.match("(Async)*Callback<(Array<([a-zA-Z_0-9]+)>)>", v["type"])
let parameter = v["type"]
let arrayType = re.match('(Async)*Callback<(Array<([a-zA-Z_0-9]+)>)>', v.type);
let parameter = v.type;
if (arrayType) {
parameter = re.getReg(v["type"], arrayType.regs[2])
parameter = re.getReg(v.type, arrayType.regs[2]);
}
if (isEnum(parameter, data)) {
let index = enumIndex(parameter, data)
if (data.enum[index].body.enumValueType == EnumValueType.ENUM_VALUE_TYPE_NUMBER) {
v["type"] = v["type"].replace(parameter, "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
} else if (data.enum[index].body.enumValueType == EnumValueType.ENUM_VALUE_TYPE_STRING) {
v["type"] = v["type"].replace(parameter, "string")
let index = enumIndex(parameter, data);
if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) {
v.type = v.type.replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease());
} else if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) {
v.type = v.type.replace(parameter, 'string');
} else {
NapiLog.logError("analyzeFunction getFuncParaType is not support this type %s"
NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s'
.format(data.enum[index].body.enumValueType));
return null
return null;
}
}
let interfaceType = re.match("{([A-Za-z0-9_]+:[A-Za-z0-9_,]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$", v["type"])
let interfaceType = re.match('{([A-Za-z0-9_]+:[A-Za-z0-9_,]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$', v.type);
if (interfaceType) {
v["type"] = interfaceName
v.type = interfaceName;
}
if (parameter.indexOf("number") >= 0) {
v["type"] = v["type"].replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
if (parameter.indexOf('number') >= 0) {
v.type = v.type.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease());
}
// type的处理
if (isType(parameter, data)) {
let index = typeIndex(parameter, data)
let index = typeIndex(parameter, data);
if (data.type[index].isEnum) {
v["type"] = v["type"].replace(parameter, "string")
v.type = v.type.replace(parameter, 'string');
}
}
return v
return v;
}
function analyzeFuncNoNameInterface(data, values) {
values = re.replaceAll(re.replaceAll(values, " ", ""), "\n", "")
let interfaceName = ""
let matchNoName = "([:{,;a-zA-Z_0-9]*)\\?*(:[A-Za-z0-9_,;]*)?:{([A-Za-z0-9_]+:"+
"[A-Za-z0-9_,;]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}(}|,|;)?$"
let matchs = re.match(matchNoName, values)
values = re.replaceAll(re.replaceAll(values, ' ', ''), '\n', '');
let interfaceName = '';
let matchNoName = '([:{,;a-zA-Z_0-9]*)\\?*(:[A-Za-z0-9_,;]*)?:{([A-Za-z0-9_]+:' +
'[A-Za-z0-9_,;]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}(}|,|;)?$';
let matchs = re.match(matchNoName, values);
if (matchs) {
let st = values.lastIndexOf("{")
let end = values.indexOf("}")
let st = values.lastIndexOf('{');
let end = values.indexOf('}');
let number = NumberIncrease.getAndIncrease();
interfaceName = "AUTO_INTERFACE_%s".format(number)
let interfaceBody = values.substring(st+1, end)
let typeInterface = "{%s}".format(interfaceBody)
values = re.replaceAll(values, typeInterface, interfaceName)
interfaceBody = re.replaceAll(interfaceBody, ",", ";")
interfaceName = 'AUTO_INTERFACE_%s'.format(number);
let interfaceBody = values.substring(st+1, end);
let typeInterface = '{%s}'.format(interfaceBody);
values = re.replaceAll(values, typeInterface, interfaceName);
interfaceBody = re.replaceAll(interfaceBody, ",", ';');
data.interface.push({
name: interfaceName,
body: analyzeSubInterface(interfaceBody)
})
});
}
matchs = re.match(matchNoName, values)
if(matchs) {
let resNoNameInter = analyzeFuncNoNameInterface(data, values)
values = resNoNameInter.values
matchs = re.match(matchNoName, values);
if (matchs) {
let resNoNameInter = analyzeFuncNoNameInterface(data, values);
values = resNoNameInter.values;
}
let result = {
interfaceName: interfaceName,
values: values
}
return result
return result;
}
function analyseSubReturn(ret, data) {
// 匿名interface返回值 function fun4(input: string): { read: number; written: number };
ret = re.replaceAll(re.replaceAll(ret, " ", ""), "\n", "")
let tt = re.match("{([A-Za-z0-9_]+:[A-Za-z0-9_,;]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}", ret)
ret = re.replaceAll(re.replaceAll(ret, ' ', ''), '\n', '');
let tt = re.match('{([A-Za-z0-9_]+:[A-Za-z0-9_,;]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}', ret);
if (tt) {
let len = tt.regs.length
let res = ""
let interfaceName = ""
let len = tt.regs.length;
let res = '';
let interfaceName = '';
for (let i=1; i<len; i++) {
let regs1 = re.getReg(ret, tt.regs[i])
if (regs1 !== "}" && regs1 !== ",") {
res += regs1
let regs1 = re.getReg(ret, tt.regs[i]);
if (regs1 !== '}' && regs1 !== ',') {
res += regs1;
}
}
};
let number = NumberIncrease.getAndIncrease();
interfaceName = "AUTO_INTERFACE_%s".format(number)
let interfaceBody = res
ret = interfaceName
interfaceName = 'AUTO_INTERFACE_%s'.format(number);
let interfaceBody = res;
ret = interfaceName;
interfaceBody = re.replaceAll(interfaceBody, ",", ";")
interfaceBody = re.replaceAll(interfaceBody, ',', ';');
data.interface.push({
name: interfaceName,
body: analyzeSubInterface(interfaceBody)
})
});
}
if (ret.indexOf("number") >= 0) {
ret = ret.replaceAll("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
if (ret.indexOf('number') >= 0) {
ret = ret.replaceAll('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease());
}
return ret
return ret;
}
/**函数解析 */
function analyzeFunction(data, isStatic, name, values, ret) {
let res = analyzeFuncNoNameInterface(data, values)
let tmp
let funcType
let res = analyzeFuncNoNameInterface(data, values);
let tmp;
let funcType;
if (res) {
tmp = analyzeParams(name, res.values)
values = tmp[0]
funcType = tmp[1]
tmp = analyzeParams(name, res.values);
values = tmp[0];
funcType = tmp[1];
}
tmp = analyzeReturn(ret)
ret = tmp[0]
tmp = analyzeReturn(ret);
ret = tmp[0];
if (tmp[1]) { // 返回类型为 Promise, 解析成等价的AsyncCallback方法
funcType = FuncType.ASYNC
funcType = FuncType.ASYNC;
// 将返回值Promise<type>改为AsyncCallback<type>,作为方法的入参
let paramType = ret.replace("Promise", "AsyncCallback")
values.push({name: "promise", optional: false, type: paramType})
ret = "void" // 返回值由Promise改为void与AsyncCallback接口保持一致
let paramType = ret.replace('Promise', 'AsyncCallback');
values.push({name: 'promise', optional: false, type: paramType});
ret = 'void'; // 返回值由Promise改为void与AsyncCallback接口保持一致
}
for (let j in values) {
let v = values[j]
v = getFuncParaType(v, res.interfaceName, data)
if (v == null) {
NapiLog.logError("analyzeFunction is not support this type %s".format(v));
let v = values[j];
v = getFuncParaType(v, res.interfaceName, data);
if (v === null) {
NapiLog.logError('analyzeFunction is not support this type %s'.format(v));
}
}
ret = analyseSubReturn(ret, data)
ret = analyseSubReturn(ret, data);
let result = {
name: name,
type: funcType,
value: values,
ret: ret,
isStatic: isStatic
}
return result
};
return result;
}
module.exports = {
analyzeFunction,
analyzeSubInterface,
getFuncParaType
}
};

View File

@ -19,13 +19,13 @@ const { analyzeFunction } = require("./function");
/* 匿名interface */
function analyzeNoNameInterface(valueType, valueName, rsltInterface) {
valueType = re.replaceAll(valueType, " ", "")
valueType = re.replaceAll(valueType, '' ', '')
let matchs = re.match("{([A-Za-z0-9_]+:[A-Za-z0-9_,;]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$", valueType)
if (matchs) {
let number = NumberIncrease.getAndIncrease();
let interfaceTypeName = 'AUTO_INTERFACE_%s_%s'.format(valueName, number)
let interfaceBody = valueType.substring(1, valueType.length-1)
interfaceBody = re.replaceAll(interfaceBody, ",", ";")
interfaceBody = re.replaceAll(interfaceBody, ',', ';')
rsltInterface.push({
name: interfaceTypeName,
body: analyzeInterface(interfaceBody, rsltInterface)
@ -37,12 +37,12 @@ function analyzeNoNameInterface(valueType, valueName, rsltInterface) {
/* 去除单行注释// */
function parseNotes(data) {
let notes = data.indexOf("//") >= 0 ? data.substring(data.indexOf("//"), data.length) : "";
while(notes != "") {
let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : '';
while(notes !== '') {
notes = notes.substring(0, notes.indexOf("\n"));
data = data.replace(notes, "");
notes = ""
let st = data.indexOf("//");
data = data.replace(notes, '');
notes = ''
let st = data.indexOf('//');
if(st >= 0) {
notes = data.substring(st, data.length);
}
@ -50,49 +50,64 @@ function parseNotes(data) {
return data
}
function checkAnalyzeTT(tt, t, rsltInterface, result) {
if (tt && t.indexOf("=>") < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理
let valueName = re.getReg(t, tt.regs[1])
let valueType = re.getReg(t, tt.regs[2])
let index = valueType.indexOf('number')
while (index !== -1) {
valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease())
index = valueType.indexOf('number')
}
valueType = analyzeNoNameInterface(valueType, valueName, rsltInterface);
result.value.push({
name: valueName,
type: valueType
})
}
}
function checkAnalyzeInterface(data, body, result, rsltInterface) {
for (let i in body) {
let t = body[i];
while (t.length > 0 && t[0] === ' ') { // 去除前面的空格
t = t.substring(1, t.length)
}
while (t.length > 0 && t[-1] === ' ') { // 去除后面的空格
t = t.substring(0, t.length - 1)
}
if (t === '') {
break // 如果t为空直接返回
}
let tt = re.match(' *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t);
checkAnalyzeTT(tt, t, rsltInterface, result);
tt = re.match("(static )* *(\\$*[A-Za-z0-9_]+) *[:]? *\\(([\n 'a-zA-Z:;=,_0-9?<>{}|[\\]]*)\\)" +
' *(:|=>) *([A-Za-z0-9_<>{}:, .[\\]]+)', t);
if (tt) { // 接口函数成员
let funcDetail = analyzeFunction(data, re.getReg(t, tt.regs[1]) !== '', re.getReg(t, tt.regs[2]),
re.getReg(t, tt.regs[3]), re.getReg(t, tt.regs[5]));
if (funcDetail !== null) {
// 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法)
addUniqFunc2List(funcDetail, result.function);
}
}
}
}
/**interface解析 */
function analyzeInterface(data, rsltInterface = null) { // same as class
let body = data
body = body.indexOf("//") < 0 ? body : parseNotes(body)
body = re.replaceAll(body, "\n", "").split(";")
body = body.indexOf('//') < 0 ? body : parseNotes(body);
body = re.replaceAll(body, '\n', '').split(';');
let result = {
value: [],
function: []
}
for (let i in body) {
let t = body[i]
while (t.length > 0 && t[0] == ' ') // 去除前面的空格
t = t.substring(1, t.length)
while (t.length > 0 && t[-1] == ' ') // 去除后面的空格
t = t.substring(0, t.length - 1)
if (t == "") break // 如果t为空直接返回
let tt = re.match(" *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\]| ]+)", t)
if (tt && t.indexOf("=>") < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理
let valueName = re.getReg(t, tt.regs[1])
let valueType = re.getReg(t, tt.regs[2])
let index = valueType.indexOf("number")
while (index !== -1) {
valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
index = valueType.indexOf("number")
}
valueType = analyzeNoNameInterface(valueType, valueName, rsltInterface)
result.value.push({
name: valueName,
type: valueType
})
}
tt = re.match("(static )* *(\\$*[A-Za-z0-9_]+) *[:]? *\\(([\n 'a-zA-Z:;=,_0-9?<>{}|[\\]]*)\\)"
+ " *(:|=>) *([A-Za-z0-9_<>{}:, .[\\]]+)", t)
if (tt) { // 接口函数成员
let funcDetail = analyzeFunction(data, re.getReg(t, tt.regs[1]) != '', re.getReg(t, tt.regs[2]),
re.getReg(t, tt.regs[3]), re.getReg(t, tt.regs[5]))
if (funcDetail != null) {
// 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法)
addUniqFunc2List(funcDetail, result.function)
}
}
}
return result
checkAnalyzeInterface(data, body, result, rsltInterface);
return result;
}
module.exports = {

View File

@ -17,53 +17,62 @@ const { checkOutBody, print } = require("../tools/tool");
const { FuncType } = require("../tools/common");
const { NapiLog } = require("../tools/NapiLog");
/**函数参数解析 */
function analyzeParams(funcName, values) {
let result = []
let funcType = FuncType.DIRECT
let optionalParamCount = 0; // 可选参数的个数
while (values.length > 0) {
let v = checkOutBody(values, 0, ["", ","])
if (v == null)
v = values
values = values.substring(v.length, values.length)
let matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *([a-zA-Z<,>|_0-9\\[\\]\\(\\):='{}]+)", v)
if (matchs === null && (funcName === "on" || funcName === "off")) {
// on和off的第一个参数的类型可以是一串字符
matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *\"([a-zA-Z|_0-9\\[\\]\\(\\):='{}]+)\"", v)
}
if (matchs != null) {
let type = re.getReg(v, matchs.regs[3])
if (type.indexOf("Map") < 0) {
type = type.replace(/,/g, "")
}
function checkMatchers(v, matchs, optionalParamCount, result, funcType, funcName) {
let type = re.getReg(v, matchs.regs[3]);
if (type.indexOf('Map') < 0) {
type = type.replace(/,/g, '');
}
let optionalFlag = re.getReg(v, matchs.regs[2]) === '?' ? true : false;
let checkParamOk = true;
if (optionalFlag) {
optionalParamCount++;
} else if (optionalParamCount > 0) {
// 可选参数之后不能再有必选参数,必选都是可选参数。
NapiLog.logError("Invalid parameter [%s] of function [%s],".format(v, funcName)
+ " the required parameter cannot follow an optional parameter.");
checkParamOk = false;
}
if (checkParamOk) {
result.push({ "name": re.getReg(v, matchs.regs[1]), "type": type , "optional": optionalFlag})
if (type.indexOf("AsyncCallback") >= 0)
funcType = FuncType.ASYNC
if (funcType === FuncType.DIRECT && type.indexOf("Callback") >= 0 && type.indexOf("AsyncCallback") < 0)
funcType = FuncType.SYNC
}
let optionalFlag = re.getReg(v, matchs.regs[2]) === '?' ? true : false;
let checkParamOk = true;
if (optionalFlag) {
optionalParamCount++;
} else if (optionalParamCount > 0) {
// 可选参数之后不能再有必选参数,必选都是可选参数。
NapiLog.logError('Invalid parameter [%s] of function [%s],'.format(v, funcName) +
' the required parameter cannot follow an optional parameter.');
checkParamOk = false;
}
if (checkParamOk) {
result.push({ 'name': re.getReg(v, matchs.regs[1]), 'type': type, 'optional': optionalFlag});
if (type.indexOf('AsyncCallback') >= 0) {
funcType = FuncType.ASYNC;
}
else {
NapiLog.logError("方法[%s]的参数列表[%s]解析失败。".format(funcName, v));
NapiLog.logError("Failed to analyse parameter [%s] of function [%s].".format(v, funcName));
if (funcType === FuncType.DIRECT && type.indexOf('Callback') >= 0 && type.indexOf('AsyncCallback') < 0) {
funcType = FuncType.SYNC;
}
}
return [result, funcType]
}
function checkAnalyzeParams(values, result, funcType, optionalParamCount, funcName) {
while (values.length > 0) {
let v = checkOutBody(values, 0, ['', ',']);
if (v === null) {
v = values;
}
values = values.substring(v.length, values.length);
let matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *([a-zA-Z<,>|_0-9\\[\\]\\(\\):='{}]+)", v);
if (matchs === null && (funcName === 'on' || funcName === 'off')) {
// on和off的第一个参数的类型可以是一串字符
matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *\"([a-zA-Z|_0-9\\[\\]\\(\\):='{}]+)\"", v);
} else if (matchs != null) {
checkMatchers(v, matchs, optionalParamCount, result, funcType, funcName);
} else {
NapiLog.logError('方法[%s]的参数列表[%s]解析失败。'.format(funcName, v));
NapiLog.logError('Failed to analyse parameter [%s] of function [%s].'.format(v, funcName));
}
}
}
/**函数参数解析 */
function analyzeParams(funcName, values) {
let result = [];
let funcType = FuncType.DIRECT;
let optionalParamCount = 0; // 可选参数的个数
checkAnalyzeParams(values, result, funcType, optionalParamCount, funcName);
return [result, funcType];
}
module.exports = {
analyzeParams
}
};

View File

@ -17,78 +17,90 @@ const { NumberIncrease } = require("../tools/common");
/* 去除单行注释// */
function parseNotes(data) {
let notes = data.indexOf("//") >= 0 ? data.substring(data.indexOf("//"), data.length) : "";
while(notes != "") {
let notes = data.indexOf("//") >= 0 ? data.substring(data.indexOf("//"), data.length) : '';
while(notes !== '') {
notes = notes.substring(0, notes.indexOf("\n"));
data = data.replace(notes, "");
notes = ""
let st = data.indexOf("//");
data = data.replace(notes, '');
notes = '';
let st = data.indexOf('//');
if(st >= 0) {
notes = data.substring(st, data.length);
}
}
return data
return data;
}
function checkTT(tt, t, result) {
if (tt && t.indexOf('=>') < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理
let valueName = re.getReg(t, tt.regs[1]);
let valueType = re.getReg(t, tt.regs[2]);
let index = valueType.indexOf('number');
while (index !== -1) {
valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease());
index = valueType.indexOf('number');
}
result.value.push({
name: valueName,
type: valueType
});
}
}
function checkAnalyzeType(body, result) {
for (let i in body) {
let t = body[i];
while (t.length > 0 && t[0] === ' ') { // 去除前面的空格
t = t.substring(1, t.length);
}
while (t.length > 0 && t[-1] === ' ') { // 去除后面的空格
t = t.substring(0, t.length - 1);
}
if (t === '') {
break; // 如果t为空直接返回
}
let tt = re.match(' *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t);
checkTT(tt, t, result);
}
}
/**type解析 */
function analyzeType(data, rsltInterface = null) { // same as class
let body = data
body = body.indexOf("//") < 0 ? body : parseNotes(body)
body = re.replaceAll(body, "\n", "").split(";")
let body = data;
body = body.indexOf('//') < 0 ? body : parseNotes(body);
body = re.replaceAll(body, '\n', '').split(';');
let result = {
value: [],
// function: []
}
for (let i in body) {
let t = body[i]
while (t.length > 0 && t[0] == ' ') // 去除前面的空格
t = t.substring(1, t.length)
while (t.length > 0 && t[-1] == ' ') // 去除后面的空格
t = t.substring(0, t.length - 1)
if (t == "") break // 如果t为空直接返回
let tt = re.match(" *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\]| ]+)", t)
if (tt && t.indexOf("=>") < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理
let valueName = re.getReg(t, tt.regs[1])
let valueType = re.getReg(t, tt.regs[2])
let index = valueType.indexOf("number")
while (index !== -1) {
valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
index = valueType.indexOf("number")
}
result.value.push({
name: valueName,
type: valueType
})
}
}
return result
};
checkAnalyzeType(body, result);
return result;
}
function analyzeType2(data) {
let body = re.replaceAll(data, " ", "").split("'|'")
let body = re.replaceAll(data, ' ', '').split("'|'")
let result = {
element: [],
function: [],
enumValueType: 0 // 0代表数字1代表字符串
}
};
for (let i in body) {
let bodyContent = body[i]
while (bodyContent.length > 0 && bodyContent[0] == ' ') {
bodyContent = bodyContent.substring(1, bodyContent.length)
let bodyContent = body[i];
while (bodyContent.length > 0 && bodyContent[0] === ' ') {
bodyContent = bodyContent.substring(1, bodyContent.length);
}
while (bodyContent.length > 0 && bodyContent[-1] == ' ') {
bodyContent = bodyContent.substring(0, bodyContent.length - 1)
while (bodyContent.length > 0 && bodyContent[-1] === ' ') {
bodyContent = bodyContent.substring(0, bodyContent.length - 1);
}
if (bodyContent == "") {
break
if (bodyContent === '') {
break;
}
analyzeType2Result(result, bodyContent, i)
}
return result
return result;
}
function analyzeType2Result(result, bodyContent, index) {
let regString = re.match(" *([a-zA-Z0-9_]+) *", bodyContent)
let regString = re.match(' *([a-zA-Z0-9_]+) *', bodyContent)
if (regString) {
let elementName = re.getReg(bodyContent, regString.regs[1])
elementName = 'NAME_' + elementName.toUpperCase()
@ -97,10 +109,10 @@ function analyzeType2Result(result, bodyContent, index) {
name: elementName,
value: elementValue,
type: 'string'
})
result.enumValueType = 1
});
result.enumValueType = 1;
}
return result
return result;
}
module.exports = {
@ -108,4 +120,4 @@ module.exports = {
analyzeType2,
analyzeType2Result,
parseNotes
}
};

View File

@ -31,27 +31,33 @@ let gypTemplete = `
}
`
/**创建nodejs编译文件用于在ubuntu测试 */
function generateGYP(destDir, implName, license) {
let ss = gypTemplete.replaceAll("[implName]", implName)
if (license) {
let s2 = license.substring(2, license.length - 2).split("\n");
license = "";
for (let i = 1; i < s2.length; i++) {
if (s2[i].length > 0) {
while (s2[i][0] == " ") s2[i] = s2[i].substring(1);
if (s2[i].length > 3 && s2[i][0] == "*") {
license += "#" + s2[i].substring(1) + "\n";
}
function checkGenGYP(s2, license) {
for (let i = 1; i < s2.length; i++) {
if (s2[i].length > 0) {
while (s2[i][0] === ' ') {
s2[i] = s2[i].substring(1);
}
if (s2[i].length > 3 && s2[i][0] === '*') {
license += '#' + s2[i].substring(1) + '\n';
}
}
}
writeFile(re.pathJoin(destDir, "binding.gyp"), null != license ? (license + "\n" + ss) : ss)
}
writeFile(re.pathJoin(destDir, "test.sh"), "node-gyp configure build && sleep 0.5 && node --expose-gc test.js")
/**创建nodejs编译文件用于在ubuntu测试 */
function generateGYP(destDir, implName, license) {
let ss = gypTemplete.replaceAll('[implName]', implName)
if (license) {
let s2 = license.substring(2, license.length - 2).split('\n');
license = '';
checkGenGYP(s2, license);
}
writeFile(re.pathJoin(destDir, 'binding.gyp'), null !== license ? (license + '\n' + ss) : ss)
writeFile(re.pathJoin(destDir, 'test.sh'), 'node-gyp configure build && sleep 0.5 && node --expose-gc test.js')
}
module.exports = {
generateGYP
}
};

View File

@ -47,25 +47,31 @@ ohos_shared_library("[implName]")
}
`
/**创建nodejs编译文件用于在ubuntu测试 */
function generateGN(destDir, implName, license, partName) {
let subsystemName = implName;
let gnFile = gnTemplete.replaceAll("[implName]", implName);
gnFile = gnFile.replaceAll("[subsystemName]", subsystemName);
gnFile = gnFile.replaceAll("[partName]", partName);
if (license) {
let s2 = license.substring(2, license.length - 2).split("\n");
license = "";
for (let i = 1; i < s2.length; i++) {
if (s2[i].length > 0) {
while (s2[i][0] == " ") s2[i] = s2[i].substring(1);
if (s2[i].length > 3 && s2[i][0] == "*") {
license += "#" + s2[i].substring(1) + "\n";
}
function checkGenerateGN(license) {
let s2 = license.substring(2, license.length - 2).split('\n');
license = '';
for (let i = 1; i < s2.length; i++) {
if (s2[i].length > 0) {
while (s2[i][0] === ' ') {
s2[i] = s2[i].substring(1);
}
if (s2[i].length > 3 && s2[i][0] === '*') {
license += '#' + s2[i].substring(1) + '\n';
}
}
}
writeFile(re.pathJoin(destDir, "BUILD.gn"), null != license ? (license + "\n" + gnFile) : gnFile)
}
/**创建nodejs编译文件用于在ubuntu测试 */
function generateGN(destDir, implName, license, partName) {
let subsystemName = implName;
let gnFile = gnTemplete.replaceAll('[implName]', implName);
gnFile = gnFile.replaceAll('[subsystemName]', subsystemName);
gnFile = gnFile.replaceAll('[partName]', partName);
if (license) {
checkGenerateGN(license);
}
writeFile(re.pathJoin(destDir, 'BUILD.gn'), null !== license ? (license + '\n' + gnFile) : gnFile);
}
module.exports = {

View File

@ -43,39 +43,41 @@ public:
};`
function getHDefineOfVariable(name, type, variable) {
if (type.indexOf("|") >= 0) {
if (type.indexOf('|') >= 0) {
unionTypeString(name, type, variable)
} else if (type == "string") variable.hDefine += "\n std::string %s;".format(name)
else if (InterfaceList.getValue(type)) variable.hDefine += "\n %s %s;".format(type, name)
else if (EnumList.getValue(type)) variable.hDefine += "\n %s %s;".format(type, name)
else if (type.indexOf("Array<") == 0) {
let arrayType = getArrayType(type)
if (arrayType == "any") {
variable.hDefine += "\n std::string %s_type; \n std::any %s;".format(name,name)
} else if (type == 'string') {
variable.hDefine += '\n std::string %s;'.format(name);
} else if (InterfaceList.getValue(type)) {
variable.hDefine += '\n %s %s;'.format(type, name);
} else if (EnumList.getValue(type)) {
variable.hDefine += '\n %s %s;'.format(type, name);
} else if (type.indexOf('Array<') == 0) {
let arrayType = getArrayType(type);
if (arrayType == 'any') {
variable.hDefine += '\n std::string %s_type; \n std::any %s;'.format(name,name);
} else {
let cType = jsType2CType(arrayType)
variable.hDefine += "\n std::vector<%s> %s;".format(cType, name)
let cType = jsType2CType(arrayType);
variable.hDefine += '\n std::vector<%s> %s;'.format(cType, name);
}
} else if (type == "boolean") {
variable.hDefine += "\n bool %s;".format(name)
} else if (type.substring(type.length - 2) == "[]") {
let arrayType = getArrayTypeTwo(type)
if (arrayType == "any") {
variable.hDefine += "\n std::string %s_type;\n std::any %s;".format(name,name)
} else if (type == 'boolean') {
variable.hDefine += '\n bool %s;'.format(name);
} else if (type.substring(type.length - 2) == '[]') {
let arrayType = getArrayTypeTwo(type);
if (arrayType == 'any') {
variable.hDefine += '\n std::string %s_type;\n std::any %s;'.format(name,name);
} else {
let cType = jsType2CType(arrayType)
variable.hDefine += "\n std::vector<%s> %s;".format(cType, name)
let cType = jsType2CType(arrayType);
variable.hDefine += '\n std::vector<%s> %s;'.format(cType, name);
}
} else if (type.substring(0, 4) == "Map<" || type.indexOf("{[key:") == 0) {
variable.hDefine += mapTypeString(type, name)
} else if (type == "any") {
variable.hDefine += anyTypeString(type, name)
} else if (type.substring(0, 12) == "NUMBER_TYPE_") {
variable.hDefine += "\n %s %s;".format(type, name)
} else if (type == "Object" || type == "object") {
variable.hDefine += "\n std::map<std::string, std::any> %s;".format(name)
}
else {
} else if (type.substring(0, 4) == 'Map<' || type.indexOf('{[key:') == 0) {
variable.hDefine += mapTypeString(type, name);
} else if (type == 'any') {
variable.hDefine += anyTypeString(type, name);
} else if (type.substring(0, 12) == 'NUMBER_TYPE_') {
variable.hDefine += '\n %s %s;'.format(type, name);
} else if (type == 'Object' || type == 'object') {
variable.hDefine += '\n std::map<std::string, std::any> %s;'.format(name);
} else {
NapiLog.logError(`
---- generateVariable fail %s,%s ----
`.format(name, type));
@ -83,11 +85,11 @@ function getHDefineOfVariable(name, type, variable) {
}
function generateVariable(value, variable, className) {
let name = value.name
let type = value.type
let name = value.name;
let type = value.type;
if (!value.isParentMember) {
// 只有类/接口自己的成员属性需要在.h中定义 父类/父接口不需要
getHDefineOfVariable(name, type, variable)
getHDefineOfVariable(name, type, variable);
}
variable.middleValue += `
@ -97,7 +99,7 @@ function generateVariable(value, variable, className) {
void *instPtr = pxt->UnWarpInstance();
%s *p = static_cast<%s *>(instPtr);
napi_value result = nullptr;
`.format(name, className, className) + cToJs("p->" + name, type, "result") + `
`.format(name, className, className) + cToJs('p->' + name, type, 'result') + `
delete pxt;
return result;
}
@ -106,105 +108,129 @@ function generateVariable(value, variable, className) {
std::shared_ptr<XNapiTool> pxt = std::make_shared<XNapiTool>(env, info);
void *instPtr = pxt->UnWarpInstance();
%s *p = static_cast<%s *>(instPtr);
`.format(name, className, className) + jsToC("p->" + name, "pxt->GetArgv(XNapiTool::ZERO)", type) + `
`.format(name, className, className) + jsToC('p->' + name, 'pxt->GetArgv(XNapiTool::ZERO)', type) + `
return nullptr;
}`
}
function unionTypeString(name, type, variable) {
variable.hDefine += `std::string %s_type;\n
std::any %s;`.format(name, name)
std::any %s;`.format(name, name);
}
function checkMapType1(mapType, mapTypeString, name) {
if (mapType[1] !== undefined && mapType[2] === undefined) {
if (mapType[1] === 'string') {
mapTypeString = 'std::string, std::string';
} else if (mapType[1] === 'boolean') {
mapTypeString = 'std::string, bool';
} else if (mapType[1].substring(0, 12) === 'NUMBER_TYPE_') {
mapTypeString = 'std::string, %s'.format(mapType[1]);
} else if (mapType[1].substring(0, 12) === 'any') {
mapTypeString = `std::string, std::any`.format(mapType[1]);
return `\n std::map<%s> %s;
std::string %s_type;`.format(mapTypeString, name, name);
} else if (InterfaceList.getValue(mapType[1])) {
mapTypeString = 'std::string, %s'.format(mapType[1]);
}
}
return null;
}
function checkMapType2(mapType, mapTypeString) {
if (mapType[2] !== undefined) {
if (mapType[2] === 'string') {
mapTypeString = 'std::string, std::map<std::string, std::string>';
} else if (mapType[2] === 'boolean') {
mapTypeString = 'std::string, std::map<std::string, bool>';
} else if (mapType[2].substring(0, 12) === 'NUMBER_TYPE_') {
mapTypeString = 'std::string, std::map<std::string, %s>'.format(mapType[2]);
}
}
}
function checkMapType3(mapType, mapTypeString) {
if (mapType[3] !== undefined) {
if (mapType[3] === 'string') {
mapTypeString = 'std::string, std::vector<std::string>';
} else if (mapType[3] === 'boolean') {
mapTypeString = 'std::string, std::vector<bool>';
} else if (mapType[3].substring(0, 12) === 'NUMBER_TYPE_') {
mapTypeString = 'std::string, std::vector<%s>'.format(mapType[3]);
}
}
}
function mapTypeString(type, name) {
let mapType = getMapType(type)
let mapTypeString
if (mapType[1] != undefined && mapType[2] == undefined) {
if (mapType[1] == "string") mapTypeString = "std::string, std::string"
else if (mapType[1] == "boolean") mapTypeString = "std::string, bool"
else if (mapType[1].substring(0, 12) == "NUMBER_TYPE_") {
mapTypeString = "std::string, %s".format(mapType[1])
}
else if (mapType[1].substring(0, 12) == "any") {
mapTypeString = `std::string, std::any`.format(mapType[1])
return `\n std::map<%s> %s;
std::string %s_type;`.format(mapTypeString, name, name)
}
else if (InterfaceList.getValue(mapType[1])) mapTypeString = "std::string, %s".format(mapType[1])
let mapType = getMapType(type);
let mapTypeString;
let retstr = checkMapType1(mapType, mapTypeString, name);
if (retstr) {
return retstr;
}
if (mapType[2] != undefined) {
if (mapType[2] == "string") mapTypeString = "std::string, std::map<std::string, std::string>"
else if (mapType[2] == "boolean") mapTypeString = "std::string, std::map<std::string, bool>"
else if (mapType[2].substring(0, 12) == "NUMBER_TYPE_") {
mapTypeString = "std::string, std::map<std::string, %s>".format(mapType[2])
}
}
if (mapType[3] != undefined) {
if (mapType[3] == "string") mapTypeString = "std::string, std::vector<std::string>"
else if (mapType[3] == "boolean") mapTypeString = "std::string, std::vector<bool>"
else if (mapType[3].substring(0, 12) == "NUMBER_TYPE_") {
mapTypeString = "std::string, std::vector<%s>".format(mapType[3])
}
}
return "\n std::map<%s> %s;".format(mapTypeString, name);
checkMapType2(mapType, mapTypeString);
checkMapType3(mapType, mapTypeString);
return '\n std::map<%s> %s;'.format(mapTypeString, name);
}
function anyTypeString (type, name) {
function anyTypeString(type, name) {
let anyType = `\n std::string %s_type;
std::any %s;`
std::any %s;`;
return anyType.format(name, name)
return anyType.format(name, name);
}
function generateInterface(name, data, inNamespace) {
let resultConnect = connectResult(data, inNamespace, name)
let middleFunc = resultConnect[0]
let implH = resultConnect[1]
let implCpp = resultConnect[2]
let middleInit = resultConnect[3]
let selfNs = ""
let resultConnect = connectResult(data, inNamespace, name);
let middleFunc = resultConnect[0];
let implH = resultConnect[1];
let implCpp = resultConnect[2];
let middleInit = resultConnect[3];
let selfNs = '';
if (inNamespace.length > 0) {
let nsl = inNamespace.split("::")
nsl.pop()
let nsl = inNamespace.split('::');
nsl.pop();
if (nsl.length >= 2) {
selfNs = ", " + nsl[nsl.length - 1]
selfNs = ', ' + nsl[nsl.length - 1];
}
}
middleInit += `\n pxt->DefineClass("%s", %s%s_middle::constructor,
middleInit += `\n pxt->DefineClass('%s', %s%s_middle::constructor,
valueList, funcList%s);\n}\n`
.format(name, inNamespace, name, selfNs)
.format(name, inNamespace, name, selfNs);
let extendsStr = (data.parentNameList && data.parentNameList.length > 0) ?
" : public %s".format(data.parentNameList.join(", public ")) : ""
' : public %s'.format(data.parentNameList.join(', public ')) : '';
let result = {
implH: `
class %s%s {
public:%s
};\n`.format(name, extendsStr, implH),
class %s%s {
public:%s
};\n`.format(name, extendsStr, implH),
implCpp: implCpp,
middleBody: middleBodyTmplete.replaceAll("[className]", name).replaceAll("[static_funcs]", middleFunc),
middleBody: middleBodyTmplete.replaceAll('[className]', name).replaceAll('[static_funcs]', middleFunc),
middleInit: middleInit
}
return result
};
return result;
}
// 递归获取接口及接口父类的所有成员属性和方法
function getAllPropties(interfaceBody, properties, isParentClass) {
for (let i in interfaceBody.value) {
interfaceBody.value[i].isParentMember = isParentClass
addUniqObj2List(interfaceBody.value[i], properties.values)
interfaceBody.value[i].isParentMember = isParentClass;
addUniqObj2List(interfaceBody.value[i], properties.values);
}
for (let i in interfaceBody.function) {
interfaceBody.function[i].isParentMember = isParentClass
interfaceBody.function[i].isParentMember = isParentClass;
if(!addUniqFunc2List(interfaceBody.function[i], properties.functions)) {
if (isParentClass) {
// 没添加到列表说明子类方法properties.functions重写了父类方法interfaceBody.function[i]
// 找到该子类方法并将其设置为override (生成的重写函数如果没有override关键字会触发门禁告警)
setOverrideFunc(interfaceBody.function[i], properties.functions)
setOverrideFunc(interfaceBody.function[i], properties.functions);
}
}
}
if (!isParentClass && interfaceBody.parentNameList && interfaceBody.parentNameList.length > 0) {
getAllPropties(interfaceBody.parentBody, properties, true)
getAllPropties(interfaceBody.parentBody, properties, true);
}
}
@ -212,61 +238,61 @@ function addVirtualKeywords(data, implH, name) {
if (data.childList && data.childList.length > 0) {
// 如果该类是其它类的父类,增加虚析构函数使其具备泛型特征 (基类必须有虚函数才能正确使用dynamic_cast和typeinfo等方法)
// 如果该类自己也有父类虚析构函数需要加上override关键字(否则C++门禁会有告警)
let ovrrideStr = (data.parentList && data.parentList.length > 0) ? " override" : "";
let ovrrideStr = (data.parentList && data.parentList.length > 0) ? ' override' : '';
// 如果虚析构函数已经有override关键字就不需要再加virtual关键字了(否则C++门禁会有告警)
let virtualStr = (data.parentList && data.parentList.length > 0) ? "" : "virtual ";
implH += "\n %s~%s()%s {};".format(virtualStr, name, ovrrideStr);
let virtualStr = (data.parentList && data.parentList.length > 0) ? '' : 'virtual ';
implH += '\n %s~%s()%s {};'.format(virtualStr, name, ovrrideStr);
}
return implH;
}
function connectResult(data, inNamespace, name) {
let implH = ""
let implCpp = ""
let middleFunc = ""
let middleInit = ""
let implH = '';
let implCpp = '';
let middleFunc = '';
let middleInit = '';
let variable = {
hDefine: "",
middleValue: "",
}
middleInit = `{\n std::map<const char *, std::map<const char *, napi_callback>> valueList;`
data.allProperties = {values:[], functions:[]}
getAllPropties(data, data.allProperties, false)
hDefine: '',
middleValue: '',
};
middleInit = `{\n std::map<const char *, std::map<const char *, napi_callback>> valueList;`;
data.allProperties = {values:[], functions:[]};
getAllPropties(data, data.allProperties, false);
for (let i in data.allProperties.values) {
let v = data.allProperties.values[i]
generateVariable(v, variable, name)
let v = data.allProperties.values[i];
generateVariable(v, variable, name);
middleInit += `
valueList["%s"]["getvalue"] = %s%s_middle::getvalue_%s;
valueList["%s"]["setvalue"] = %s%s_middle::setvalue_%s;`
.format(v.name, inNamespace, name, v.name, v.name, inNamespace, name, v.name)
.format(v.name, inNamespace, name, v.name, v.name, inNamespace, name, v.name);
}
implH += variable.hDefine
middleFunc += variable.middleValue
middleInit += `\n std::map<const char *, napi_callback> funcList;`
implH += variable.hDefine;
middleFunc += variable.middleValue;
middleInit += `\n std::map<const char *, napi_callback> funcList;`;
for (let i in data.allProperties.functions) {
let func = data.allProperties.functions[i]
let func = data.allProperties.functions[i];
let tmp;
switch (func.type) {
case FuncType.DIRECT:
tmp = generateFunctionDirect(func, data, name)
tmp = generateFunctionDirect(func, data, name);
break;
case FuncType.SYNC:
tmp = generateFunctionSync(func, data, name)
break
tmp = generateFunctionSync(func, data, name);
break;
case FuncType.ASYNC:
case FuncType.PROMISE:
tmp = generateFunctionAsync(func, data, name)
break
tmp = generateFunctionAsync(func, data, name);
break;
default:
return
return [];
}
middleFunc += tmp[0]
implH += tmp[1]
implCpp += tmp[2]
middleInit += `\n funcList["%s"] = %s%s_middle::%s_middle;`.format(func.name, inNamespace, name, func.name)
middleFunc += tmp[0];
implH += tmp[1];
implCpp += tmp[2];
middleInit += `\n funcList["%s"] = %s%s_middle::%s_middle;`.format(func.name, inNamespace, name, func.name);
}
implH = addVirtualKeywords(data, implH, name);
return [middleFunc, implH, implCpp, middleInit]
return [middleFunc, implH, implCpp, middleInit];
}
module.exports = {
@ -274,6 +300,4 @@ module.exports = {
connectResult,
generateVariable,
mapTypeString
}
};

File diff suppressed because it is too large Load Diff

View File

@ -28,7 +28,7 @@ const specialPrefixArr = ["p->", "vio->out."];
*/
function delPrefix(valueName) {
for ( var i in specialPrefixArr) {
if (valueName.indexOf(specialPrefixArr[i]) == 0) {
if (valueName.indexOf(specialPrefixArr[i]) === 0) {
// Find special prefix and delete it.
return valueName.substring(specialPrefixArr[i].length, valueName.length);
}
@ -41,7 +41,7 @@ function cToJsForType(value, type, dest, deep) {
let lt = deep
let result = ""
let ifl = TypeList.getValue(type)
if (typeof(ifl) == 'object') {
if (typeof(ifl) === 'object') {
for (let i in ifl) {
let name2 = ifl[i].name
let type2 = ifl[i].type
@ -90,44 +90,37 @@ function cToJs(value, type, dest, deep = 1) {
var propertyName = delPrefix(value);
if (type.indexOf("|") >= 0) {
return unionTempleteFunc(value, type, dest);
} else if (type == "void")
} else if (type === "void") {
return "%s = pxt->UndefinedValue();".format(dest);
else if (type == "boolean")
} else if (type === "boolean") {
return "%s = pxt->SwapC2JsBool(%s);".format(dest, value.replace("[replace]", deep - 2));
else if (type == "string")
} else if (type === "string") {
return `%s = pxt->SwapC2JsUtf8(%s.c_str());`.format(dest, value.replace("[replace]", deep - 2))
else if (InterfaceList.getValue(type)) {
} else if (InterfaceList.getValue(type)) {
return cToJsForInterface(value, type, dest, deep);
}
else if (TypeList.getValue(type)) {
} else if (TypeList.getValue(type)) {
return cToJsForType(value, type, dest, deep);
}
else if(EnumList.getValue(type)){
} else if (EnumList.getValue(type)) {
let lt = deep
let result = ""
let ifl = EnumList.getValue(type)
let type2 = ifl[0].type
let enumCtoJsStr = cToJs("enumInt%d".format(lt), type2, "tnv%d".format(lt), deep + 1)
let enumCtoJsStr = cToJs("enumInt%d".format(lt), type2, "tnv%d".format(lt), deep + 1);
result += "{\nnapi_value tnv%d = nullptr;\n".format(lt) + "int enumInt%d = (int)%s;\n".format(lt, value) +
enumCtoJsStr + `\npxt->SetValueProperty(%s, "%s", tnv%d);\n}\n`
.format(dest, propertyName, lt)
return result
}
else if (type.substring(0, 6) == "Array<" || type.substring(type.length - 2) == "[]") {
let arrayType = checkArrayParamType(type)
return arrayTempleteFunc(arrayType, deep, dest, value)
}
else if (type.substring(0, 4) == "Map<" || type.indexOf("{[key:") == 0) {
return mapTempleteFunc(type, deep, dest, value)
}
else if (type.substring(0, 12) == "NUMBER_TYPE_") {
return `%s = NUMBER_C_2_JS(pxt, %s);`.format(dest, value.replace("[replace]", deep - 2))
}
else if (type == "any") {
return anyTempleteFunc(value)
}
else if (type == "Object" || type == "object") {
return objectTempleteFuncReturn(value)
enumCtoJsStr + `\npxt->SetValueProperty(%s, "%s", tnv%d);\n}\n`;
.format(dest, propertyName, lt);
return result;
} else if (type.substring(0, 6) === 'Array<' || type.substring(type.length - 2) === '[]') {
let arrayType = checkArrayParamType(type);
return arrayTempleteFunc(arrayType, deep, dest, value);
} else if (type.substring(0, 4) === 'Map<' || type.indexOf('{[key:') === 0) {
return mapTempleteFunc(type, deep, dest, value);
} else if (type.substring(0, 12) === 'NUMBER_TYPE_') {
return `%s = NUMBER_C_2_JS(pxt, %s);`.format(dest, value.replace("[replace]", deep - 2));
} else if (type === 'any') {
return anyTempleteFunc(value);
} else if (type === 'Object' || type === 'object') {
return objectTempleteFuncReturn(value);
}
else {
NapiLog.logError(`\n---- This type do not generate cToJs %s,%s,%s ----\n`.format(value, type, dest));
@ -144,20 +137,20 @@ function unionTempleteFunc(value, type, dest){
let unionType = getUnionType(type)
let unionTypeString = ''
for (let i = 0; i < unionType.length; i++) {
if (unionType[i] == "string") {
unionTypeString += `if (%s_type == "string") {
if (unionType[i] === "string") {
unionTypeString += `if (%s_type === "string") {
%s
%s
}\n`.format(value, "std::string union_string = std::any_cast<std::string>("+value+");",
cToJs("union_string", unionType[i], dest))
} else if (unionType[i].substring(0, 12) == "NUMBER_TYPE_") {
unionTypeString += `if (%s_type == "number") {
} else if (unionType[i].substring(0, 12) === "NUMBER_TYPE_") {
unionTypeString += `if (%s_type === "number") {
%s
%s
}\n`.format(value, "std::uint32_t union_number = std::any_cast<std::uint32_t>("+value+");",
cToJs("union_number", unionType[i], dest))
} else if (unionType[i] == "boolean") {
unionTypeString += `if (%s_type == "boolean") {
} else if (unionType[i] === "boolean") {
unionTypeString += `if (%s_type === "boolean") {
%s
%s
}\n`.format(value, "bool union_boolean = std::any_cast<bool>("+value+");",
@ -189,19 +182,19 @@ function arrayTempleteFunc(arrayType, deep, dest, value) {
pxt->SetArrayElement(%s, i%d, tnv%d);
}`.format(tnv, lt, value.replace("[replace]",lt -2), lt, lt, lt, lt, lt, tnv, lt, lt)
let ret = ""
if (arrayType.substring(0, 12) == "NUMBER_TYPE_") {
if (arrayType.substring(0, 12) === "NUMBER_TYPE_") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = NUMBER_C_2_JS(pxt, %s[i%d]);`
.format(lt, value.replace("[replace]",lt), lt))
}
else if (arrayType == "string") {
else if (arrayType === "string") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = pxt->SwapC2JsUtf8(%s[i%d].c_str());`
.format(lt, value.replace("[replace]",lt), lt))
}
else if (arrayType == "boolean") {
else if (arrayType === "boolean") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = pxt->SwapC2JsBool(%s[i%d]);`
.format(lt, value.replace("[replace]",lt), lt))
}
else if (arrayType == "any") {
else if (arrayType === "any") {
return anyArrayTempleteFuncReturn(value.replace("[replace]",lt))
}
else if (InterfaceList.getValue(arrayType)) {
@ -215,20 +208,20 @@ function mapTempleteFunc(type, deep, dest, value) {
let lt = deep
let tnv = dest
let tnvdef = `result = nullptr;
for (auto i = %s.begin(); i != %s.end(); i++) {
for (auto i = %s.begin(); i !== %s.end(); i++) {
const char * tnv%d;
napi_value tnv%d = nullptr;
[calc_out]
pxt->SetMapElement(%s, tnv%d, tnv%d);
}`.format(value, value, lt, lt + 1, tnv, lt, lt + 1)
let ret = ""
if (mapType[1] != undefined && mapType[2] == undefined) {
if (mapType[1] !== undefined && mapType[2] === undefined) {
ret = mapTempleteValue(mapType, tnvdef, lt, value, tnv)
}
else if (mapType[2] != undefined) {
else if (mapType[2] !== undefined) {
ret = mapTempleteMap(mapType, tnvdef, lt)
}
else if (mapType[3] != undefined) {
else if (mapType[3] !== undefined) {
ret = mapTempleteArray(mapType, tnvdef, lt)
}
return ret
@ -251,7 +244,7 @@ function anyArrayTempleteFuncReturn(value) {
function mapInterface(value, lt, tnv, mapType) {
let ret
let tnvdefInterface = `result = nullptr;
for (auto i = %s.begin(); i != %s.end(); i++) {
for (auto i = %s.begin(); i !== %s.end(); i++) {
const char *tnv%d;
[calc_out]
}`.format(value, value, lt, lt + 1, tnv, lt, lt + 1)
@ -260,7 +253,7 @@ function mapInterface(value, lt, tnv, mapType) {
let interfaceVar = ""
let interfaceFun = ""
for (let i = 0; i < interfaceValue.length; i++) {
if (interfaceValue[i].type == 'string') {
if (interfaceValue[i].type === 'string') {
interfaceVarName += `const char *tnv_%s_name;
napi_value tnv_%s = nullptr;\n`.format(interfaceValue[i].name, interfaceValue[i].name)
interfaceVar += `tnv_%s_name = "%s";
@ -269,7 +262,7 @@ function mapInterface(value, lt, tnv, mapType) {
interfaceFun += `pxt->SetMapElement(result_obj, tnv_%s_name, tnv_%s);\n`
.format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name)
}
else if (interfaceValue[i].type.substring(0, 12) == "NUMBER_TYPE_") {
else if (interfaceValue[i].type.substring(0, 12) === "NUMBER_TYPE_") {
interfaceVarName += `const char *tnv_%s_name;
napi_value tnv_%s = nullptr;\n`.format(interfaceValue[i].name, interfaceValue[i].name)
interfaceVar += `tnv_%s_name = "%s";
@ -300,16 +293,16 @@ function mapInterface(value, lt, tnv, mapType) {
function mapTempleteValue(mapType, tnvdef, lt, value, tnv) {
let ret
if (mapType[1] == "string") {
if (mapType[1] === "string") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str();
tnv%d = pxt->SwapC2JsUtf8(i->second.c_str());`.format(lt, lt + 1))
} else if (mapType[1] == "boolean") {
} else if (mapType[1] === "boolean") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str();
tnv%d = pxt->SwapC2JsBool(i->second);`.format(lt, lt + 1))
} else if (mapType[1].substring(0, 12) == "NUMBER_TYPE_") {
} else if (mapType[1].substring(0, 12) === "NUMBER_TYPE_") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str();
tnv%d = NUMBER_C_2_JS(pxt, i->second);`.format(lt, lt + 1))
} else if (mapType[1] == "any") {
} else if (mapType[1] === "any") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str();
pxt->GetAnyValue(%s_type, tnv%d, i->second);`.format(lt, value, lt + 1))
}
@ -323,9 +316,9 @@ function mapTempleteValue(mapType, tnvdef, lt, value, tnv) {
function mapTempleteMap(mapType, tnvdef, lt) {
let ret
if (mapType[2] == "string") {
if (mapType[2] === "string") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = i->first.c_str();
for (auto j = i->second.begin(); j != i->second.end(); j++) {
for (auto j = i->second.begin(); j !== i->second.end(); j++) {
const char *tt%d;
napi_value tt%d;
tt%d = j->first.c_str();
@ -335,7 +328,7 @@ function mapTempleteMap(mapType, tnvdef, lt) {
}
else if (mapType[2] === "boolean") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = i->first.c_str();
for (auto j = i->second.begin(); j != i->second.end(); j++) {
for (auto j = i->second.begin(); j !== i->second.end(); j++) {
const char *tt%d;
napi_value tt%d;
tt%d = j->first.c_str();
@ -345,7 +338,7 @@ function mapTempleteMap(mapType, tnvdef, lt) {
}
if (mapType[2].substring(0, 12) === "NUMBER_TYPE_") {
ret = tnvdef.replaceAll("[calc_out]", `tnv%d = i->first.c_str();
for (auto j = i->second.begin(); j != i->second.end(); j++) {
for (auto j = i->second.begin(); j !== i->second.end(); j++) {
const char *tt%d;
napi_value tt%d;
tt%d = j->first.c_str();
@ -393,28 +386,26 @@ function returnGenerateMap(returnInfo, param) {
let type = returnInfo.type
let mapType = getMapType(type)
let mapTypeString
if (mapType[1] != undefined && mapType[2] == undefined) {
if (mapType[1] == "string") { mapTypeString = "std::string" }
else if (mapType[1].substring(0, 12) == "NUMBER_TYPE_") { mapTypeString = mapType[1] }
else if (mapType[1] == "boolean") { mapTypeString = "bool" }
else if (mapType[1] == "any") { mapTypeString = "std::any" }
if (mapType[1] !== undefined && mapType[2] === undefined) {
if (mapType[1] === "string") { mapTypeString = "std::string" }
else if (mapType[1].substring(0, 12) === "NUMBER_TYPE_") { mapTypeString = mapType[1] }
else if (mapType[1] === "boolean") { mapTypeString = "bool" }
else if (mapType[1] === "any") { mapTypeString = "std::any" }
else { mapTypeString = mapType[1] }
}
else if (mapType[2] != undefined) {
if (mapType[2] == "string") { mapTypeString = "std::map<std::string, std::string>" }
else if (mapType[2].substring(0, 12) == "NUMBER_TYPE_") { "std::map<std::string, "+mapType[2]+">" }
else if (mapType[2] == "boolean") { mapTypeString = "std::map<std::string, bool>" }
}
else if (mapType[3] != undefined) {
if (mapType[3] == "string") { mapTypeString = "std::vector<std::string>" }
else if (mapType[3].substring(0, 12) == "NUMBER_TYPE_") { mapTypeString = "std::vector<"+mapType[3]+">" }
else if (mapType[3] == "boolean") { mapTypeString = "std::vector<bool>" }
} else if (mapType[2] !== undefined) {
if (mapType[2] === "string") { mapTypeString = "std::map<std::string, std::string>" }
else if (mapType[2].substring(0, 12) === "NUMBER_TYPE_") { "std::map<std::string, "+mapType[2]+">" }
else if (mapType[2] === "boolean") { mapTypeString = "std::map<std::string, bool>" }
} else if (mapType[3] !== undefined) {
if (mapType[3] === "string") { mapTypeString = "std::vector<std::string>" }
else if (mapType[3].substring(0, 12) === "NUMBER_TYPE_") { mapTypeString = "std::vector<"+mapType[3]+">" }
else if (mapType[3] === "boolean") { mapTypeString = "std::vector<bool>" }
}
let modifiers = returnInfo.optional ? "*" : "&"
param.valueOut = returnInfo.optional ? "std::map<std::string, %s>* out = nullptr;".format(mapTypeString)
: "std::map<std::string, %s> out;".format(mapTypeString)
param.valueDefine += "%sstd::map<std::string, %s>%s out"
.format(param.valueDefine.length > 0 ? ", " : "", mapTypeString, modifiers)
param.valueDefine += "%sstd::map<std::string, %s>%s out"
.format(param.valueDefine.length > 0 ? ", " : "", mapTypeString, modifiers)
}
function returnGenerateUnion (param) {
@ -456,55 +447,52 @@ function getReturnFill(returnInfo, param) {
}
function isObjectType(type) {
if(type == "Object" || type == "object") {
if(type === "Object" || type === "object") {
return true;
}
return false;
}
function checkReturnGenerate(type, param, returnInfo, data) {
if (type === "string") {
param.valueOut = returnInfo.optional ? "std::string* out = nullptr;" : "std::string out;"
param.valueDefine += "%sstd::string%s out".format(param.valueDefine.length > 0 ? ", " : "", modifiers)
} else if (type === "void") {
NapiLog.logInfo("The current void type don't need generate");
} else if (type === "boolean") {
param.valueOut = returnInfo.optional ? "bool* out = nullptr;" : "bool out;";
param.valueDefine += "%sbool%s out".format(param.valueDefine.length > 0 ? ", " : "", modifiers);
} else if (isEnum(type, data)) {
returnGenerateEnum(data, returnInfo, param);
} else if (generateType(type)){
returnGenerate2(returnInfo, param, data);
} else if (type.substring(0, 12) === "NUMBER_TYPE_") {
param.valueOut = type + (returnInfo.optional ? "* out = nullptr;" : " out;");
param.valueDefine += "%s%s%s out".format(param.valueDefine.length > 0 ? ", " : "", type, modifiers);
} else if (isObjectType(type)) {
returnGenerateObject(returnInfo, param, data);
} else {
NapiLog.logError("Do not support returning the type [%s].".format(type));
}
}
function returnGenerate(returnInfo, param, data) {
let type = returnInfo.type
let valueFillStr = getReturnFill(returnInfo, param)
let valueFillStr = getReturnFill(returnInfo, param);
param.valueFill += ("%s" + valueFillStr).format(param.valueFill.length > 0 ? ", " : "")
let outParam = returnInfo.optional ? "(*vio->out)" : "vio->out"
let modifiers = returnInfo.optional ? "*" : "&"
let outParam = returnInfo.optional ? "(*vio->out)" : "vio->out";
let modifiers = returnInfo.optional ? "*" : "&";
if (returnInfo.optional) {
param.optionalParamDestory += "C_DELETE(vio->out);\n "
param.optionalParamDestory += "C_DELETE(vio->out);\n ";
}
if (!isEnum(type, data)) {
param.valuePackage = cToJs(outParam, type, "result")
param.valuePackage = cToJs(outParam, type, "result");
} else if (type.indexOf("|") >= 0) {
returnGenerateUnion(param)
}
if (type === "string") {
param.valueOut = returnInfo.optional ? "std::string* out = nullptr;" : "std::string out;"
param.valueDefine += "%sstd::string%s out".format(param.valueDefine.length > 0 ? ", " : "", modifiers)
}
else if (type === "void") {
NapiLog.logInfo("The current void type don't need generate");
}
else if (type === "boolean") {
param.valueOut = returnInfo.optional ? "bool* out = nullptr;" : "bool out;"
param.valueDefine += "%sbool%s out".format(param.valueDefine.length > 0 ? ", " : "", modifiers)
}
else if (isEnum(type, data)) {
returnGenerateEnum(data, returnInfo, param)
}
else if(generateType(type)){
returnGenerate2(returnInfo, param, data)
}
else if (type.substring(0, 12) === "NUMBER_TYPE_") {
param.valueOut = type + (returnInfo.optional ? "* out = nullptr;" : " out;")
param.valueDefine += "%s%s%s out".format(param.valueDefine.length > 0 ? ", " : "", type, modifiers)
}
else if (isObjectType(type)) {
returnGenerateObject(returnInfo, param, data)
}
else {
NapiLog.logError("Do not support returning the type [%s].".format(type));
}
checkReturnGenerate(type, param, returnInfo, data);
}
function generateType(type){
@ -531,7 +519,7 @@ function generateType(type){
}
}
function isMapType(type) {
if(type.substring(0, 4) === "Map<" || type.indexOf("{[key:") === 0) {
if (type.substring(0, 4) === "Map<" || type.indexOf("{[key:") === 0) {
return true;
}
return false;

View File

@ -119,9 +119,12 @@ function unionTypeString(name, type, variable) {
std::any %s;`.format(name, name)
}
function mapTypeString(type, name) {
let mapType = getMapType(type)
let mapTypeString
function unionTypeString(name, type, variable) {
variable.hDefine += `std::string ${name}_type;\n
std ${name};`;
}
function checkMapType1(mapType, mapTypeString) {
if (mapType[1] != undefined && mapType[2] == undefined) {
if (mapType[1] == "string") mapTypeString = "std::string, std::string"
else if (mapType[1] == "boolean") mapTypeString = "std::string, bool"
@ -135,6 +138,9 @@ function mapTypeString(type, name) {
}
else if (TypeList.getValue(mapType[1])) mapTypeString = "std::string, %s".format(mapType[1])
}
}
function checkMapType2(mapType, mapTypeString) {
if (mapType[2] != undefined) {
if (mapType[2] == "string") mapTypeString = "std::string, std::map<std::string, std::string>"
else if (mapType[2] == "boolean") mapTypeString = "std::string, std::map<std::string, bool>"
@ -142,6 +148,9 @@ function mapTypeString(type, name) {
mapTypeString = "std::string, std::map<std::string, %s>".format(mapType[2])
}
}
}
function checkMapType3(mapType, mapTypeString) {
if (mapType[3] != undefined) {
if (mapType[3] == "string") mapTypeString = "std::string, std::vector<std::string>"
else if (mapType[3] == "boolean") mapTypeString = "std::string, std::vector<bool>"
@ -149,6 +158,16 @@ function mapTypeString(type, name) {
mapTypeString = "std::string, std::vector<%s>".format(mapType[3])
}
}
}
function mapTypeString(type, name) {
let mapType = getMapType(type)
let mapTypeString
checkMapType1(mapType, mapTypeString)
checkMapType2(mapType, mapTypeString)
checkMapType3(mapType, mapTypeString)
return "\n std::map<%s> %s;".format(mapTypeString, name);
}

View File

@ -45,22 +45,4 @@ describe('array_map', function () {
let ret = fun10([{"age":true}, {"name":false}]);
assert.strictEqual(ret, 0);
});
/*
it('test fun7', function () {
let ret = fun7([{"key":'{"code":0,"data":"code0"}'}, {"name":'{"code":1,"data":"code1"}'}]);
assert.strictEqual(ret, 0);
});
*/
/*it('test fun12', function () {
let ret = fun12([{"key1":'code1'}, {"key2":'code2'}]);
assert.strictEqual(ret, 0);
});
it('test fun10', function () {
let ret = fun12([{"key1":'{"code":0,"data":"code0"}'}, {"key2":'{"code":1,"data":"code1"}'}]);
assert.strictEqual(ret, 0);
});
*/
});

View File

@ -37,24 +37,19 @@ describe('interface_no_name', function () {
assert.strictEqual(ret, '');
});
it('test interface_no_name fun2', function () {
let ret = fun2(fp2);
//assert.strictEqual(ret, '');
fun2(fp2);
});
it('test interface_no_name fun3', function () {
let ret = fun3("fun3p1", {nm:"abc",age:20});
//assert.strictEqual(ret, '');
fun3("fun3p1", {nm:"abc",age:20});
});
it('test interface_no_name fun4', function () {
let ret = fun4("name");
//assert.strictEqual(ret.read, 0);
fun4("name");
});
it('test interface_no_name fun5', function () {
fun5(value);
//let ret = fun5(value);
//assert.strictEqual(ret, void);
});
it('test interface_no_name fun6', function () {
fun6("name", value);

View File

@ -53,22 +53,22 @@ describe('Extend', function () {
partGenerateBase();
});
function partGenerateBase(){
function checkUnlink(filepath) {
fs.unlink(filepath, function (err) {
if (err) {
return console.error(err);
}
});
}
function partGenerateBase() {
it('test gen/extend/tool_utility generateBase', function () {
var fs = require("fs");
if (fs.existsSync('test/unittest/tool_utility.cpp')) {
fs.unlink('test/unittest/tool_utility.cpp', function (err) {
if (err) {
return console.error(err);
}
});
checkUnlink('test/unittest/tool_utility.cpp')
}
if (fs.existsSync('test/unittest/tool_utility.h')) {
fs.unlink('test/unittest/tool_utility.h', function (err) {
if (err) {
return console.error(err);
}
});
checkUnlink('test/unittest/tool_utility.h')
}
generateBase('test/unittest', '/*\n* Copyright (c) 2022 Shenzhen Kaihong\n*/');
let data = readFile("test/unittest/tool_utility.cpp")