!428 修改js文件和Java文件下错误

Merge pull request !428 from zhangmenghan/master
This commit is contained in:
openharmony_ci 2024-07-11 14:44:51 +00:00 committed by Gitee
commit c2325857d3
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
27 changed files with 1142 additions and 1113 deletions

View File

@ -1,19 +1,19 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fs = require('fs');
const path = require("path");
const path = require('path');
let vscode = null;
try {
vscode = require('vscode');
@ -31,10 +31,10 @@ NapiLog.LEV_ERROR = 1;
NapiLog.LEV_DEBUG = 2;
NapiLog.LEV_INFO = 3;
const LEV_STR = ["[NON]", "[ERR]", "[DBG]", "[INF]"]
const LEV_STR = ['[NON]', '[ERR]', '[DBG]', '[INF]'];
var logLevel = NapiLog.LEV_ERROR;
var logFileName = null;
var logResultMessage = [true, ""]
var logResultMessage = [true, ''];
function getDateString() {
let nowDate = new Date();
@ -43,7 +43,7 @@ function getDateString() {
function saveLog(dateStr, levStr, detail) {
if (logFileName) {
let logStr = dateStr + " " + levStr + " " + detail + "\n";
let logStr = dateStr + ' ' + levStr + ' ' + detail + '\n';
fs.appendFileSync(logFileName, logStr);
}
}
@ -51,67 +51,69 @@ function saveLog(dateStr, levStr, detail) {
NapiLog.init = function (level, fileName) {
logLevel = level in [NapiLog.LEV_NONE, NapiLog.LEV_ERROR, NapiLog.LEV_DEBUG, NapiLog.LEV_INFO]
? level : NapiLog.LEV_ERROR;
logFileName = fileName ? fileName : "napi_generator.log";
}
logFileName = fileName ? fileName : 'napi_generator.log';
};
/**
* 通过调用栈获取当前正在执行的方法名代码行数及文件路径
* @param {} callerFuncName 指定取调用栈中哪个方法名所在的帧作为目标帧
* @returns
*/
NapiLog.getCallPath = function(callerFuncName = null) {
let callPath = ""
NapiLog.getCallPath = function (callerFuncName = null) {
let callPath = '';
let stackArray = new Error().stack.split('\n');
// 如果没有指定目标方法,默认在调用栈中查找当前方法"getCallPath"所在的帧
let destFuncName = callerFuncName != null ? callerFuncName : "getCallPath"
let destFuncName = callerFuncName != null ? callerFuncName : 'getCallPath';
for (let i = stackArray.length -1; i >=0 ; --i) {
for (let i = stackArray.length - 1; i >= 0; --i) {
// debug模式和打包后的可执行程序调用栈函数名不同 以NapiLog.log()方法为例:
// vscode debug模式下调用栈打印的方法名为NapiLog.log而可执行程序的调用栈中显示为Function.log()
let callerMatch = (stackArray[i].indexOf("NapiLog." + destFuncName) > 0
|| stackArray[i].indexOf("Function." + destFuncName) > 0)
let callerMatch = (stackArray[i].indexOf('NapiLog.' + destFuncName) > 0 ||
stackArray[i].indexOf('Function.' + destFuncName) > 0);
if (callerMatch) {
let stackMsg = stackArray[i+1].trim()
let leftIndex = stackMsg.indexOf("(")
let rightIndex = stackMsg.indexOf(")")
let stackMsg = stackArray[i + 1].trim();
let leftIndex = stackMsg.indexOf('(');
let rightIndex = stackMsg.indexOf(')');
if (leftIndex > 0 && rightIndex > 0) {
let funInfo = stackMsg.substring(0, leftIndex);
let srcPath = stackMsg.substring(leftIndex + 1, rightIndex)
let colNumIndex = srcPath.lastIndexOf(":")
let colNum = srcPath.substring(colNumIndex + 1, srcPath.length)
let lineNumIndex = srcPath.lastIndexOf(":", colNumIndex - 1)
let lineNum = srcPath.substring(lineNumIndex + 1, colNumIndex)
let filePath = srcPath.substring(0, lineNumIndex)
let srcPath = stackMsg.substring(leftIndex + 1, rightIndex);
let colNumIndex = srcPath.lastIndexOf(':');
let colNum = srcPath.substring(colNumIndex + 1, srcPath.length);
let lineNumIndex = srcPath.lastIndexOf(':', colNumIndex - 1);
let lineNum = srcPath.substring(lineNumIndex + 1, colNumIndex);
let filePath = srcPath.substring(0, lineNumIndex);
callPath = "%s[%s(%s:%s)]".format(funInfo,filePath,lineNum,colNum)
callPath = '%s[%s(%s:%s)]'.format(funInfo, ilePath, lineNum, colNum);
}
break;
}
}
return callPath;
}
};
function print(...args) {
if (vscode) {
vscode.window.showInformationMessage(...args);
}
console.log(args + "");
console.log(args + '');
}
function recordLog(lev, ...args) {
let origMsgInfo = args;
let callPath = NapiLog.getCallPath("log");
let callPath = NapiLog.getCallPath('log');
let dataStr = getDateString();
let detail = args.join(" ");
saveLog(dataStr + " " + callPath, LEV_STR[lev], detail);
let detail = args.join(' ');
saveLog(dataStr + ' ' + callPath, LEV_STR[lev], detail);
if (lev === NapiLog.LEV_ERROR) {
logResultMessage = [false, detail];
}
let logStr = callPath + " " + detail;
if (logLevel <= lev) return logStr;
let logStr = callPath + ' ' + detail;
if (logLevel <= lev) {
return logStr;
}
NapiLog.logInfo(origMsgInfo[0]);
return logStr;
}
@ -119,20 +121,20 @@ function recordLog(lev, ...args) {
NapiLog.logError = function (...args) {
let logInfo = recordLog(NapiLog.LEV_ERROR, args);
print(logInfo);
}
};
NapiLog.logDebug = function (...args) {
recordLog(NapiLog.LEV_DEBUG, args);
}
};
NapiLog.logInfo = function (...args) {
recordLog(NapiLog.LEV_INFO, args);
}
};
NapiLog.getResult = function () {
return logResultMessage;
}
};
module.exports = {
NapiLog
}
};

View File

@ -20,7 +20,7 @@ const MOVE_SIX = 6;
function utf8ArrayToStr(array) {
let char2, char3;
let outStr = "";
let outStr = '';
let len = array.length;
let i = 0;
while (i < len) {
@ -74,42 +74,42 @@ function stringToUint8Array(string, option = { streamBool: false }) {
}
}
if (value >= 0xd800 && value <= 0xdbff) {
isContinue = true; // drop lone surrogate
isContinue = true; // drop lone surrogate
}
}
if (!isContinue) {
// expand the buffer if we couldn't write 4 bytes
if (atPos + 4 > target.length) {
tlength += 8; // minimum extra
tlength *= (1.0 + (position / string.length) * 2); // take 2x the remaining
tlength = (tlength >> 3) << 3; // 8 byte offset
tlength += 8; // minimum extra
tlength *= (1.0 + (position / string.length) * 2); // take 2x the remaining
tlength = (tlength >> 3) << 3; // 8 byte offset
target = uint8Array(tlength, target);
}
let calculateResult = calculate(value, target, atPos)
isContinue = calculateResult[0]
target = calculateResult[1]
atPos = calculateResult[2]
let calculateResult = calculate(value, target, atPos);
isContinue = calculateResult[0];
target = calculateResult[1];
atPos = calculateResult[2];
}
}
return target.slice(0, atPos);
}
function calculate(val, target, at) {
let isContinue = false
if ((val & 0xffffff80) === 0) { // 1-byte
target[at++] = val; // ASCII
let isContinue = false;
if ((val & 0xffffff80) === 0) { // 1-byte
target[at++] = val; // ASCII
isContinue = true;
} else if ((val & 0xffe00000) === 0) { // 4-byte
} else if ((val & 0xffe00000) === 0) { // 4-byte
target[at++] = ((val >> MOVE_EIGHTEEN) & 0x07) | 0xf0;
target[at++] = ((val >> MOVE_TWELVE) & 0x3f) | 0x80;
target[at++] = ((val >> MOVE_SIX) & 0x3f) | 0x80;
} else if ((val & 0xffff0000) === 0) { // 3-byte
} else if ((val & 0xffff0000) === 0) { // 3-byte
target[at++] = ((val >> MOVE_TWELVE) & 0x0f) | 0xe0;
target[at++] = ((val >> MOVE_SIX) & 0x3f) | 0x80;
} else if ((val & 0xfffff800) === 0) { // 2-byte
} else if ((val & 0xfffff800) === 0) { // 2-byte
target[at++] = ((val >> MOVE_SIX) & 0x1f) | 0xc0;
} else {
isContinue = true;
@ -117,18 +117,18 @@ function calculate(val, target, at) {
if (!isContinue) {
target[at++] = (val & 0x3f) | 0x80;
}
return [isContinue, target, at]
return [isContinue, target, at];
}
function uint8Array(tlen, target) {
const update = new Uint8Array(tlen);
update.set(target);
return update
return update;
}
function readFile(fn) {
if (!fs.existsSync(fn)) {
return "";
return '';
}
let data = fs.readFileSync(fn);
data = utf8ArrayToStr(data);
@ -161,7 +161,7 @@ function generateRandomInteger(min, max) {
*/
function getJsonCfg(jsonFilePath) {
let jsonCfg = null; // json 配置文件
let jsonFile = fs.readFileSync(jsonFilePath, { encoding: "utf8" });
let jsonFile = fs.readFileSync(jsonFilePath, { encoding: 'utf8' });
jsonCfg = JSON.parse(jsonFile);
return jsonCfg;
}
@ -172,4 +172,4 @@ module.exports = {
appendWriteFile,
generateRandomInteger,
getJsonCfg
}
};

View File

@ -16,16 +16,16 @@
class InterfaceList { }
InterfaceList.interfacess_ = [];
InterfaceList.push = function (ifs) {
InterfaceList.interfacess_.push(ifs)
}
InterfaceList.interfacess_.push(ifs);
};
InterfaceList.pop = function () {
InterfaceList.interfacess_.pop()
}
InterfaceList.interfacess_.pop();
};
InterfaceList.getValue = function (name) {
let ifs = InterfaceList.interfacess_
let ifs = InterfaceList.interfacess_;
for (let i in ifs) {
if (ifs[i].name === name) {
var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, "allProperties")
var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, 'allProperties');
if (hasProperty) {
return ifs[i].body.allProperties.values;
} else {
@ -34,32 +34,32 @@ InterfaceList.getValue = function (name) {
}
}
return null;
}
};
InterfaceList.getBody = function (name) {
let ifs = InterfaceList.interfacess_
let ifs = InterfaceList.interfacess_;
for (let i in ifs) {
if (ifs[i].name === name) {
return ifs[i].body;
}
}
return null;
}
};
class TypeList { }
TypeList.types = [];
TypeList.push = function (ifs) {
TypeList.types.push(ifs)
}
TypeList.types.push(ifs);
};
TypeList.pop = function () {
TypeList.types.pop()
}
TypeList.types.pop();
};
TypeList.getValue = function (name) {
// let ifs = TypeList.types[TypeList.types.length - 1]
let ifs = TypeList.types
let ifs = TypeList.types;
for (let i in ifs) {
if (ifs[i].name === name) {
var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, "allProperties")
var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, 'allProperties');
if (hasProperty) {
return ifs[i].body.allProperties.values;
} else {
@ -68,9 +68,9 @@ TypeList.getValue = function (name) {
}
}
return null;
}
};
module.exports = {
InterfaceList,
TypeList,
}
};

View File

@ -12,8 +12,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { writeFile } = require("./Tool");
const re = require("./re");
const { writeFile } = require('./Tool');
const re = require('./re');
let commonH = `
#ifndef [h_define_replace]
@ -52,7 +52,7 @@ void getErrMessage(napi_status &status, napi_env &env, const napi_extended_error
const char *info, const char *tag);
#endif //[h_define_replace]
`
`;
let commonCpp = `
#include "[include_name]common.h"
@ -74,30 +74,30 @@ void getErrMessage(napi_status &status, napi_env &env, const napi_extended_error
napi_throw_error(env, NULL, res.c_str());
}
}
`
`;
function generateBase(destDir, license, hFilePath) {
let index = hFilePath.lastIndexOf("\\");
let indexH = hFilePath.lastIndexOf(".h");
let index = hFilePath.lastIndexOf('\\');
let indexH = hFilePath.lastIndexOf('.h');
let hFileName = hFilePath.substring(index + 1, indexH).toLowerCase();
// [h_define_replace]
let hDefine = "NAPITUTORIALS_" + hFileName.toLocaleUpperCase() + "COMMON_H"
commonH = replaceAll(commonH, "[h_define_replace]", hDefine)
let hDefine = 'NAPITUTORIALS_' + hFileName.toLocaleUpperCase() + 'COMMON_H';
commonH = replaceAll(commonH, '[h_define_replace]', hDefine);
// [business_include_replace]
let businessInclude = hFilePath.substring(index + 1, hFilePath.length)
commonH = replaceAll(commonH, "[business_include_replace]", businessInclude)
commonCpp = replaceAll(commonCpp, "[include_name]", hFileName)
writeFile(re.pathJoin(destDir, hFileName + "common.h"), null != license ? (license + "\n" + commonH) : commonH)
writeFile(re.pathJoin(destDir, hFileName + "common.cpp"), null != license ? (license + "\n" + commonCpp): commonCpp)
let businessInclude = hFilePath.substring(index + 1, hFilePath.length);
commonH = replaceAll(commonH, '[business_include_replace]', businessInclude);
commonCpp = replaceAll(commonCpp, '[include_name]', hFileName);
writeFile(re.pathJoin(destDir, hFileName + 'common.h'), null != license ? (license + '\n' + commonH) : commonH);
writeFile(re.pathJoin(destDir, hFileName + 'common.cpp'), null != license ? (license + '\n' + commonCpp) : commonCpp);
}
function replaceAll(s, sfrom, sto) {
while (s.indexOf(sfrom) >= 0) {
s = s.replace(sfrom, sto)
s = s.replace(sfrom, sto);
}
return s;
}
module.exports = {
generateBase
}
};

View File

@ -15,18 +15,18 @@
const path = require('path');
function search(ss, data) {
ss = replaceAll(ss, "\\.", "\\.")
ss = replaceAll(ss, '\\.', '\\.');
let reg = new RegExp(ss);
let tt = reg.exec(data);
if (tt === null || tt === undefined) return null;
let ret = { "regs": [] }
if (tt === null || tt === undefined) { return null; }
let ret = { 'regs': [] };
for (let i = 0; i < tt.length; i++) {
let p = data.indexOf(tt[i]);
if (tt[i] === null || tt[i] === undefined) {
ret.regs.push([-1, -1])
ret.regs.push([-1, -1]);
}
else {
ret.regs.push([p, p + tt[i].length])
ret.regs.push([p, p + tt[i].length]);
}
}
@ -34,17 +34,17 @@ function search(ss, data) {
}
function match(ss, data) {
let tt = search(ss, data)
if ((tt !== null && tt !== undefined) && tt.regs[0][0] === 0) return tt;
let tt = search(ss, data);
if ((tt !== null && tt !== undefined) && tt.regs[0][0] === 0) { return tt; }
return null;
}
function removeReg(data, reg) {
return data.substring(0, reg[0]) + data.substring(reg[1], data.length)
return data.substring(0, reg[0]) + data.substring(reg[1], data.length);
}
function getReg(data, reg) {
return data.substring(reg[0], reg[1])
return data.substring(reg[0], reg[1]);
}
function getFileInPath(tpath) {
@ -56,15 +56,15 @@ function getPathInPath(tpath) {
}
function all(sfrom) {
return new RegExp(sfrom, "g");
return new RegExp(sfrom, 'g');
}
function replaceAll(ss, sfrom, sto) {
return ss.replace(all(sfrom), sto)
return ss.replace(all(sfrom), sto);
}
function pathJoin(...args) {
return path.join(...args)
return path.join(...args);
}
module.exports = {
@ -77,4 +77,4 @@ module.exports = {
pathJoin,
replaceAll,
all
}
};

View File

@ -12,55 +12,55 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { NapiLog } = require("../tools/NapiLog");
const { writeFile, appendWriteFile, generateRandomInteger, readFile, getJsonCfg } = require("../tools/Tool");
const path = require('path')
const re = require("../tools/re");
const fs = require("fs");
const os = require("os");
const { NapiLog } = require('../tools/NapiLog');
const { writeFile, appendWriteFile, generateRandomInteger, readFile, getJsonCfg } = require('../tools/Tool');
const path = require('path');
const re = require('../tools/re');
const fs = require('fs');
const os = require('os');
const util = require('util');
const readline = require('readline');
const { generateDirectFunction } = require('../napiGen/functionDirect')
const { generateFuncTestCase } = require('../napiGen/functionDirectTest')
const { generateBase } = require('../tools/commonTemplete')
const { InterfaceList, TypeList } = require('../tools/common')
const { generateDirectFunction } = require('../napiGen/functionDirect');
const { generateFuncTestCase } = require('../napiGen/functionDirectTest');
const { generateBase } = require('../tools/commonTemplete');
const { InterfaceList, TypeList } = require('../tools/common');
const MIN_RANDOM = 100
const MAX_RANDOM = 999
let tsFuncName = ''
const MIN_RANDOM = 100;
const MAX_RANDOM = 999;
let tsFuncName = '';
function parseFileAll(hFilePath) {
let execSync = require("child_process").execSync
let cmd = ""
let execSync = require('child_process').execSync;
let cmd = '';
// call exe file (for real runtime)
let sysInfo = os.platform()
let execPath = path.dirname(process.execPath)
let exeFile = sysInfo === 'win32' ? path.join(execPath, "header_parser.exe") :
path.join(execPath, "header_parser")
cmd = exeFile + " " + hFilePath
let sysInfo = os.platform();
let execPath = path.dirname(process.execPath);
let exeFile = sysInfo === 'win32' ? path.join(execPath, 'header_parser.exe') :
path.join(execPath, 'header_parser');
cmd = exeFile + ' ' + hFilePath;
let parseResult = null
let stdout = execSync(cmd)
parseResult = JSON.parse(stdout.toString()).result
return parseResult
let parseResult = null;
let stdout = execSync(cmd);
parseResult = JSON.parse(stdout.toString()).result;
return parseResult;
}
function createNameSpaceInfo(parseNameSpaceInfo) {
let nameSpaceInfo = {
"name": "",
"classes": [],
"functions": []
}
nameSpaceInfo.name = parseNameSpaceInfo
return nameSpaceInfo
'name': '',
'classes': [],
'functions': []
};
nameSpaceInfo.name = parseNameSpaceInfo;
return nameSpaceInfo;
}
function analyzeNameSpace(rootInfo, parseResult) {
let parseNameSpaces = parseResult.namespaces
let parseNameSpaces = parseResult.namespaces;
for (var i = 0; i < parseNameSpaces.length; ++i) {
let nameSpaceInfo = createNameSpaceInfo(parseNameSpaces[i])
rootInfo.namespaces.push(nameSpaceInfo)
let nameSpaceInfo = createNameSpaceInfo(parseNameSpaces[i]);
rootInfo.namespaces.push(nameSpaceInfo);
}
}
@ -72,17 +72,17 @@ function isStringType(cType) {
case 'wchar_t':
case 'char16_t':
case 'char32_t':
return true
return true;
default:
return false
return false;
}
}
function isBoolType(cType) {
if (cType === 'bool') {
return true
return true;
}
return false
return false;
}
function isNumberType(cType) {
@ -103,179 +103,179 @@ function isNumberType(cType) {
case 'uint64_t':
case 'double_t':
case 'float_t':
return true
return true;
default:
return false
return false;
}
}
function basicC2js(cType) {
let jsType = ""
let jsType = '';
if (isStringType(cType)) {
jsType = 'string'
jsType = 'string';
} else if (isBoolType(cType)) {
jsType = 'boolean'
jsType = 'boolean';
} else if (isNumberType(cType)) {
jsType = 'number'
jsType = 'number';
} else {
jsType = cType
jsType = cType;
}
return jsType
return jsType;
}
function getJsTypeFromC(cType, typeInfo) {
let basicCtype = cType
let matchs = re.match("(std::)?vector<([\x21-\x7e ]+)>", basicCtype);
let basicCtype = cType;
let matchs = re.match('(std::)?vector<([\x21-\x7e ]+)>', basicCtype);
if (matchs) {
basicCtype = re.getReg(basicCtype, matchs.regs[2]).trim()
typeInfo.array = 1
basicCtype = re.getReg(basicCtype, matchs.regs[2]).trim();
typeInfo.array = 1;
}
let unsignedIdx = basicCtype.indexOf('unsigned')
let unsignedIdx = basicCtype.indexOf('unsigned');
if (unsignedIdx >= 0) {
// cut off the keywords 'unsigned'
basicCtype = basicCtype.substring(unsignedIdx + 8, basicCtype.length).trim()
basicCtype = basicCtype.substring(unsignedIdx + 8, basicCtype.length).trim();
}
let jsType = basicCtype
let jsType = basicCtype;
if (typeInfo.array) {
jsType = util.format("Array<%s>", jsType)
jsType = util.format('Array<%s>', jsType);
}
// 去掉const
jsType = jsType.replaceAll('const', '')
jsType = jsType.replaceAll('const', '');
// struct cJson * 的情况
let matchStruct = re.match("(struct)?[A-Z_a-z0-9 *]+", basicCtype);
let matchStruct = re.match('(struct)?[A-Z_a-z0-9 *]+', basicCtype);
if (matchStruct) {
let index = basicCtype.indexOf('struct')
let index = basicCtype.indexOf('struct');
// 去掉struct和*
if (index >=0) {
jsType = jsType.substring(index + 6, basicCtype.length)
if (index >= 0) {
jsType = jsType.substring(index + 6, basicCtype.length);
}
jsType = jsType.replaceAll('*', '').trim()
jsType = jsType.replaceAll('*', '').trim();
}
jsType = basicC2js(jsType)
return jsType
jsType = basicC2js(jsType);
return jsType;
}
function createParam(parseParamInfo) {
let param = {
"name": "",
"type": ""
}
param.name = parseParamInfo.name
let rawType = getJsTypeFromC(parseParamInfo.type, parseParamInfo)
param.type = rawType
'name': '',
'type': ''
};
param.name = parseParamInfo.name;
let rawType = getJsTypeFromC(parseParamInfo.type, parseParamInfo);
param.type = rawType;
return param
return param;
}
function createFuncInfo(parseFuncInfo, isClassFunc) {
let funcInfo = {
"name": "",
"genName": "",
"params": [],
"namespace": "",
"retType": "",
"static": ""
}
funcInfo.name = parseFuncInfo.name
funcInfo.namespace = parseFuncInfo.namespace
let tokenIndex = funcInfo.namespace.indexOf('::')
'name': '',
'genName': '',
'params': [],
'namespace': '',
'retType': '',
'static': ''
};
funcInfo.name = parseFuncInfo.name;
funcInfo.namespace = parseFuncInfo.namespace;
let tokenIndex = funcInfo.namespace.indexOf('::');
if (tokenIndex >= 0) {
// delete '::' in namespace, get the pure space name.
funcInfo.namespace = funcInfo.namespace.substring(0, tokenIndex)
funcInfo.namespace = funcInfo.namespace.substring(0, tokenIndex);
}
let parseParams = parseFuncInfo.parameters
let parseParams = parseFuncInfo.parameters;
for (var i = 0; i < parseParams.length; ++i) {
let param = createParam(parseParams[i])
funcInfo.params.push(param)
let param = createParam(parseParams[i]);
funcInfo.params.push(param);
}
funcInfo.isClassFunc = isClassFunc
funcInfo.isClassFunc = isClassFunc;
if (parseFuncInfo.static && isClassFunc) {
funcInfo.static = "static "
funcInfo.static = 'static ';
}
let retType = parseFuncInfo.returns === '' ? parseFuncInfo.rtnType : parseFuncInfo.returns
funcInfo.retType = getJsTypeFromC(retType, parseFuncInfo)
return funcInfo
let retType = parseFuncInfo.returns === '' ? parseFuncInfo.rtnType : parseFuncInfo.returns;
funcInfo.retType = getJsTypeFromC(retType, parseFuncInfo);
return funcInfo;
}
function putFuncIntoNamespace(funcInfo, namespaces) {
for (var i = 0; i < namespaces.length; ++i) {
if (namespaces[i].name === funcInfo.namespace) {
namespaces[i].functions.push(funcInfo)
return
namespaces[i].functions.push(funcInfo);
return;
}
}
}
function analyzeRootTypeDef(rootInfo, parseResult) {
let parserTypedefs = Object.keys(parseResult.typedefs)
let parserTypedefs = Object.keys(parseResult.typedefs);
for (let i = 0; i < parserTypedefs.length; ++i) {
let objTypedefKeys = parserTypedefs[i]
let objTypedefVal = parseResult.typedefs[parserTypedefs[i]]
rootInfo.typedefs.push({objTypedefKeys, objTypedefVal})
let objTypedefKeys = parserTypedefs[i];
let objTypedefVal = parseResult.typedefs[parserTypedefs[i]];
rootInfo.typedefs.push({objTypedefKeys, objTypedefVal});
}
}
function analyzeRootFunction(rootInfo, parseResult) {
let parseFunctions = parseResult.functions
let parseFunctions = parseResult.functions;
for (var i = 0; i < parseFunctions.length; ++i) {
// 普通方法生成模板
let funcInfo = createFuncInfo(parseFunctions[i], false)
let funcInfo = createFuncInfo(parseFunctions[i], false);
if (parseFunctions[i].namespace !== '') {
// function in namespace
putFuncIntoNamespace(funcInfo, rootInfo.namespaces)
putFuncIntoNamespace(funcInfo, rootInfo.namespaces);
} else {
// function without namespace, put on root
rootInfo.functions.push(funcInfo)
rootInfo.functions.push(funcInfo);
}
}
}
function createProperties(parseProperties) {
let propertyList = []
let propertyList = [];
for (var i = 0; i < parseProperties.length; ++i) {
let property = {}
property.name = parseProperties[i].name
property.type = getJsTypeFromC(parseProperties[i].type, parseProperties[i])
propertyList.push(property)
let property = {};
property.name = parseProperties[i].name;
property.type = getJsTypeFromC(parseProperties[i].type, parseProperties[i]);
propertyList.push(property);
}
return propertyList
return propertyList;
}
function createClassFunctions(parseFuncs) {
let funcList = []
let funcList = [];
for (var i = 0; i < parseFuncs.length; ++i) {
let funcInfo = createFuncInfo(parseFuncs[i], true)
funcList.push(funcInfo)
let funcInfo = createFuncInfo(parseFuncs[i], true);
funcList.push(funcInfo);
}
return funcList
return funcList;
}
function createClassInfo(parseClassInfo) {
let classInfo = {
"name": "",
"namespace": "",
"properties": [],
"functions": [],
"extends": []
}
classInfo.name = parseClassInfo.name
classInfo.namespace = parseClassInfo.namespace
classInfo.properties = createProperties(parseClassInfo.properties.public)
classInfo.functions = createClassFunctions(parseClassInfo.methods.public)
'name': '',
'namespace': '',
'properties': [],
'functions': [],
'extends': []
};
classInfo.name = parseClassInfo.name;
classInfo.namespace = parseClassInfo.namespace;
classInfo.properties = createProperties(parseClassInfo.properties.public);
classInfo.functions = createClassFunctions(parseClassInfo.methods.public);
return classInfo
return classInfo;
}
function putClassIntoNamespace(classInfo, namespaces) {
for (var i = 0; i < namespaces.length; ++i) {
if (namespaces[i].name === classInfo.namespace) {
namespaces[i].classes.push(classInfo)
return
namespaces[i].classes.push(classInfo);
return;
}
}
}
@ -284,55 +284,55 @@ function analyzeClasses(rootInfo, parseResult) {
let parseClasses = parseResult.classes;
for (var className in parseClasses) {
let classInfo = createClassInfo(parseClasses[className])
let classInfo = createClassInfo(parseClasses[className]);
if (classInfo.namespace !== '') {
// class in namespace
putClassIntoNamespace(classInfo, rootInfo.namespaces)
putClassIntoNamespace(classInfo, rootInfo.namespaces);
} else {
// class without namespace, put on root
rootInfo.classes.push(classInfo)
rootInfo.classes.push(classInfo);
}
}
}
function getTab(tabLv) {
let tab = ""
let tab = '';
for (var i = 0; i < tabLv; ++i) {
tab += " "
tab += ' ';
}
return tab
return tab;
}
function genFunction(func, tabLv, dtsDeclare) {
let tab = getTab(tabLv)
let funcPrefix = func.isClassFunc ? "" : "export const "
let funcParams = ""
let tab = getTab(tabLv);
let funcPrefix = func.isClassFunc ? '' : 'export const ';
let funcParams = '';
for (var i = 0; i < func.params.length; ++i) {
funcParams += i > 0 ? ", " : ""
funcParams += func.params[i].name + ": " + func.params[i].type
funcParams += i > 0 ? ', ' : '';
funcParams += func.params[i].name + ': ' + func.params[i].type;
}
func.genName = 'KH' + generateRandomInteger(MIN_RANDOM, MAX_RANDOM) + '_' + func.name
let dtsDeclareContent = replaceAll(dtsDeclare, '[tab_replace]', tab)
dtsDeclareContent = replaceAll(dtsDeclareContent, '[export_replace]', funcPrefix)
dtsDeclareContent = replaceAll(dtsDeclareContent, '[func_name_replace]', func.genName)
dtsDeclareContent = replaceAll(dtsDeclareContent, '[func_param_replace]', funcParams)
dtsDeclareContent = replaceAll(dtsDeclareContent, '[input_introduce_replace]', funcParams === ''? "void": funcParams)
dtsDeclareContent = replaceAll(dtsDeclareContent, '[func_return_replace]', func.retType)
dtsDeclareContent = replaceAll(dtsDeclareContent, '[output_introduce_replace]', func.retType)
dtsDeclareContent = replaceAll(dtsDeclareContent, '[func_introduce_replace]', func.name)
func.genName = 'KH' + generateRandomInteger(MIN_RANDOM, MAX_RANDOM) + '_' + func.name;
let dtsDeclareContent = replaceAll(dtsDeclare, '[tab_replace]', tab);
dtsDeclareContent = replaceAll(dtsDeclareContent, '[export_replace]', funcPrefix);
dtsDeclareContent = replaceAll(dtsDeclareContent, '[func_name_replace]', func.genName);
dtsDeclareContent = replaceAll(dtsDeclareContent, '[func_param_replace]', funcParams);
dtsDeclareContent = replaceAll(dtsDeclareContent, '[input_introduce_replace]', funcParams === '' ? 'void' : funcParams);
dtsDeclareContent = replaceAll(dtsDeclareContent, '[func_return_replace]', func.retType);
dtsDeclareContent = replaceAll(dtsDeclareContent, '[output_introduce_replace]', func.retType);
dtsDeclareContent = replaceAll(dtsDeclareContent, '[func_introduce_replace]', func.name);
let classFuncTestUseTemplete = '[func_name_replace]:([func_param_replace]) => [func_return_replace]'
let classFuncTestUse = replaceAll(classFuncTestUseTemplete, '[func_name_replace]', func.genName)
classFuncTestUse = replaceAll(classFuncTestUse, '[func_param_replace]', funcParams)
classFuncTestUse = replaceAll(classFuncTestUse, '[func_return_replace]', func.retType)
let classFuncTestUseTemplete = '[func_name_replace]:([func_param_replace]) => [func_return_replace]';
let classFuncTestUse = replaceAll(classFuncTestUseTemplete, '[func_name_replace]', func.genName);
classFuncTestUse = replaceAll(classFuncTestUse, '[func_param_replace]', funcParams);
classFuncTestUse = replaceAll(classFuncTestUse, '[func_return_replace]', func.retType);
let interfaceFuncResult = null;
if (func.isClassFunc) {
interfaceFuncResult = {
name: func.genName,
type: classFuncTestUse,
}
};
}
return [dtsDeclareContent,interfaceFuncResult]
return [dtsDeclareContent, interfaceFuncResult];
}
function isJsBasicType(type) {
@ -344,80 +344,80 @@ function isJsBasicType(type) {
}
function genClass(classInfo, tabLv, dtsDeclare, needDeclare = false) {
let tab = getTab(tabLv)
let tsClass = tab + 'export ' + "interface " + classInfo.name + " {\n"
let tab1 = getTab(tabLv + 1)
let tab = getTab(tabLv);
let tsClass = tab + 'export ' + 'interface ' + classInfo.name + ' {\n';
let tab1 = getTab(tabLv + 1);
let interfaceBody = [];
for (var i = 0; i < classInfo.properties.length; ++i) {
let myType = classInfo.properties[i].type
let myType = classInfo.properties[i].type;
if (!isJsBasicType(myType)) {
myType += ' | null'
myType += ' | null';
}
tsClass += util.format("%s%s: %s;\n", tab1, classInfo.properties[i].name, myType)
tsClass += util.format('%s%s: %s;\n', tab1, classInfo.properties[i].name, myType);
interfaceBody.push({
name: classInfo.properties[i].name,
type: classInfo.properties[i].type,
})
});
}
// 循环加入class中的方法
let interfaceFunc = null
let interfaceFunc = null;
for (let i = 0; i < classInfo.functions.length; ++i) {
let result = genFunction(classInfo.functions[i], tabLv+1, dtsDeclare);
tsClass += result[0]
interfaceFunc = result[1]
let result = genFunction(classInfo.functions[i], tabLv + 1, dtsDeclare);
tsClass += result[0];
interfaceFunc = result[1];
if (interfaceFunc !== null) {
interfaceBody.push(interfaceFunc)
interfaceBody.push(interfaceFunc);
}
}
tsClass += tab + "}\n"
tsClass += tab + '}\n';
let interfaceData = {
name: classInfo.name,
body: interfaceBody
}
InterfaceList.push(interfaceData)
return tsClass
};
InterfaceList.push(interfaceData);
return tsClass;
}
function genNamespace(namespace, tabLv, dtsDeclare) {
let tab = getTab(tabLv)
let tsNamespace = tab + util.format("declare namespace %s {\n", namespace.name)
let tab = getTab(tabLv);
let tsNamespace = tab + util.format('declare namespace %s {\n', namespace.name);
for (var i = 0; i < namespace.functions.length; ++i) {
tsNamespace += genFunction(namespace.functions[i], tabLv + 1 , dtsDeclare)[0]
tsNamespace += genFunction(namespace.functions[i], tabLv + 1, dtsDeclare)[0];
}
for (var i = 0; i < namespace.classes.length; ++i) {
tsNamespace += genClass(namespace.classes[i], tabLv + 1, dtsDeclare)
tsNamespace += genClass(namespace.classes[i], tabLv + 1, dtsDeclare);
}
tsNamespace += tab + "}\n"
return tsNamespace
tsNamespace += tab + '}\n';
return tsNamespace;
}
function genType(typeInfo, tabLv) {
let tab = getTab(tabLv)
let tsTypedef = ''
let tab = getTab(tabLv);
let tsTypedef = '';
for (let i = 0; i < typeInfo.length; i++) {
if (isNumberType(typeInfo[i].objTypedefVal)) {
tsTypedef += tab + 'type ' + typeInfo[i].objTypedefKeys + ' = number;\n'
tsTypedef += tab + 'type ' + typeInfo[i].objTypedefKeys + ' = number;\n';
let typeData = {
name: typeInfo[i].objTypedefKeys,
body: "number"
}
TypeList.push(typeData)
body: 'number'
};
TypeList.push(typeData);
} else if (isBoolType(typeInfo[i].objTypedefVal)) {
tsTypedef += tab + 'type ' + typeInfo[i].objTypedefKeys + ' = boolean;\n'
tsTypedef += tab + 'type ' + typeInfo[i].objTypedefKeys + ' = boolean;\n';
let typeData = {
name: typeInfo[i].objTypedefKeys,
body: "boolean"
}
TypeList.push(typeData)
body: 'boolean'
};
TypeList.push(typeData);
} else if (isStringType(typeInfo[i].objTypedefVal)) {
tsTypedef += tab + 'type ' + typeInfo[i].objTypedefKeys + ' = string;\n'
tsTypedef += tab + 'type ' + typeInfo[i].objTypedefKeys + ' = string;\n';
let typeData = {
name: typeInfo[i].objTypedefKeys,
body: "string"
}
TypeList.push(typeData)
body: 'string'
};
TypeList.push(typeData);
}
}
@ -425,23 +425,23 @@ function genType(typeInfo, tabLv) {
}
function genTsContent(rootInfo, dtsDeclare) {
let tsContent = rootInfo.needCallback ? "import { AsyncCallback, Callback } from './../basic';\n\n" : ""
let tsContent = rootInfo.needCallback ? 'import { AsyncCallback, Callback } from './../basic';\n\n' : '';
// gen typedefs
tsContent += genType(rootInfo.typedefs, 0)
tsContent += genType(rootInfo.typedefs, 0);
for (var i = 0; i < rootInfo.classes.length; ++i) {
tsContent += genClass(rootInfo.classes[i], 0, dtsDeclare, true)
tsContent += genClass(rootInfo.classes[i], 0, dtsDeclare, true);
}
for (var i = 0; i < rootInfo.namespaces.length; ++i) {
tsContent += genNamespace(rootInfo.namespaces[i], 0, dtsDeclare)
tsContent += genNamespace(rootInfo.namespaces[i], 0, dtsDeclare);
}
for (var i = 0; i < rootInfo.functions.length; ++i) {
tsContent += genFunction(rootInfo.functions[i], 0, dtsDeclare)[0]
tsContent += genFunction(rootInfo.functions[i], 0, dtsDeclare)[0];
}
return tsContent
return tsContent;
}
function removeMarco(hFilePath, tempFilePath, macros) {
@ -457,19 +457,19 @@ function removeMarco(hFilePath, tempFilePath, macros) {
// 逐行读取文件内容并处理 去除方法中的宏
rl.on('line', (line) => {
// 替换使用宏的地方,保留#define宏定义
if (line.indexOf('#define') < 0 && line.indexOf('#ifndef') < 0 && line.indexOf('#ifdef')
&& line.indexOf('#elif') && line.indexOf('#if') < 0 && line.indexOf('#else')) {
if (line.indexOf('#define') < 0 && line.indexOf('#ifndef') < 0 && line.indexOf('#ifdef') &&
line.indexOf('#elif') && line.indexOf('#if') < 0 && line.indexOf('#else')) {
macros.forEach(macro => {
// 去掉使用的宏以及括号()
line = getLineContent(line, macro);
})
});
}
processedContent += line + '\n';
});
// 完成读取操作
rl.on('close', () => {
writeFile(tempFilePath, processedContent)
writeFile(tempFilePath, processedContent);
});
}
@ -503,6 +503,8 @@ function extractMacros(headerFilePath) {
fs.readFile(headerFilePath, 'utf8', (err, data) => {
if (err) {
return reject(err);
} else {
return '';
}
// 匹配#define指令的正则表达式
@ -527,30 +529,30 @@ function sleep(ms) {
async function doGenerate(hFilePath, testFilePath, tsFilePath, cppFilePath) {
// 预处理文件,读出文件中所有的宏,存在数组中
let macros = await extractMacros(hFilePath)
let macros = await extractMacros(hFilePath);
// 将使用宏的地方置空
let random = generateRandomInteger(MIN_RANDOM, MAX_RANDOM)
let tempFileName = '../temp_' + random + '.h'
let tempFilePath = path.join(hFilePath, tempFileName)
removeMarco(hFilePath, tempFilePath, macros)
let random = generateRandomInteger(MIN_RANDOM, MAX_RANDOM);
let tempFileName = '../temp_' + random + '.h';
let tempFilePath = path.join(hFilePath, tempFileName);
removeMarco(hFilePath, tempFilePath, macros);
while (!fs.existsSync(tempFilePath)) {
await sleep(20); // 延迟 20 毫秒
}
let parseResult = parseFileAll(tempFilePath)
let parseResult = parseFileAll(tempFilePath);
let rootInfo = {
"namespaces": [],
"classes": [],
"functions": [],
"needCallback": false,
"typedefs": [],
}
'namespaces': [],
'classes': [],
'functions': [],
'needCallback': false,
'typedefs': [],
};
analyzeNameSpace(rootInfo, parseResult)
analyzeRootTypeDef(rootInfo, parseResult)
analyzeRootFunction(rootInfo, parseResult)
analyzeClasses(rootInfo, parseResult)
analyzeNameSpace(rootInfo, parseResult);
analyzeRootTypeDef(rootInfo, parseResult);
analyzeRootFunction(rootInfo, parseResult);
analyzeClasses(rootInfo, parseResult);
// 读取Json文件
let funcJsonPath = path.join(__dirname, '../json/function.json');
@ -558,13 +560,13 @@ async function doGenerate(hFilePath, testFilePath, tsFilePath, cppFilePath) {
// 读取dts文件模板
let dtsDeclarePath = path.join(__dirname, funcJson.directFunction.dtsTemplete);
let dtsDeclare = readFile(dtsDeclarePath)
let dtsDeclare = readFile(dtsDeclarePath);
let hFileName = hFilePath.substring(hFilePath.lastIndexOf("\\") + 1, hFilePath.length);
let hFileName = hFilePath.substring(hFilePath.lastIndexOf('\\') + 1, hFilePath.length);
// 生成dts声明文件内容
let tsContent = genTsContent(rootInfo, dtsDeclare)
tsContent = replaceAll(tsContent, "[file_introduce_replace]", hFileName)
appendWriteFile(tsFilePath, '\n' + tsContent)
let tsContent = genTsContent(rootInfo, dtsDeclare);
tsContent = replaceAll(tsContent, '[file_introduce_replace]', hFileName);
appendWriteFile(tsFilePath, '\n' + tsContent);
// 生成native侧文件
generateCppFile(cppFilePath, hFilePath, funcJson, rootInfo, parseResult);
@ -573,24 +575,25 @@ async function doGenerate(hFilePath, testFilePath, tsFilePath, cppFilePath) {
generateAbilityTest(funcJson, rootInfo, parseResult, testFilePath, hFileName);
// 删除生成的中间文件
clearTmpFile(tempFilePath)
clearTmpFile(tempFilePath);
console.info('Generate success')
console.info('Generate success');
}
function checkPathType(path) {
try {
const stats = fs.statSync(path);
if (stats.isDirectory()) {
return "directory"
return 'directory';
} else if (stats.isFile()) {
return "file"
return 'file';
} else {
return "badpath"
return 'badpath';
}
} catch (err) {
console.error(err);
}
return '';
}
function checkFileIsNull(filePath) {
@ -618,23 +621,23 @@ function genTestTemplete(filePath, content) {
function generateAbilityTest(funcJson, rootInfo, parseResult, testFilePath, hFileName) {
let index = hFileName.indexOf('.h')
let hFileNameReplace = hFileName.substring(0, index)
let index = hFileName.indexOf('.h');
let hFileNameReplace = hFileName.substring(0, index);
// 第一次生成时应生成框架
let abilityTestFirstGenTempletePath = funcJson.directFunction.testTempleteDetails.abilityTestFirstGenTemplete;
let abilityTestFirstGenAbsPath = path.join(__dirname, abilityTestFirstGenTempletePath);
let abilityTestFirstGenTemplete = readFile(abilityTestFirstGenAbsPath);
abilityTestFirstGenTemplete = replaceAll(abilityTestFirstGenTemplete, '[abilitytest_name_replace]', hFileNameReplace)
abilityTestFirstGenTemplete = replaceAll(abilityTestFirstGenTemplete, '[abilitytest_name_replace]', hFileNameReplace);
// 判断testFilePath是文件还是文件夹若是文件夹则生成文件同时第一次写入内容
let realTestFilePath = testFilePath
let isDir = checkPathType(realTestFilePath)
let realTestFilePath = testFilePath;
let isDir = checkPathType(realTestFilePath);
if (isDir === 'directory') {
realTestFilePath = path.join(testFilePath, hFileNameReplace + 'Ability.test.ets');
genTestTemplete(realTestFilePath, abilityTestFirstGenTemplete)
genTestTemplete(realTestFilePath, abilityTestFirstGenTemplete);
} else if (isDir === 'file') {
if (checkFileIsNull(realTestFilePath)) {
genTestTemplete(realTestFilePath, abilityTestFirstGenTemplete)
genTestTemplete(realTestFilePath, abilityTestFirstGenTemplete);
}
}
@ -656,11 +659,11 @@ function generateCppFile(cppFilePath, hFilePath, funcJson, rootInfo, parseResult
// 写入common.h 和 common.cpp
generateBase(cppFilePath, '', hFilePath);
let index = hFilePath.lastIndexOf("\\");
let indexH = hFilePath.lastIndexOf(".h");
let index = hFilePath.lastIndexOf('\\');
let indexH = hFilePath.lastIndexOf('.h');
let napiHFileName = hFilePath.substring(index + 1, indexH).toLowerCase() + 'napi.h';
let includes_replace = util.format('#include "%s"\n', napiHFileName);
let hFileName = hFilePath.substring(hFilePath.lastIndexOf("\\") + 1, hFilePath.length);
let includesReplace = util.format('#include "%s"\n', napiHFileName);
let hFileName = hFilePath.substring(hFilePath.lastIndexOf('\\') + 1, hFilePath.length);
let funcDeclare = '';
let funcInit = '';
@ -672,7 +675,7 @@ function generateCppFile(cppFilePath, hFilePath, funcJson, rootInfo, parseResult
let genResult = generateDirectFunction(parseResult, i, rootInfo.functions[i].genName, directFuncPath, hFileName);
funcDeclare += genResult[0];
funcInit += genResult[1];
let funcBody = includes_replace + genResult[2];
let funcBody = includesReplace + genResult[2];
writeFile(thisFuncCppFilePath, funcBody);
}
@ -680,7 +683,7 @@ function generateCppFile(cppFilePath, hFilePath, funcJson, rootInfo, parseResult
let cppInitTempletePath = funcJson.directFunction.initTempleteDetails.cppInitTemplete;
const cppInitTempleteAbsPath = path.join(__dirname, cppInitTempletePath);
let cppInitTemplete = readFile(cppInitTempleteAbsPath);
cppInitTemplete = replaceAll(cppInitTemplete, '[include_replace]', includes_replace);
cppInitTemplete = replaceAll(cppInitTemplete, '[include_replace]', includesReplace);
cppInitTemplete = replaceAll(cppInitTemplete, '[init_replace]', funcInit);
let napiInitFileName = hFilePath.substring(index + 1, indexH).toLowerCase() + 'init.cpp';
let initFilePath = path.join(cppFilePath, napiInitFileName);
@ -710,15 +713,15 @@ function writeTestFile(filePath, importContent, funcTestContent) {
newFileContent = fileContent.slice(0, importPosition) + newImportStatement + fileContent.slice(importPosition);
}
// 追加写入测试用例
let testCasePosition = newFileContent.lastIndexOf('})')
let testCasePosition = newFileContent.lastIndexOf('})');
newFileContent = newFileContent.slice(0, testCasePosition) + funcTestContent + newFileContent.slice(testCasePosition);
writeFile(filePath, newFileContent)
writeFile(filePath, newFileContent);
}
function replaceAll(s, sfrom, sto) {
while (s.indexOf(sfrom) >= 0) {
s = s.replace(sfrom, sto)
s = s.replace(sfrom, sto);
}
return s;
}
@ -733,4 +736,4 @@ function clearTmpFile(filePath) {
module.exports = {
doGenerate
}
};

View File

@ -12,25 +12,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { NapiLog } = require("../tools/NapiLog");
const fs = require("fs");
const os = require("os");
const { AllParseFileList } = require("../tools/common");
const { NapiLog } = require('../tools/NapiLog');
const fs = require('fs');
const os = require('os');
const { AllParseFileList } = require('../tools/common');
const path = require('path');
function parseFileAll(hFilePath) {
let execSync = require("child_process").execSync;
let cmd = "";
if(fs.existsSync("./hdc/service/service-gen/src/gen/header_parser.py")) {
let execSync = require('child_process').execSync;
let cmd = '';
if (fs.existsSync('./hdc/service/service-gen/src/gen/header_parser.py')) {
// call python file (for debug test)
cmd = "python ./hdc/service/service-gen/src/gen/header_parser.py " + hFilePath;
cmd = 'python ./hdc/service/service-gen/src/gen/header_parser.py ' + hFilePath;
} else {
// call exe file (for real runtime)
let sysInfo = os.platform();
let execPath = path.dirname(process.execPath);
let exeFile = sysInfo === 'win32' ? path.join(execPath, "header_parser.exe") :
path.join(execPath, "header_parser");
cmd = exeFile + " " + hFilePath;
let exeFile = sysInfo === 'win32' ? path.join(execPath, 'header_parser.exe') :
path.join(execPath, 'header_parser');
cmd = exeFile + ' ' + hFilePath;
}
let parseResult = null;
@ -51,7 +51,7 @@ function analyzeNameSpace(rootInfo, parseResult) {
function createParam(parseParamInfo) {
let param = {};
param.name = parseParamInfo.name;
param.type = parseParamInfo.reference ? parseParamInfo.type.replace("&", "").trim(): parseParamInfo.type
param.type = parseParamInfo.reference ? parseParamInfo.type.replace('&', '').trim() : parseParamInfo.type;
param.rawType = parseParamInfo.raw_type;
param.isPointer = (parseParamInfo.pointer === 1);
param.isReference = (parseParamInfo.reference === 1);
@ -62,15 +62,15 @@ function createParam(parseParamInfo) {
function createFuncInfo(parseFuncInfo) {
let funcInfo = {
"name": "", // 方法名
"params": [], // 参数列表
"retType": "", // 返回值
"rawStr": "" // 方法原始代码
}
'name': '', // 方法名
'params': [], // 参数列表
'retType': '', // 返回值
'rawStr': '' // 方法原始代码
};
funcInfo.name = parseFuncInfo.name;
let parseParams = parseFuncInfo.parameters;
for(var i = 0; i < parseParams.length; ++i) {
for (var i = 0; i < parseParams.length; ++i) {
let param = createParam(parseParams[i]);
funcInfo.params.push(param);
}
@ -82,7 +82,7 @@ function createFuncInfo(parseFuncInfo) {
function createClassFunctions(parseFuncs) {
let funcList = [];
for(var i = 0; i < parseFuncs.length; ++i) {
for (var i = 0; i < parseFuncs.length; ++i) {
if (!(parseFuncs[i].constructor || parseFuncs[i].destructor)) { // 构造和析构方法不需要生成remote接口代码
let funcInfo = createFuncInfo(parseFuncs[i]);
funcList.push(funcInfo);
@ -93,12 +93,12 @@ function createClassFunctions(parseFuncs) {
function createClassInfo(parseClassInfo) {
let classInfo = {
"name": "",
"namespace": [],
"properties": [],
"functions": [],
"extends":[]
}
'name': '',
'namespace': [],
'properties': [],
'functions': [],
'extends':[]
};
classInfo.name = parseClassInfo.name;
classInfo.namespace = parseClassInfo.namespace.split('::');
classInfo.functions = createClassFunctions(parseClassInfo.methods.public);
@ -108,20 +108,20 @@ function createClassInfo(parseClassInfo) {
function analyzeClasses(rootInfo, parseClasses) {
if (parseClasses.length === 0) {
NapiLog.logError("Can not find any class.");
NapiLog.logError('Can not find any class.');
return;
}
let firstClassName = null; // JSON集合中第一个class名称
let serviceClassName = null;// JSON集合中带“@ServiceClass”注解的class名称
let i = 0;
for(var className in parseClasses) {
for (var className in parseClasses) {
if (++i === 1) {
firstClassName = className;
}
let doxygen = parseClasses[className].doxygen;
if (doxygen && doxygen.includes("@ServiceClass")) {
if (doxygen && doxygen.includes('@ServiceClass')) {
serviceClassName = className;
break;
}
@ -135,7 +135,7 @@ function analyzeClasses(rootInfo, parseClasses) {
} else {
// h文件中有多个类基于带@ServiceClass注解的类生成service
if (serviceClassName === null || serviceClassName === undefined) {
NapiLog.logError("There must be one class that contains @ServiceClass annotations.");
NapiLog.logError('There must be one class that contains @ServiceClass annotations.');
return;
}
rootInfo.serviceName = serviceClassName;
@ -149,15 +149,15 @@ function doAnalyze(hFilePath, cmdParam) {
parseResult.isInclude = false;
AllParseFileList.push(parseResult);
let rootInfo = {
"serviceName": "",
"nameSpace": [],
"class": [],
"includes": [],
"using": [],
"serviceId": (cmdParam.serviceId === null || cmdParam.serviceId === undefined) ?
"9002" : cmdParam.serviceId,
"rawContent": parseResult.rawContent
}
'serviceName': '',
'nameSpace': [],
'class': [],
'includes': [],
'using': [],
'serviceId': (cmdParam.serviceId === null || cmdParam.serviceId === undefined) ?
'9002' : cmdParam.serviceId,
'rawContent': parseResult.rawContent
};
analyzeNameSpace(rootInfo, parseResult);
analyzeClasses(rootInfo, parseResult.classes);
@ -168,4 +168,4 @@ function doAnalyze(hFilePath, cmdParam) {
module.exports = {
doAnalyze
}
};

View File

@ -474,4 +474,4 @@ module.exports = {
serviceCfgTemplate,
serviceCfgGnTemplate,
iServiceCppTemplate
}
};

View File

@ -13,59 +13,59 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { NapiLog } = require("../tools/NapiLog");
const { replaceAll, getTab } = require("../tools/tool");
const re = require("../tools/re");
const { NapiLog } = require('../tools/NapiLog');
const { replaceAll, getTab } = require('../tools/tool');
const re = require('../tools/re');
const { iServiceHTemplate, proxyHTemplate, stubHTemplate, serviceHTemplate, proxyCppTemplate,
proxyFuncTemplate, stubCppTemplate, stubInnerFuncTemplate, serviceCppTemplate, serviceFuncImplTemplate,
clientCppTemplate, buildGnTemplate, bundleJsonTemplate, profileGnTemplate, profileXmlTemplate, serviceCfgTemplate,
serviceCfgGnTemplate, iServiceCppTemplate } = require("./fileTemplate");
serviceCfgGnTemplate, iServiceCppTemplate } = require('./fileTemplate');
const { DATA_W_MAP, DATA_R_MAP, VECTOR_W_MAP, VECTOR_R_MAP, getParcelType, AllParseFileList, MarshallInfo,
ProcessingClassList} = require("../tools/common");
ProcessingClassList} = require('../tools/common');
let rootHFileSrc = ""; // .h文件的源码
let rootHFileSrc = ''; // .h文件的源码
let dependSrcList = []; //在.h文件中定义并被接口使用到的class/struct类定义源码集合(接口没用到的class定义就不需要了)
let marshallFuncList = []; // class类的消息序列化方法代码集合
let fileContent = {
"iServiceHFile": {},
"proxyHFile": {},
"stubHFile": {},
"serviceHFile": {},
"proxyCppFile": {},
"stubCppFile": {},
"serviceCppFile": {},
"clientCppFile": {},
"buildGnFile": {},
"bundleJsonFile": {},
"profileGnFile": {},
"profileXmlFile": {},
"serviceCfgFile": {},
"serviceCfgGnFile": {},
"iServiceCppFile": {},
'iServiceHFile': {},
'proxyHFile': {},
'stubHFile': {},
'serviceHFile': {},
'proxyCppFile': {},
'stubCppFile': {},
'serviceCppFile': {},
'clientCppFile': {},
'buildGnFile': {},
'bundleJsonFile': {},
'profileGnFile': {},
'profileXmlFile': {},
'serviceCfgFile': {},
'serviceCfgGnFile': {},
'iServiceCppFile': {},
};
function getIncludeStr(includeList) {
let includeStr = "";
let includeStr = '';
for (let i = 0; i < includeList.length; ++i) {
includeStr += "#include " + includeList[i] + "\n";
includeStr += '#include ' + includeList[i] + '\n';
}
return includeStr;
}
function getUsingStr(usingList) {
let usingStr = "";
let usingStr = '';
for (usingName in usingList) {
usingStr += "\nusing " + usingList[usingName].raw_type + ";";
usingStr += '\nusing ' + usingList[usingName].raw_type + ';';
}
return usingStr;
}
function getFuncParamStr(params) {
let paramStr = "";
let paramStr = '';
for (let i = 0; i < params.length; ++i) {
paramStr += (i === 0) ? "" : ", ";
paramStr += params[i].type + " " + params[i].name;
paramStr += (i === 0) ? '' : ', ';
paramStr += params[i].type + ' ' + params[i].name;
}
return paramStr;
}
@ -78,33 +78,33 @@ function getFuncParamStr(params) {
*/
function getClassSrc(className, rawContent) {
let beginPos = rawContent.indexOf(className);
if( beginPos < 0) {
NapiLog.logError("Warning: Can not find definition of " + className);
if ( beginPos < 0) {
NapiLog.logError('Warning: Can not find definition of ' + className);
return null;
}
let firstBracesPos = rawContent.indexOf("{", beginPos); // class后面第一个{的位置
let firstSemiPos = rawContent.indexOf(";", beginPos); // class后面第一个分号的位置
let firstBracesPos = rawContent.indexOf('{', beginPos); // class后面第一个{的位置
let firstSemiPos = rawContent.indexOf(';', beginPos); // class后面第一个分号的位置
if ( (firstBracesPos < 0) || (firstSemiPos < firstBracesPos)) {
// class定义后面找不到{}或先找到了结束符分号视为该class没有相关的实现代码
NapiLog.logError("Warning: Can not find implementation of " + className);
NapiLog.logError('Warning: Can not find implementation of ' + className);
return null;
}
let endPos = firstBracesPos + 1;
let bracesCount = 1;
for (; (endPos < rawContent.length) && (bracesCount !== 0); ++endPos) {
if (rawContent.charAt(endPos) === "{") {
if (rawContent.charAt(endPos) === '{') {
++bracesCount;
}
if (rawContent.charAt(endPos) === "}") {
if (rawContent.charAt(endPos) === '}') {
--bracesCount;
}
}
if (bracesCount !== 0) {
// 左右括号不匹配
NapiLog.logError("Warning: The braces of %s do not match.".format(className));
NapiLog.logError('Warning: The braces of %s do not match.'.format(className));
return null;
}
@ -135,8 +135,8 @@ function findClassGenInfo(vType) {
function findGetSet(propName, classInfo) {
let upperName = propName.replace(propName[0], propName[0].toUpperCase());
let getName = "get" + upperName;
let setName = "set" + upperName;
let getName = 'get' + upperName;
let setName = 'set' + upperName;
let findGet = false;
let findSet = false;
let result = null;
@ -150,7 +150,7 @@ function findGetSet(propName, classInfo) {
}
if (findGet && findSet) {
// get和set方法必须同时具备成员对象属性才能序列化/反序列化,缺一不可。
result = {"name": propName, "getName": getName, "setName": setName};
result = {'name': propName, 'getName': getName, 'setName': setName};
}
return result;
}
@ -165,48 +165,48 @@ function privatePropMashall(parcelName, objName, classInfo, marshallInfo) {
propFuncs.push(getSetInfo);
} else {
NapiLog.logError(
"Warning: Can not find get/set method of %s.%s, the property will be ignored in remote request."
'Warning: Can not find get/set method of %s.%s, the property will be ignored in remote request.'
.format(classInfo.name, properties[i].name));
}
}
let writePropStr = "";
let readPropStr = "";
let writePropStr = '';
let readPropStr = '';
let tab = getTab(1);
for (let i = 0; i < propFuncs.length; ++i) {
writePropStr += "\n" + tab;
writePropStr += genWrite(objName + "." + propFuncs[i].getName + "()", parcelName, propFuncs[i].type);
writePropStr += '\n' + tab;
writePropStr += genWrite(objName + '.' + propFuncs[i].getName + '()', parcelName, propFuncs[i].type);
readPropStr += "\n" + tab;
readPropStr += '\n' + tab;
let destObj = {
"name": objName + "." + propFuncs[i].name,
"setFunc": objName + "." + propFuncs[i].setName,
"type": propFuncs[i].type
'name': objName + '.' + propFuncs[i].name,
'setFunc': objName + '.' + propFuncs[i].setName,
'type': propFuncs[i].type
};
readPropStr += genRead(parcelName, destObj);
}
marshallInfo.marshallFuncH = marshallInfo.marshallFuncH.replace("[privateMarshall]", writePropStr);
marshallInfo.unmarshallFuncH = marshallInfo.unmarshallFuncH.replace("[privateUnmarshall]", readPropStr);
marshallInfo.marshallFuncH = marshallInfo.marshallFuncH.replace('[privateMarshall]', writePropStr);
marshallInfo.unmarshallFuncH = marshallInfo.unmarshallFuncH.replace('[privateUnmarshall]', readPropStr);
}
function publicPropMashall(parcelName, objName, classInfo, marshallInfo) {
let properties = classInfo.properties.public;
let writePropStr = "";
let readPropStr = "";
let writePropStr = '';
let readPropStr = '';
let tab = getTab(1);
for (let i = 0; i < properties.length; ++i) {
writePropStr += "\n" + tab;
writePropStr += genWrite(objName + "." + properties[i].name, parcelName, properties[i].type);
writePropStr += '\n' + tab;
writePropStr += genWrite(objName + '.' + properties[i].name, parcelName, properties[i].type);
readPropStr += "\n" + tab;
readPropStr += '\n' + tab;
let destObj = {
"name": objName + "." + properties[i].name,
"setFunc": null,
"type": properties[i].type
'name': objName + '.' + properties[i].name,
'setFunc': null,
'type': properties[i].type
};
readPropStr += genRead(parcelName, destObj);
}
marshallInfo.marshallFuncH = marshallInfo.marshallFuncH.replace("[publicMarshall]", writePropStr);
marshallInfo.unmarshallFuncH = marshallInfo.unmarshallFuncH.replace("[publicUnmarshall]", readPropStr);
marshallInfo.marshallFuncH = marshallInfo.marshallFuncH.replace('[publicMarshall]', writePropStr);
marshallInfo.unmarshallFuncH = marshallInfo.unmarshallFuncH.replace('[publicUnmarshall]', readPropStr);
}
/**
@ -228,7 +228,7 @@ function saveClassSrc(classInfo) {
let srcObj = {};
srcObj.name = classInfo.name;
let className = classInfo.declaration_method + " " + classInfo.name;
let className = classInfo.declaration_method + ' ' + classInfo.name;
// 从.h源码中获取该class定义的源码段
srcObj.srcCode = getClassSrc(className, rootHFileSrc);
@ -245,28 +245,28 @@ function createMarshallInfo(classInfo) {
saveClassSrc(classInfo);
let newMarshall = new MarshallInfo(classInfo.name);
let objName = classInfo.name.toLowerCase();
newMarshall.marshallFuncName = "marshalling" + classInfo.name;
newMarshall.unmarshallFuncName = "unmarshalling" + classInfo.name;
newMarshall.marshallFuncName = 'marshalling' + classInfo.name;
newMarshall.unmarshallFuncName = 'unmarshalling' + classInfo.name;
// 为了marshall方法的入参能同时支持左值引用marshall(xx.obj)和右值引用marshall(xx.getObj()),这里采用万能引用模板来实现
newMarshall.marshallFuncH = replaceAll(
"\ntemplate<typename T> // T should be [className]& or [className]&&", "[className]", classInfo.name);
'\ntemplate<typename T> // T should be [className]& or [className]&&', '[className]', classInfo.name);
newMarshall.marshallFuncH +=
"\n%s bool %s(MessageParcel& data, T&& %s) {[publicMarshall][privateMarshall]\n return true;\n}\n"
.format("__attribute__((unused)) static", newMarshall.marshallFuncName, objName);
'\n%s bool %s(MessageParcel& data, T&& %s) {[publicMarshall][privateMarshall]\n return true;\n}\n'
.format('__attribute__((unused)) static', newMarshall.marshallFuncName, objName);
newMarshall.unmarshallFuncH =
"\n%s bool %s(MessageParcel& data, %s& %s) {[publicUnmarshall][privateUnmarshall]\n return true;\n}\n"
.format("__attribute__((unused)) static", newMarshall.unmarshallFuncName, classInfo.name, objName);
'\n%s bool %s(MessageParcel& data, %s& %s) {[publicUnmarshall][privateUnmarshall]\n return true;\n}\n'
.format('__attribute__((unused)) static', newMarshall.unmarshallFuncName, classInfo.name, objName);
let marshallInfo = {
"className": classInfo.name,
"marshallFuncs": newMarshall
}
'className': classInfo.name,
'marshallFuncs': newMarshall
};
// 这里必须先将class放入处理列表中以免后续的属性代码生成过程中再次遇到该class类型造成无限循环嵌套。
ProcessingClassList.push(marshallInfo);
// 继续生成属性代码
publicPropMashall("data", objName, classInfo, newMarshall);
privatePropMashall("data", objName, classInfo, newMarshall);
publicPropMashall('data', objName, classInfo, newMarshall);
privatePropMashall('data', objName, classInfo, newMarshall);
marshallFuncList.push(marshallInfo);
return newMarshall;
@ -292,7 +292,7 @@ function genClassWriteString(objName, parcelName, marshallInfo, classInfo) {
marshall = ProcessingClass.marshallFuncs;
}
}
return "%s(%s, %s);".format(marshall.marshallFuncName, parcelName, objName);
return '%s(%s, %s);'.format(marshall.marshallFuncName, parcelName, objName);
}
/**
@ -307,13 +307,13 @@ function genClassWriteString(objName, parcelName, marshallInfo, classInfo) {
if (!marshall) {
marshall = createMarshallInfo(classInfo);
}
let readStr = "";
let readStr = '';
if (destObj.setFunc) { // 有set方法的是私有成员需要生成set代码
let className = destObj.type;
readStr = "%s tmp%s;\n %s(%s, tmp%s);\n %s(tmp%s);".format(className, className,
readStr = '%s tmp%s;\n %s(%s, tmp%s);\n %s(tmp%s);'.format(className, className,
marshall.unmarshallFuncName, parcelName, className, destObj.setFunc, className);
} else {
readStr = "%s(%s, %s);".format(marshall.unmarshallFuncName, parcelName, destObj.name);
readStr = '%s(%s, %s);'.format(marshall.unmarshallFuncName, parcelName, destObj.name);
}
return readStr;
}
@ -332,10 +332,10 @@ function genClassWriteString(objName, parcelName, marshallInfo, classInfo) {
let parcelType = getParcelType(rawType);
let wFunc = VECTOR_W_MAP.get(parcelType);
if (!wFunc) {
NapiLog.logError("Unsupport writing with type: " + vecType);
return "";
NapiLog.logError('Unsupport writing with type: ' + vecType);
return '';
}
return "%s.%s(%s);".format(parcelName, wFunc, vectorName);
return '%s.%s(%s);'.format(parcelName, wFunc, vectorName);
}
/**
@ -346,7 +346,7 @@ function genClassWriteString(objName, parcelName, marshallInfo, classInfo) {
* @returns 生成的代码段
*/
function genWrite(srcName, parcelName, vType) {
let matchs = re.match("(std::)?vector<([\x21-\x7e]+)[ ]?>", vType);
let matchs = re.match('(std::)?vector<([\x21-\x7e]+)[ ]?>', vType);
if (matchs) {
// vector类型变量包装成parcel data
return genVectorWrite(srcName, parcelName, vType, matchs);
@ -357,8 +357,8 @@ function genWrite(srcName, parcelName, vType) {
if (!wFunc) {
let result = findClassGenInfo(vType);
if (!result[0] && !result[1]) {
NapiLog.logError("Unsupport writing with type: " + vType);
return "";
NapiLog.logError('Unsupport writing with type: ' + vType);
return '';
}
// class与struct类型变量包装成parcel data
@ -366,7 +366,7 @@ function genWrite(srcName, parcelName, vType) {
}
// 基本类型变量包装成parcel data
return "%s.%s(%s);".format(parcelName, wFunc, srcName);
return '%s.%s(%s);'.format(parcelName, wFunc, srcName);
}
/**
@ -383,10 +383,10 @@ function genWrite(srcName, parcelName, vType) {
let parcelType = getParcelType(rawType);
let rFunc = VECTOR_R_MAP.get(parcelType);
if (!rFunc) {
NapiLog.logError("Unsupport reading with type: " + vecType);
return "";
NapiLog.logError('Unsupport reading with type: ' + vecType);
return '';
}
return "%s.%s(&(%s));".format(parcelName, rFunc, vectorName);
return '%s.%s(&(%s));'.format(parcelName, rFunc, vectorName);
}
/**
@ -396,7 +396,7 @@ function genWrite(srcName, parcelName, vType) {
* @returns 生成的代码段
*/
function genRead(parcelName, destObj) {
let matchs = re.match("(std::)?vector<([\x21-\x7e]+)[ ]?>", destObj.type);
let matchs = re.match('(std::)?vector<([\x21-\x7e]+)[ ]?>', destObj.type);
if (matchs) {
// 从parcel data中读取vector类型变量
return genVectorRead(parcelName, destObj.name, destObj.type, matchs);
@ -407,8 +407,8 @@ function genRead(parcelName, destObj) {
if (!rFunc) {
let result = findClassGenInfo(destObj.type);
if (!result[0] && !result[1]) {
NapiLog.logError("Unsupport reading with type: " + destObj.type);
return "";
NapiLog.logError('Unsupport reading with type: ' + destObj.type);
return '';
}
// 从parcel data中读取class与struct类型变量
@ -416,257 +416,257 @@ function genRead(parcelName, destObj) {
}
// 从parcel data中读取基本类型变量
let result = destObj.setFunc ? "%s(%s.%s());".format(destObj.setFunc, parcelName, rFunc)
: "%s = %s.%s();".format(destObj.name, parcelName, rFunc) ;
let result = destObj.setFunc ? '%s(%s.%s());'.format(destObj.setFunc, parcelName, rFunc)
: '%s = %s.%s();'.format(destObj.name, parcelName, rFunc);
return result;
}
function genProxyFunc(funcInfo, className, paramStr) {
let proxyFunc = replaceAll(proxyFuncTemplate, "[className]", className);
proxyFunc = replaceAll(proxyFunc, "[funcName]", funcInfo.name);
proxyFunc = replaceAll(proxyFunc, "[params]", paramStr);
proxyFunc = replaceAll(proxyFunc, "[retType]", funcInfo.retType);
proxyFunc = replaceAll(proxyFunc, "[funcEnum]", funcInfo.funcEnum);
let proxyFunc = replaceAll(proxyFuncTemplate, '[className]', className);
proxyFunc = replaceAll(proxyFunc, '[funcName]', funcInfo.name);
proxyFunc = replaceAll(proxyFunc, '[params]', paramStr);
proxyFunc = replaceAll(proxyFunc, '[retType]', funcInfo.retType);
proxyFunc = replaceAll(proxyFunc, '[funcEnum]', funcInfo.funcEnum);
// 入参处理
let writeDataStr = "";
let writeDataStr = '';
let tab = getTab(1);
for (let i = 0; i < funcInfo.params.length; ++i) {
let param = funcInfo.params[i];
writeDataStr += (i === 0) ? "" : "\n" + tab;
writeDataStr += genWrite(param.name, "data", param.type);
writeDataStr += (i === 0) ? '' : '\n' + tab;
writeDataStr += genWrite(param.name, 'data', param.type);
}
proxyFunc = replaceAll(proxyFunc, "[writeData]", writeDataStr);
proxyFunc = replaceAll(proxyFunc, '[writeData]', writeDataStr);
// 返回值处理
let readReplyStr = "";
if (funcInfo.retType !== "void") {
readReplyStr = "%s result;".format(funcInfo.retType);
let readReplyStr = '';
if (funcInfo.retType !== 'void') {
readReplyStr = '%s result;'.format(funcInfo.retType);
let destObj = {
"name": "result",
"setFunc": null,
"type": funcInfo.retType
'name': 'result',
'setFunc': null,
'type': funcInfo.retType
};
readReplyStr += "\n" + tab + genRead("reply", destObj);
readReplyStr += "\n" + tab + "return result;";
readReplyStr += '\n' + tab + genRead('reply', destObj);
readReplyStr += '\n' + tab + 'return result;';
}
proxyFunc = replaceAll(proxyFunc, "[readReply]", readReplyStr);
proxyFunc = replaceAll(proxyFunc, '[readReply]', readReplyStr);
return proxyFunc;
}
function genStubInnerFunc(funcInfo, className) {
let innerFunc = replaceAll(stubInnerFuncTemplate, "[className]", className);
innerFunc = replaceAll(innerFunc, "[funcName]", funcInfo.name);
let innerFunc = replaceAll(stubInnerFuncTemplate, '[className]', className);
innerFunc = replaceAll(innerFunc, '[funcName]', funcInfo.name);
// 入参处理
let readDataStr = ""; // 生成服务端读取客户端传参的代码段
let readDataStr = ''; // 生成服务端读取客户端传参的代码段
let tab = getTab(1);
let innerParamStr = ""; // 调用业务方法时传入的入参列表
let innerParamStr = ''; // 调用业务方法时传入的入参列表
for (let i = 0; i < funcInfo.params.length; ++i) {
let param = funcInfo.params[i];
let innerParamName = param.name + "Val";
let innerParamName = param.name + 'Val';
if (i > 0) {
readDataStr += "\n" + tab;
innerParamStr += " ,";
readDataStr += '\n' + tab;
innerParamStr += ' ,';
}
//将remote请求中的参数值读取到内部参数变量中
readDataStr += "%s %s;".format(param.type, innerParamName); // 定义内部参数变量
readDataStr += '%s %s;'.format(param.type, innerParamName); // 定义内部参数变量
let destObj = {
"name": param.name + "Val",
"setFunc": null,
"type": param.type
'name': param.name + 'Val',
'setFunc': null,
'type': param.type
};
readDataStr += "\n" + tab + genRead("data", destObj);
readDataStr += '\n' + tab + genRead('data', destObj);
innerParamStr += innerParamName;
}
innerFunc = replaceAll(innerFunc, "[readData]", readDataStr);
innerFunc = replaceAll(innerFunc, '[readData]', readDataStr);
// 调用service的实际业务逻辑实现方法
let writeReplyStr = ""; // 生成调用服务端实现并返回结果的代码段
if (funcInfo.retType === "void") {
writeReplyStr += "%s(%s); // call business implementation".format(funcInfo.name, innerParamStr);
writeReplyStr += "\n" + tab + "reply.WriteInt32(retCode);";
let writeReplyStr = ''; // 生成调用服务端实现并返回结果的代码段
if (funcInfo.retType === 'void') {
writeReplyStr += '%s(%s); // call business implementation'.format(funcInfo.name, innerParamStr);
writeReplyStr += '\n' + tab + 'reply.WriteInt32(retCode);';
} else {
writeReplyStr += "%s retVal = %s(%s); // call business implementation".format(
writeReplyStr += '%s retVal = %s(%s); // call business implementation'.format(
funcInfo.retType, funcInfo.name, innerParamStr);
writeReplyStr += "\n" + tab + "reply.WriteInt32(retCode);";
writeReplyStr += "\n" + tab + genWrite("retVal", "reply", funcInfo.retType);
writeReplyStr += '\n' + tab + 'reply.WriteInt32(retCode);';
writeReplyStr += '\n' + tab + genWrite('retVal', 'reply', funcInfo.retType);
}
innerFunc = replaceAll(innerFunc, "[writeReply]", writeReplyStr);
innerFunc = replaceAll(innerFunc, '[writeReply]', writeReplyStr);
return innerFunc;
}
function genServiceFunc(funcInfo, className, paramStr) {
let serviceFunc = replaceAll(serviceFuncImplTemplate, "[retType]", funcInfo.retType);
serviceFunc = replaceAll(serviceFunc, "[className]", className);
serviceFunc = replaceAll(serviceFunc, "[funcName]", funcInfo.name);
serviceFunc = replaceAll(serviceFunc, "[params]", paramStr);
let serviceFunc = replaceAll(serviceFuncImplTemplate, '[retType]', funcInfo.retType);
serviceFunc = replaceAll(serviceFunc, '[className]', className);
serviceFunc = replaceAll(serviceFunc, '[funcName]', funcInfo.name);
serviceFunc = replaceAll(serviceFunc, '[params]', paramStr);
return serviceFunc;
}
function genFunctions(classInfo, files) {
let res = genFunctionCode(classInfo);
files.iServiceH = replaceAll(files.iServiceH, "[funcEnum]", res.funcEnumStr);
files.iServiceH = replaceAll(files.iServiceH, "[functions]", res.iServiceFuncH);
files.proxyH = replaceAll(files.proxyH, "[functions]", res.proxyFuncH);
files.stubH = replaceAll(files.stubH, "[innerFuncDef]", res.stubInnerFuncH);
files.serviceH = replaceAll(files.serviceH, "[functions]", res.proxyFuncH);
files.proxyCpp = replaceAll(files.proxyCpp, "[remoteFuncImpl]", res.proxyFuncCpp);
files.stubCpp = replaceAll(files.stubCpp, "[innerFuncMap]", res.stubInnerFuncMap);
files.stubCpp = replaceAll(files.stubCpp, "[innerFuncImpl]", res.stubInnerFuncCpp);
files.serviceCpp = replaceAll(files.serviceCpp, "[serviceFuncImpl]", res.serviceFuncCpp);
files.clientCpp = replaceAll(files.clientCpp, "[clientFuncInvoke]", res.clientFuncCpp);
files.iServiceH = replaceAll(files.iServiceH, '[funcEnum]', res.funcEnumStr);
files.iServiceH = replaceAll(files.iServiceH, '[functions]', res.iServiceFuncH);
files.proxyH = replaceAll(files.proxyH, '[functions]', res.proxyFuncH);
files.stubH = replaceAll(files.stubH, '[innerFuncDef]', res.stubInnerFuncH);
files.serviceH = replaceAll(files.serviceH, '[functions]', res.proxyFuncH);
files.proxyCpp = replaceAll(files.proxyCpp, '[remoteFuncImpl]', res.proxyFuncCpp);
files.stubCpp = replaceAll(files.stubCpp, '[innerFuncMap]', res.stubInnerFuncMap);
files.stubCpp = replaceAll(files.stubCpp, '[innerFuncImpl]', res.stubInnerFuncCpp);
files.serviceCpp = replaceAll(files.serviceCpp, '[serviceFuncImpl]', res.serviceFuncCpp);
files.clientCpp = replaceAll(files.clientCpp, '[clientFuncInvoke]', res.clientFuncCpp);
}
function genFilesByTemplate(upperServiceName, lowServiceName, rootInfo) {
let files = {};
// 按模板生成.h和.cpp文件内容框架
files.iServiceH = replaceAll(iServiceHTemplate, "[marcoName]", upperServiceName);
files.proxyH = replaceAll(proxyHTemplate, "[marcoName]", upperServiceName);
files.stubH = replaceAll(stubHTemplate, "[marcoName]", upperServiceName);
files.serviceH = replaceAll(serviceHTemplate, "[marcoName]", upperServiceName);
files.iServiceH = replaceAll(iServiceHTemplate, '[marcoName]', upperServiceName);
files.proxyH = replaceAll(proxyHTemplate, '[marcoName]', upperServiceName);
files.stubH = replaceAll(stubHTemplate, '[marcoName]', upperServiceName);
files.serviceH = replaceAll(serviceHTemplate, '[marcoName]', upperServiceName);
files.proxyCpp = proxyCppTemplate;
files.stubCpp = stubCppTemplate;
files.serviceCpp = replaceAll(serviceCppTemplate, "[marcoName]", upperServiceName);
files.clientCpp = replaceAll(clientCppTemplate, "[marcoName]", upperServiceName);
files.serviceCpp = replaceAll(serviceCppTemplate, '[marcoName]', upperServiceName);
files.clientCpp = replaceAll(clientCppTemplate, '[marcoName]', upperServiceName);
files.iServiceCpp = iServiceCppTemplate;
// 按模板生成资源配置文件内容框架
files.buildGn = replaceAll(buildGnTemplate, "[lowServiceName]", lowServiceName);
files.buildGn = replaceAll(files.buildGn, "[stubCppFile]", fileContent.stubCppFile.name);
files.buildGn = replaceAll(files.buildGn, "[serviceCppFile]", fileContent.serviceCppFile.name);
files.buildGn = replaceAll(files.buildGn, "[proxyCppFile]", fileContent.proxyCppFile.name);
files.buildGn = replaceAll(files.buildGn, "[clientCppFile]", fileContent.clientCppFile.name);
files.buildGn = replaceAll(files.buildGn, "[iServiceCppFile]", fileContent.iServiceCppFile.name);
files.bundleJson = replaceAll(bundleJsonTemplate, "[lowServiceName]", lowServiceName);
files.profileGn = replaceAll(profileGnTemplate, "[lowServiceName]", lowServiceName);
files.profileGn = replaceAll(files.profileGn, "[serviceId]", rootInfo.serviceId);
files.profileXml = replaceAll(profileXmlTemplate, "[lowServiceName]", lowServiceName);
files.profileXml = replaceAll(files.profileXml, "[serviceId]", rootInfo.serviceId);
files.serviceCfg = replaceAll(serviceCfgTemplate, "[lowServiceName]", lowServiceName);
files.serviceGnCfg = replaceAll(serviceCfgGnTemplate, "[lowServiceName]", lowServiceName);
files.buildGn = replaceAll(buildGnTemplate, '[lowServiceName]', lowServiceName);
files.buildGn = replaceAll(files.buildGn, '[stubCppFile]', fileContent.stubCppFile.name);
files.buildGn = replaceAll(files.buildGn, '[serviceCppFile]', fileContent.serviceCppFile.name);
files.buildGn = replaceAll(files.buildGn, '[proxyCppFile]', fileContent.proxyCppFile.name);
files.buildGn = replaceAll(files.buildGn, '[clientCppFile]', fileContent.clientCppFile.name);
files.buildGn = replaceAll(files.buildGn, '[iServiceCppFile]', fileContent.iServiceCppFile.name);
files.bundleJson = replaceAll(bundleJsonTemplate, '[lowServiceName]', lowServiceName);
files.profileGn = replaceAll(profileGnTemplate, '[lowServiceName]', lowServiceName);
files.profileGn = replaceAll(files.profileGn, '[serviceId]', rootInfo.serviceId);
files.profileXml = replaceAll(profileXmlTemplate, '[lowServiceName]', lowServiceName);
files.profileXml = replaceAll(files.profileXml, '[serviceId]', rootInfo.serviceId);
files.serviceCfg = replaceAll(serviceCfgTemplate, '[lowServiceName]', lowServiceName);
files.serviceGnCfg = replaceAll(serviceCfgGnTemplate, '[lowServiceName]', lowServiceName);
return files;
}
function replaceClassName(files, classInfo) {
files.iServiceH = replaceAll(files.iServiceH, "[className]", classInfo.name);
files.proxyH = replaceAll(files.proxyH, "[className]", classInfo.name);
files.stubH = replaceAll(files.stubH, "[className]", classInfo.name);
files.serviceH = replaceAll(files.serviceH, "[className]", classInfo.name);
files.proxyCpp = replaceAll(files.proxyCpp, "[className]", classInfo.name);
files.stubCpp = replaceAll(files.stubCpp, "[className]", classInfo.name);
files.serviceCpp = replaceAll(files.serviceCpp, "[className]", classInfo.name);
files.clientCpp = replaceAll(files.clientCpp, "[className]", classInfo.name);
files.iServiceH = replaceAll(files.iServiceH, '[className]', classInfo.name);
files.proxyH = replaceAll(files.proxyH, '[className]', classInfo.name);
files.stubH = replaceAll(files.stubH, '[className]', classInfo.name);
files.serviceH = replaceAll(files.serviceH, '[className]', classInfo.name);
files.proxyCpp = replaceAll(files.proxyCpp, '[className]', classInfo.name);
files.stubCpp = replaceAll(files.stubCpp, '[className]', classInfo.name);
files.serviceCpp = replaceAll(files.serviceCpp, '[className]', classInfo.name);
files.clientCpp = replaceAll(files.clientCpp, '[className]', classInfo.name);
}
function replaceServiceName(files, rootInfo) {
files.iServiceH = replaceAll(files.iServiceH, "[serviceName]", rootInfo.serviceName);
files.proxyH = replaceAll(files.proxyH, "[serviceName]", rootInfo.serviceName);
files.stubH = replaceAll(files.stubH, "[serviceName]", rootInfo.serviceName);
files.serviceH = replaceAll(files.serviceH, "[serviceName]", rootInfo.serviceName);
files.proxyCpp = replaceAll(files.proxyCpp, "[serviceName]", rootInfo.serviceName);
files.stubCpp = replaceAll(files.stubCpp, "[serviceName]", rootInfo.serviceName);
files.serviceCpp = replaceAll(files.serviceCpp, "[serviceName]", rootInfo.serviceName);
files.clientCpp = replaceAll(files.clientCpp, "[serviceName]", rootInfo.serviceName);
files.iServiceH = replaceAll(files.iServiceH, '[serviceName]', rootInfo.serviceName);
files.proxyH = replaceAll(files.proxyH, '[serviceName]', rootInfo.serviceName);
files.stubH = replaceAll(files.stubH, '[serviceName]', rootInfo.serviceName);
files.serviceH = replaceAll(files.serviceH, '[serviceName]', rootInfo.serviceName);
files.proxyCpp = replaceAll(files.proxyCpp, '[serviceName]', rootInfo.serviceName);
files.stubCpp = replaceAll(files.stubCpp, '[serviceName]', rootInfo.serviceName);
files.serviceCpp = replaceAll(files.serviceCpp, '[serviceName]', rootInfo.serviceName);
files.clientCpp = replaceAll(files.clientCpp, '[serviceName]', rootInfo.serviceName);
}
function replaceIncludes(files, rootInfo) {
files.iServiceH = replaceAll(files.iServiceH, "[includes]", getIncludeStr(rootInfo.includes));
files.proxyH = replaceAll(files.proxyH, "[iServiceHInclude]", fileContent.iServiceHFile.name);
files.stubH = replaceAll(files.stubH, "[iServiceHInclude]", fileContent.iServiceHFile.name);
files.serviceH = replaceAll(files.serviceH, "[stubHInclude]", fileContent.stubHFile.name);
files.proxyCpp = replaceAll(files.proxyCpp, "[proxyHInclude]", fileContent.proxyHFile.name);
files.stubCpp = replaceAll(files.stubCpp, "[stubHInclude]", fileContent.stubHFile.name);
files.serviceCpp = replaceAll(files.serviceCpp, "[serviceHInclude]", fileContent.serviceHFile.name);
files.clientCpp = replaceAll(files.clientCpp, "[proxyHInclude]", fileContent.proxyHFile.name);
files.iServiceCpp = replaceAll(files.iServiceCpp, "[iServiceHInclude]", fileContent.iServiceHFile.name);
files.iServiceH = replaceAll(files.iServiceH, '[includes]', getIncludeStr(rootInfo.includes));
files.proxyH = replaceAll(files.proxyH, '[iServiceHInclude]', fileContent.iServiceHFile.name);
files.stubH = replaceAll(files.stubH, '[iServiceHInclude]', fileContent.iServiceHFile.name);
files.serviceH = replaceAll(files.serviceH, '[stubHInclude]', fileContent.stubHFile.name);
files.proxyCpp = replaceAll(files.proxyCpp, '[proxyHInclude]', fileContent.proxyHFile.name);
files.stubCpp = replaceAll(files.stubCpp, '[stubHInclude]', fileContent.stubHFile.name);
files.serviceCpp = replaceAll(files.serviceCpp, '[serviceHInclude]', fileContent.serviceHFile.name);
files.clientCpp = replaceAll(files.clientCpp, '[proxyHInclude]', fileContent.proxyHFile.name);
files.iServiceCpp = replaceAll(files.iServiceCpp, '[iServiceHInclude]', fileContent.iServiceHFile.name);
}
function replaceUsing(files, rootInfo) {
files.iServiceH = replaceAll(files.iServiceH, "[using]", getUsingStr(rootInfo.using));
files.iServiceH = replaceAll(files.iServiceH, '[using]', getUsingStr(rootInfo.using));
}
function genFileNames(lowServiceName, rootInfo) {
fileContent.iServiceHFile.name = "i_%s_service.h".format(lowServiceName);
fileContent.proxyHFile.name = "%s_service_proxy.h".format(lowServiceName);
fileContent.stubHFile.name = "%s_service_stub.h".format(lowServiceName);
fileContent.serviceHFile.name = "%s_service.h".format(lowServiceName);
fileContent.proxyCppFile.name = "%s_service_proxy.cpp".format(lowServiceName);
fileContent.stubCppFile.name = "%s_service_stub.cpp".format(lowServiceName);
fileContent.serviceCppFile.name = "%s_service.cpp".format(lowServiceName);
fileContent.clientCppFile.name = "%s_client.cpp".format(lowServiceName);
fileContent.buildGnFile.name = "BUILD.gn";
fileContent.bundleJsonFile.name = "bundle.json";
fileContent.profileGnFile.name = "BUILD.gn";
fileContent.profileXmlFile.name = rootInfo.serviceId + ".xml";
fileContent.serviceCfgFile.name = "%s_service.cfg".format(lowServiceName);
fileContent.serviceCfgGnFile.name = "BUILD.gn";
fileContent.iServiceCppFile.name = "i_%s_service.cpp".format(lowServiceName);
fileContent.iServiceHFile.name = 'i_%s_service.h'.format(lowServiceName);
fileContent.proxyHFile.name = '%s_service_proxy.h'.format(lowServiceName);
fileContent.stubHFile.name = '%s_service_stub.h'.format(lowServiceName);
fileContent.serviceHFile.name = '%s_service.h'.format(lowServiceName);
fileContent.proxyCppFile.name = '%s_service_proxy.cpp'.format(lowServiceName);
fileContent.stubCppFile.name = '%s_service_stub.cpp'.format(lowServiceName);
fileContent.serviceCppFile.name = '%s_service.cpp'.format(lowServiceName);
fileContent.clientCppFile.name = '%s_client.cpp'.format(lowServiceName);
fileContent.buildGnFile.name = 'BUILD.gn';
fileContent.bundleJsonFile.name = 'bundle.json';
fileContent.profileGnFile.name = 'BUILD.gn';
fileContent.profileXmlFile.name = rootInfo.serviceId + '.xml';
fileContent.serviceCfgFile.name = '%s_service.cfg'.format(lowServiceName);
fileContent.serviceCfgGnFile.name = 'BUILD.gn';
fileContent.iServiceCppFile.name = 'i_%s_service.cpp'.format(lowServiceName);
}
function genFunctionCode(classInfo) {
let funcList = classInfo.functions;
let genResult = {}
genResult.funcEnumStr = "";
genResult.iServiceFuncH = ""; //i_service.h 方法定义
genResult.proxyFuncH = ""; //proxy.h 方法定义
genResult.stubInnerFuncH = ""; // stub.h 的inner方法定义
genResult.proxyFuncCpp = ""; //proxy.cpp 方法实现
genResult.stubInnerFuncMap = ""; // stub.cpp 的inner方法映射表
genResult.stubInnerFuncCpp = ""; // stub.cpp 的inner方法实现
genResult.serviceFuncCpp = ""; // service.cpp的方法实现
genResult.clientFuncCpp = ""; // client.cpp 的inner方法定义
let genResult = {};
genResult.funcEnumStr = '';
genResult.iServiceFuncH = ''; //i_service.h 方法定义
genResult.proxyFuncH = ''; //proxy.h 方法定义
genResult.stubInnerFuncH = ''; // stub.h 的inner方法定义
genResult.proxyFuncCpp = ''; //proxy.cpp 方法实现
genResult.stubInnerFuncMap = ''; // stub.cpp 的inner方法映射表
genResult.stubInnerFuncCpp = ''; // stub.cpp 的inner方法实现
genResult.serviceFuncCpp = ''; // service.cpp的方法实现
genResult.clientFuncCpp = ''; // client.cpp 的inner方法定义
let enumTab = getTab(2);
let funcTab = getTab(1);
for (var i = 0; i < funcList.length; ++i) {
funcList[i].funcEnum = funcList[i].name.toUpperCase(); // remote方法的枚举值
genResult.funcEnumStr += (i === 0) ? "" : ",\n" + enumTab;
genResult.funcEnumStr += (i === 0) ? '' : ',\n' + enumTab;
genResult.funcEnumStr += funcList[i].funcEnum;
let paramStr = getFuncParamStr(funcList[i].params);
genResult.iServiceFuncH += (i === 0) ? "" : "\n" + funcTab;
genResult.iServiceFuncH += "virtual %s %s(%s) = 0;".format(funcList[i].retType, funcList[i].name, paramStr);
genResult.iServiceFuncH += (i === 0) ? '' : '\n' + funcTab;
genResult.iServiceFuncH += 'virtual %s %s(%s) = 0;'.format(funcList[i].retType, funcList[i].name, paramStr);
genResult.proxyFuncH += (i === 0) ? "" : "\n" + funcTab;
genResult.proxyFuncH += "%s %s(%s) override;".format(funcList[i].retType, funcList[i].name, paramStr);
genResult.proxyFuncH += (i === 0) ? '' : '\n' + funcTab;
genResult.proxyFuncH += '%s %s(%s) override;'.format(funcList[i].retType, funcList[i].name, paramStr);
genResult.stubInnerFuncH += (i === 0) ? "" : "\n" + funcTab;
genResult.stubInnerFuncH += (i === 0) ? '' : '\n' + funcTab;
genResult.stubInnerFuncH +=
"ErrCode %sInner(MessageParcel &data, MessageParcel &reply);".format(funcList[i].name);
'ErrCode %sInner(MessageParcel &data, MessageParcel &reply);'.format(funcList[i].name);
genResult.proxyFuncCpp += genProxyFunc(funcList[i], classInfo.name, paramStr);
genResult.stubInnerFuncMap += (i === 0) ? "" : "\n" + funcTab;
genResult.stubInnerFuncMap += "innerFuncs_[%s] = &%sStub::%sInner;".format(
genResult.stubInnerFuncMap += (i === 0) ? '' : '\n' + funcTab;
genResult.stubInnerFuncMap += 'innerFuncs_[%s] = &%sStub::%sInner;'.format(
funcList[i].funcEnum, classInfo.name, funcList[i].name);
genResult.stubInnerFuncCpp += genStubInnerFunc(funcList[i], classInfo.name);
genResult.serviceFuncCpp += genServiceFunc(funcList[i], classInfo.name, paramStr);
genResult.clientFuncCpp += (i === 0) ? "" : "\n" + funcTab;
genResult.clientFuncCpp += "// proxy->%s(%s);".format(funcList[i].name, paramStr);
genResult.clientFuncCpp += (i === 0) ? '' : '\n' + funcTab;
genResult.clientFuncCpp += '// proxy->%s(%s);'.format(funcList[i].name, paramStr);
}
return genResult;
}
function genMarshallFuncs(files) {
let marshallFuncH = "";
let marshallFuncH = '';
for (let i = 0; i < marshallFuncList.length; ++i) {
marshallFuncH += marshallFuncList[i].marshallFuncs.marshallFuncH;
marshallFuncH += marshallFuncList[i].marshallFuncs.unmarshallFuncH;
}
files.iServiceH = files.iServiceH.replace("[marshallFunctions]", marshallFuncH);
files.iServiceH = files.iServiceH.replace('[marshallFunctions]', marshallFuncH);
}
function genDependClasses(files) {
let dependSrc = "";
let dependSrc = '';
for (let i = 0; i < dependSrcList.length; ++i) {
dependSrc += dependSrcList[i].srcCode + ";\n\n";
dependSrc += dependSrcList[i].srcCode + ';\n\n';
}
files.iServiceH = files.iServiceH.replace("[dependClasses]", dependSrc);
files.iServiceH = files.iServiceH.replace('[dependClasses]', dependSrc);
}
function doGenerate(rootInfo) {
@ -690,7 +690,7 @@ function doGenerate(rootInfo) {
replaceServiceName(files, rootInfo);
// 替换类名
let classInfo = rootInfo.class[0]
let classInfo = rootInfo.class[0];
replaceClassName(files, classInfo);
// 生成函数定义与实现
@ -723,4 +723,4 @@ function doGenerate(rootInfo) {
module.exports = {
doGenerate
}
};

View File

@ -12,30 +12,30 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require("path");
const stdio = require("stdio");
const path = require('path');
const stdio = require('stdio');
const fs = require('fs');
const re = require("../tools/re");
const re = require('../tools/re');
const { NapiLog } = require("../tools/NapiLog");
const { print } = require("../tools/tool");
const analyze = require("./analyze");
const gen = require("./generate");
const { writeFile, createFolder } = require("../tools/FileRW");
const { NapiLog } = require('../tools/NapiLog');
const { print } = require('../tools/tool');
const analyze = require('./analyze');
const gen = require('./generate');
const { writeFile, createFolder } = require('../tools/FileRW');
let ops = stdio.getopt({
'filename': { key: 'f', args: 1, description: ".h file", default: "" },
'out': { key: 'o', args: 1, description: "output directory", default: "." },
'loglevel': { key: 'l', args: 1, description: "Log Level: 0~3", default: "1" },
'serviceId': { key: 's', args: 1, description: "service register id: 9000~16777214", default: "9000" }
'filename': { key: 'f', args: 1, description: '.h file', default: '' },
'out': { key: 'o', args: 1, description: 'output directory', default: '.' },
'loglevel': { key: 'l', args: 1, description: 'Log Level: 0~3', default: '1' },
'serviceId': { key: 's', args: 1, description: 'service register id: 9000~16777214', default: '9000' }
});
NapiLog.init(ops.loglevel, path.join("" + ops.out, "napi_gen.log"));
NapiLog.init(ops.loglevel, path.join('' + ops.out, 'napi_gen.log'));
let fileNames = ops.filename;
var pathDir = ops.directory;
if ((fileNames === null || fileNames === undefined) && (pathDir === null || pathDir === undefined)) {
NapiLog.logInfo("fileNames and pathDir both cannot be empty at the same time");
NapiLog.logInfo('fileNames and pathDir both cannot be empty at the same time');
} else if (pathDir && pathDir !== '') {
readDirFiles();
} else if (fileNames && fileNames !== '') {
@ -95,12 +95,12 @@ function genServiceFile(fileName) {
let fileContent = gen.doGenerate(rootInfo);
// 3. 创建service工程目录
let servicePath = re.pathJoin(ops.out, rootInfo.serviceName.toLowerCase() + "service");
let etcPath = re.pathJoin(servicePath, "etc");
let includePath = re.pathJoin(servicePath, "include");
let interfacePath = re.pathJoin(servicePath, "interface");
let profilePath = re.pathJoin(servicePath, "sa_profile");
let srcPath = re.pathJoin(servicePath, "src");
let servicePath = re.pathJoin(ops.out, rootInfo.serviceName.toLowerCase() + 'service');
let etcPath = re.pathJoin(servicePath, 'etc');
let includePath = re.pathJoin(servicePath, 'include');
let interfacePath = re.pathJoin(servicePath, 'interface');
let profilePath = re.pathJoin(servicePath, 'sa_profile');
let srcPath = re.pathJoin(servicePath, 'src');
createFolder(servicePath);
createFolder(etcPath);
createFolder(includePath);
@ -127,10 +127,10 @@ function genServiceFile(fileName) {
}
function checkGenerate(fileName) {
NapiLog.logInfo("check file []".format(fileName));
NapiLog.logInfo('check file []'.format(fileName));
let suffix = fileName.split('.').pop().toLowerCase();
if (suffix === 'h') {
NapiLog.logInfo("Generating service code from file " + fileName);
NapiLog.logInfo('Generating service code from file ' + fileName);
genServiceFile(fileName);
} else {
NapiLog.logError('Only .h file is supported.');

View File

@ -18,7 +18,7 @@ function utf8ArrayToStr(array) {
var out, i, len, c;
var char2, char3;
out = "";
out = '';
len = array.length;
i = 0;
while (i < len) {
@ -53,9 +53,9 @@ function stringToUint8Array(string, options = { stream: false }) {
}
let pos = 0;
const len = string.length;
let at = 0; // output position
let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size
let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset
let at = 0; // output position
let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size
let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset
while (pos < len) {
let value = string.charCodeAt(pos++);
@ -69,40 +69,40 @@ function stringToUint8Array(string, options = { stream: false }) {
}
}
if (value >= 0xd800 && value <= 0xdbff) {
isContinue = true; // drop lone surrogate
isContinue = true; // drop lone surrogate
}
}
if (!isContinue) {
// expand the buffer if we couldn't write 4 bytes
if (at + 4 > target.length) {
tlen += 8; // minimum extra
tlen *= (1.0 + (pos / string.length) * 2); // take 2x the remaining
tlen = (tlen >> 3) << 3; // 8 byte offset
tlen += 8; // minimum extra
tlen *= (1.0 + (pos / string.length) * 2); // take 2x the remaining
tlen = (tlen >> 3) << 3; // 8 byte offset
target = uint8Array(tlen, target);
}
let calculateResult = calculate(value, target, at)
isContinue = calculateResult[0]
target = calculateResult[1]
at = calculateResult[2]
let calculateResult = calculate(value, target, at);
isContinue = calculateResult[0];
target = calculateResult[1];
at = calculateResult[2];
}
}
return target.slice(0, at);
}
function calculate(value, target, at) {
let isContinue = false
if ((value & 0xffffff80) === 0) { // 1-byte
target[at++] = value; // ASCII
let isContinue = false;
if ((value & 0xffffff80) === 0) { // 1-byte
target[at++] = value; // ASCII
isContinue = true;
} else if ((value & 0xfffff800) === 0) { // 2-byte
} else if ((value & 0xfffff800) === 0) { // 2-byte
target[at++] = ((value >> 6) & 0x1f) | 0xc0;
} else if ((value & 0xffff0000) === 0) { // 3-byte
} else if ((value & 0xffff0000) === 0) { // 3-byte
target[at++] = ((value >> 12) & 0x0f) | 0xe0;
target[at++] = ((value >> 6) & 0x3f) | 0x80;
} else if ((value & 0xffe00000) === 0) { // 4-byte
} else if ((value & 0xffe00000) === 0) { // 4-byte
target[at++] = ((value >> 18) & 0x07) | 0xf0;
target[at++] = ((value >> 12) & 0x3f) | 0x80;
target[at++] = ((value >> 6) & 0x3f) | 0x80;
@ -112,18 +112,18 @@ function calculate(value, target, at) {
if (!isContinue) {
target[at++] = (value & 0x3f) | 0x80;
}
return [isContinue, target, at]
return [isContinue, target, at];
}
function uint8Array(tlen, target) {
const update = new Uint8Array(tlen);
update.set(target);
return update
return update;
}
function readFile(fn) {
if (!fs.existsSync(fn)) {
return "";
return '';
}
let data = fs.readFileSync(fn);
data = utf8ArrayToStr(data);
@ -138,11 +138,11 @@ function createFolder(path) {
if (fs.existsSync(path)) {
return;
}
fs.mkdirSync(path)
fs.mkdirSync(path);
}
module.exports = {
readFile,
writeFile,
createFolder
}
};

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
const fs = require('fs');
const path = require("path");
const path = require('path');
let vscode = null;
try {
vscode = require('vscode');
@ -31,10 +31,10 @@ NapiLog.LEV_ERROR = 1;
NapiLog.LEV_DEBUG = 2;
NapiLog.LEV_INFO = 3;
const LEV_STR = ["[NON]", "[ERR]", "[DBG]", "[INF]"]
const LEV_STR = ['[NON]', '[ERR]', '[DBG]', '[INF]'];
var logLevel = NapiLog.LEV_ERROR;
var logFileName = null;
var logResultMessage = [true, ""]
var logResultMessage = [true, ''];
function getDateString() {
let nowDate = new Date();
@ -43,7 +43,7 @@ function getDateString() {
function saveLog(dateStr, levStr, detail) {
if (logFileName) {
let logStr = dateStr + " " + levStr + " " + detail + "\n";
let logStr = dateStr + ' ' + levStr + ' ' + detail + '\n';
fs.appendFileSync(logFileName, logStr);
}
}
@ -51,28 +51,28 @@ function saveLog(dateStr, levStr, detail) {
NapiLog.init = function (level, fileName) {
logLevel = level in [NapiLog.LEV_NONE, NapiLog.LEV_ERROR, NapiLog.LEV_DEBUG, NapiLog.LEV_INFO]
? level : NapiLog.LEV_ERROR;
logFileName = fileName ? fileName : "napi_generator.log";
}
logFileName = fileName ? fileName : 'napi_generator.log';
};
function getCallPath() {
let callPath = ""
let callPath = '';
let stackArray = new Error().stack.split('\n');
for (let i = stackArray.length -1; i >=0 ; --i) {
if (stackArray[i].indexOf("NapiLog.log") > 0 || stackArray[i].indexOf("Function.log") > 0) {
let stackMsg = stackArray[i+1].trim()
let leftIndex = stackMsg.indexOf("(")
let rightIndex = stackMsg.indexOf(")")
for (let i = stackArray.length - 1; i >= 0; --i) {
if (stackArray[i].indexOf('NapiLog.log') > 0 || stackArray[i].indexOf('Function.log') > 0) {
let stackMsg = stackArray[i + 1].trim();
let leftIndex = stackMsg.indexOf('(');
let rightIndex = stackMsg.indexOf(')');
if (leftIndex > 0 && rightIndex > 0) {
let funInfo = stackMsg.substring(0, leftIndex);
let srcPath = stackMsg.substring(leftIndex + 1, rightIndex)
let colNumIndex = srcPath.lastIndexOf(":")
let colNum = srcPath.substring(colNumIndex + 1, srcPath.length)
let lineNumIndex = srcPath.lastIndexOf(":", colNumIndex - 1)
let lineNum = srcPath.substring(lineNumIndex + 1, colNumIndex)
let filePath = srcPath.substring(0, lineNumIndex)
let srcPath = stackMsg.substring(leftIndex + 1, rightIndex);
let colNumIndex = srcPath.lastIndexOf(':');
let colNum = srcPath.substring(colNumIndex + 1, srcPath.length);
let lineNumIndex = srcPath.lastIndexOf(':', colNumIndex - 1);
let lineNum = srcPath.substring(lineNumIndex + 1, colNumIndex);
let filePath = srcPath.substring(0, lineNumIndex);
callPath = "%s[%s(%s:%s)]".format(funInfo,filePath,lineNum,colNum)
callPath = '%s[%s(%s:%s)]'.format(funInfo, filePath, lineNum, colNum);
}
break;
}
@ -85,20 +85,22 @@ function print(...args) {
if (vscode) {
vscode.window.showInformationMessage(...args);
}
console.log(args + "");
console.log(args + '');
}
function recordLog(lev, ...args) {
let origMsgInfo = args;
let callPath = getCallPath();
let dataStr = getDateString();
let detail = args.join(" ");
saveLog(dataStr + " " + callPath, LEV_STR[lev], detail);
let detail = args.join(' ');
saveLog(dataStr + ' ' + callPath, LEV_STR[lev], detail);
if (lev === NapiLog.LEV_ERROR) {
logResultMessage = [false, detail];
}
let logStr = callPath + " " + detail;
if (logLevel <= lev) return logStr;
let logStr = callPath + ' ' + detail;
if (logLevel <= lev) {
return logStr;
}
NapiLog.logInfo(origMsgInfo[0]);
return logStr;
}
@ -106,20 +108,20 @@ function recordLog(lev, ...args) {
NapiLog.logError = function (...args) {
let logInfo = recordLog(NapiLog.LEV_ERROR, args);
print(logInfo);
}
};
NapiLog.logDebug = function (...args) {
recordLog(NapiLog.LEV_DEBUG, args);
}
};
NapiLog.logInfo = function (...args) {
recordLog(NapiLog.LEV_INFO, args);
}
};
NapiLog.getResult = function () {
return logResultMessage;
}
};
module.exports = {
NapiLog
}
};

View File

@ -14,48 +14,48 @@
*/
// remote消息中变量类型名(key)与对应的写parcel方法名(value)的映射参考parcel.h
const DATA_W_MAP = new Map(
[["bool", "WriteBoolUnaligned"], ["int8_t", "WriteInt8"], ["uint8_t", "ReadUint8"],
["int16_t", "WriteInt16"], ["uint16_t", "WriteUint16"],
["int32_t", "WriteInt32"], ["uint32_t", "WriteUint32"], ["int64_t", "WriteInt64"], ["uint64_t", "WriteUint64"],
["float", "WriteFloat"], ["double", "WriteDouble"], ["char *", "WriteCString"], ["std::string", "WriteString"],
["string", "WriteString"]
[['bool', 'WriteBoolUnaligned'], ['int8_t', 'WriteInt8'], ['uint8_t', 'ReadUint8'],
['int16_t', 'WriteInt16'], ['uint16_t', 'WriteUint16'],
['int32_t', 'WriteInt32'], ['uint32_t', 'WriteUint32'], ['int64_t', 'WriteInt64'], ['uint64_t', 'WriteUint64'],
['float', 'WriteFloat'], ['double', 'WriteDouble'], ['char *', 'WriteCString'], ['std::string', 'WriteString'],
['string', 'WriteString']
]);
// remote消息中变量类型名(key)与对应的读parcel方法名(value)的映射参考parcel.h
const DATA_R_MAP = new Map(
[["bool", "ReadBoolUnaligned"], ["int8_t", "ReadInt8"], ["uint8_t", "ReadUint8"],
["int16_t", "ReadInt16"], ["uint16_t", "ReadUint16"],
["int32_t", "ReadInt32"], ["uint32_t", "ReadUint32"], ["int64_t", "ReadInt64"], ["uint64_t", "ReadUint64"],
["float", "ReadFloat"], ["double", "ReadDouble"], ["char *", "ReadCString"], ["std::string", "ReadString"],
["string", "ReadString"]
[['bool', 'ReadBoolUnaligned'], ['int8_t', 'ReadInt8'], ['uint8_t', 'ReadUint8'],
['int16_t', 'ReadInt16'], ['uint16_t', 'ReadUint16'],
['int32_t', 'ReadInt32'], ['uint32_t', 'ReadUint32'], ['int64_t', 'ReadInt64'], ['uint64_t', 'ReadUint64'],
['float', 'ReadFloat'], ['double', 'ReadDouble'], ['char *', 'ReadCString'], ['std::string', 'ReadString'],
['string', 'ReadString']
]);
// 常用类型转换表, 将C语言常见类型(key)转换为remote data读写函数使用的类型(value)
// 例如 ErrCode 类型在框架中的系统原型为int类型这里映射成int32_t
// 因为int32_t类型在 DATA_W_MAP/DATA_R_MAP 表中有对应的读写数据方法(WriteInt32/ReadInt32)
const TYPE_DEF_MAP = new Map(
[["ErrCode", "int32_t"], ["char", "int8_t"], ["short", "int16_t"], ["int", "int32_t"], ["long", "int64_t"],
["unsigned char", "uint8_t"], ["unsigned short", "uint16_t"], ["unsigned int", "uint32_t"],
["unsigned long", "uint64_t"], ["double_t", "double"], ["float_t", "float"], ["size_t", "double"],
["long long", "double"], ["long double", "double"]
[['ErrCode', 'int32_t'], ['char', 'int8_t'], ['short', 'int16_t'], ['int', 'int32_t'], ['long', 'int64_t'],
['unsigned char', 'uint8_t'], ['unsigned short', 'uint16_t'], ['unsigned int', 'uint32_t'],
['unsigned long', 'uint64_t'], ['double_t', 'double'], ['float_t', 'float'], ['size_t', 'double'],
['long long', 'double'], ['long double', 'double']
]);
// remote消息中vector变量类型名(key)与对应的写parcel方法名(value)的映射参考parcel.h
const VECTOR_W_MAP = new Map(
[["bool", "WriteBoolVector"], ["int8_t", "WriteInt8Vector"], ["uint8_t", "WriteUInt8Vector"],
["int16_t", "WriteInt16Vector"], ["uint16_t", "WriteUInt16Vector"], ["int32_t", "WriteInt32Vector"],
["uint32_t", "WriteUInt32Vector"], ["int64_t", "WriteInt64Vector"], ["uint64_t", "WriteUInt64Vector"],
["float", "WriteFloatVector"], ["double", "WriteDoubleVector"], ["u16string", "WriteString16Vector"],
["std::string", "WriteStringVector"], ["string", "WriteStringVector"]
[['bool', 'WriteBoolVector'], ['int8_t', 'WriteInt8Vector'], ['uint8_t', 'WriteUInt8Vector'],
['int16_t', 'WriteInt16Vector'], ['uint16_t', 'WriteUInt16Vector'], ['int32_t', 'WriteInt32Vector'],
['uint32_t', 'WriteUInt32Vector'], ['int64_t', 'WriteInt64Vector'], ['uint64_t', 'WriteUInt64Vector'],
['float', 'WriteFloatVector'], ['double', 'WriteDoubleVector'], ['u16string', 'WriteString16Vector'],
['std::string', 'WriteStringVector'], ['string', 'WriteStringVector']
]);
// remote消息中vector变量类型名(key)与对应的读parcel方法名(value)的映射参考parcel.h
const VECTOR_R_MAP = new Map(
[["bool", "ReadBoolVector"], ["int8_t", "ReadInt8Vector"], ["uint8_t", "ReadUInt8Vector"],
["int16_t", "ReadInt16Vector"], ["uint16_t", "ReadUInt16Vector"], ["int32_t", "ReadInt32Vector"],
["uint32_t", "ReadUInt32Vector"], ["int64_t", "ReadInt64Vector"], ["uint64_t", "ReadUInt64Vector"],
["float", "ReadFloatVector"], ["double", "ReadDoubleVector"], ["u16string", "ReadString16Vector"],
["std::string", "ReadStringVector"], ["string", "ReadStringVector"]
[['bool', 'ReadBoolVector'], ['int8_t', 'ReadInt8Vector'], ['uint8_t', 'ReadUInt8Vector'],
['int16_t', 'ReadInt16Vector'], ['uint16_t', 'ReadUInt16Vector'], ['int32_t', 'ReadInt32Vector'],
['uint32_t', 'ReadUInt32Vector'], ['int64_t', 'ReadInt64Vector'], ['uint64_t', 'ReadUInt64Vector'],
['float', 'ReadFloatVector'], ['double', 'ReadDoubleVector'], ['u16string', 'ReadString16Vector'],
['std::string', 'ReadStringVector'], ['string', 'ReadStringVector']
]);
function getParcelType(srcType) {
@ -66,24 +66,24 @@ function getParcelType(srcType) {
class MarshallInfo {
constructor(className) {
this.className = className;
this.marshallFuncName = "";
this.marshallFuncStr = "";
this.unmarshallFuncName = "";
this.unmarshallFuncStr = "";
this.marshallFuncName = '';
this.marshallFuncStr = '';
this.unmarshallFuncName = '';
this.unmarshallFuncStr = '';
}
}
class AllParseFileList { }
AllParseFileList.parseFile_ = [];
AllParseFileList.push = function (ifs) {
AllParseFileList.parseFile_.push(ifs)
}
AllParseFileList.parseFile_.push(ifs);
};
AllParseFileList.pop = function () {
AllParseFileList.parseFile_.pop()
}
AllParseFileList.parseFile_.pop();
};
AllParseFileList.clearAll = function () {
AllParseFileList.parseFile_.splice(0, AllParseFileList.parseFile_.length)
}
AllParseFileList.parseFile_.splice(0, AllParseFileList.parseFile_.length);
};
AllParseFileList.findClassByName = function (destClassName) {
for (let i = 0; i < AllParseFileList.parseFile_.length; ++i) {
let classes = AllParseFileList.parseFile_[i].classes;
@ -95,7 +95,7 @@ AllParseFileList.findClassByName = function (destClassName) {
}
}
return null;
}
};
/**
@ -108,11 +108,11 @@ ProcessingClassList.push = function (classObj) {
// 已存在的class不重复添加
return;
}
ProcessingClassList.classes_.push(classObj)
}
ProcessingClassList.classes_.push(classObj);
};
ProcessingClassList.clearAll = function () {
ProcessingClassList.classes_.splice(0, ProcessingClassList.classes_.length)
}
ProcessingClassList.classes_.splice(0, ProcessingClassList.classes_.length);
};
ProcessingClassList.findByName = function (className) {
for (let i = 0; i < ProcessingClassList.classes_.length; ++i) {
if (ProcessingClassList.classes_[i].className === className) {
@ -120,10 +120,10 @@ ProcessingClassList.findByName = function (className) {
}
}
return null;
}
};
module.exports = {
DATA_W_MAP, DATA_R_MAP, VECTOR_W_MAP, VECTOR_R_MAP, getParcelType, AllParseFileList, MarshallInfo,
ProcessingClassList
}
};

View File

@ -15,18 +15,20 @@
const path = require('path');
function search(ss, data) {
ss = replaceAll(ss, "\\.", "\\.")
ss = replaceAll(ss, '\\.', '\\.');
let reg = new RegExp(ss);
let tt = reg.exec(data);
if (tt == null) return null;
let ret = { "regs": [] }
if (tt == null) {
return null;
}
let ret = { 'regs': [] };
for (let i = 0; i < tt.length; i++) {
let p = data.indexOf(tt[i]);
if (tt[i] == null) {
ret["regs"].push([-1, -1]);
ret['regs'].push([-1, -1]);
}
else {
ret["regs"].push([p, p + tt[i].length]);
ret['regs'].push([p, p + tt[i].length]);
}
}
@ -34,8 +36,10 @@ function search(ss, data) {
}
function match(ss, data) {
let tt = search(ss, data)
if (tt !== null && tt !== undefined && tt.regs[0][0] == 0) return tt;
let tt = search(ss, data);
if (tt !== null && tt !== undefined && tt.regs[0][0] == 0) {
return tt;
}
return null;
}
@ -56,7 +60,7 @@ function getPathInPath(tpath) {
}
function all(sfrom) {
return new RegExp(sfrom, "g");
return new RegExp(sfrom, 'g');
}
function replaceAll(ss, sfrom, sto) {
@ -77,4 +81,4 @@ module.exports = {
pathJoin,
replaceAll,
all
}
};

View File

@ -29,14 +29,16 @@ function print(...args) {
String.prototype.format = function (...args) {
var result = this;
let reg = new RegExp("%[sd]{1}")
let reg = new RegExp('%[sd]{1}');
for (let i = 0; i < args.length; i++) {
let p = result.search(reg);
if (p < 0) break;
if (p < 0) {
break;
}
result = result.substring(0, p) + args[i] + result.substring(p + 2, result.length);
}
return result;
}
};
String.prototype.replaceAll = function (...args) {
let result = this;
@ -44,7 +46,7 @@ String.prototype.replaceAll = function (...args) {
result = result.replace(args[0], args[1]);
}
return result;
}
};
function replaceAll(s, sfrom, sto) {
while (s.indexOf(sfrom) >= 0) {
@ -54,9 +56,9 @@ function replaceAll(s, sfrom, sto) {
}
function getTab(tabLv) {
let tab = "";
for(var i = 0; i < tabLv; ++i) {
tab += " ";
let tab = '';
for (var i = 0; i < tabLv; ++i) {
tab += ' ';
}
return tab;
}
@ -65,4 +67,4 @@ module.exports = {
replaceAll,
print,
getTab
}
};

View File

@ -26,34 +26,34 @@
var mode = 0;
let vscode = acquireVsCodeApi();
window.onload = function () {
document.getElementById("selectMode").addEventListener("change", function (e) {
document.getElementById('selectMode').addEventListener('change', function (e) {
if (e.target.value === 1) {
mode = 1;
} else {
mode = 0;
}
});
}
};
function sendMsg() {
var fileNames = document.getElementById("interfaceFile").value;
var genDir = document.getElementById("genFile").value;
var fileNames = document.getElementById('interfaceFile').value;
var genDir = document.getElementById('genFile').value;
var result = {
mode: mode,
fileNames: fileNames,
genDir: genDir,
}
};
vscode.postMessage(result);
}
function cancel() {
vscode.postMessage("cancel");
vscode.postMessage('cancel');
}
window.addEventListener('message', event => {
const message = event.data;
document.getElementById("interfaceFile").value = message;
})
document.getElementById('interfaceFile').value = message;
});
</script>
<div id="selectMode">
选择方式:

View File

@ -17,12 +17,12 @@
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const fs = require('fs');
const re = require("./gen/tools/VsPluginRe");
const { VsPluginLog } = require("./gen/tools/VsPluginLog");
const re = require('./gen/tools/VsPluginRe');
const { VsPluginLog } = require('./gen/tools/VsPluginLog');
const { detectPlatform, readFile } = require('./gen/tools/VsPluginTool');
const path = require('path');
let exeFilePath = null;
const dirCache={};
const dirCache = {};
let globalPanel = null;
let importToolChain = false;
@ -44,28 +44,29 @@ function activate(context) {
context.subscriptions.push(disposableMenu);
let platform = detectPlatform();
if (platform === 'win') {
exeFilePath = __dirname + "/search-win.exe";
exeFilePath = __dirname + '/search-win.exe';
} else if (platform === 'mac') {
exeFilePath = __dirname + "/search-macos";
exeFilePath = __dirname + '/search-macos';
} else if (platform === 'Linux') {
exeFilePath = __dirname + "/search-linux";
exeFilePath = __dirname + '/search-linux';
}
}
function executorApiscan(name, genDir) {
if (genDir === "" || genDir === null || genDir === undefined) {
if (genDir === '' || genDir === null || genDir === undefined) {
genDir = name;
}
let command = exeFilePath + " -d " + name + " -o " + genDir;
let command = exeFilePath + ' -d ' + name + ' -o ' + genDir;
let 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 !== undefined) ?
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 !== undefined) ?
error : '') + stdout);
return VsPluginLog.logError('VsPlugin:' + error + stdout);
}
vscode.window.showInformationMessage("Api Scan Successfully");
vscode.window.showInformationMessage('Api Scan Successfully');
return '';
});
}
@ -96,10 +97,10 @@ function register(context, command) {
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);
@ -108,11 +109,11 @@ function register(context, command) {
// 路径有效性判断
if (uri.fsPath !== undefined) {
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);
let result = {
msg: "selectASFilePath",
path: tt ? uri.fsPath : ""
}
msg: 'selectASFilePath',
path: tt ? uri.fsPath : ''
};
globalPanel.webview.postMessage(result);
}
});
@ -145,9 +146,9 @@ 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()) {
@ -156,7 +157,7 @@ function checkReceiveMsg(message) {
startNextPlugin();
}
} else {
vscode.window.showInformationMessage("Copy executable program to " + __dirname);
vscode.window.showInformationMessage('Copy executable program to ' + __dirname);
}
}
@ -164,15 +165,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;
@ -199,24 +200,26 @@ function startNextPlugin() {
*/
function selectPath(panel, message) {
const options = {
canSelectMany: false,//是否可以选择多个
canSelectFolders: true,//是否选择文件夹
canSelectMany: false, //是否可以选择多个
canSelectFolders: true, //是否选择文件夹
defaultUri:vscode.Uri.file(message.filePath)//默认打开本地路径
};
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(',');
}
let result = {
msg: message.msg,
path: filePath.length > 0 ? filePath.substring(0, filePath.length - 1) : filePath
}
};
panel.webview.postMessage(result);
return fileUri[0].fsPath
return fileUri[0].fsPath;
} else {
return '';
}
});
}
@ -239,7 +242,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 + '"';
@ -251,4 +254,4 @@ function getWebViewContent(context, templatePath) {
module.exports = {
activate,
deactivate
}
};

View File

@ -23,10 +23,10 @@ VsPluginLog.LEV_ERROR = 1;
VsPluginLog.LEV_DEBUG = 2;
VsPluginLog.LEV_INFO = 3;
const LEV_STR = ["[NON]", "[ERR]", "[DBG]", "[INF]"]
const LEV_STR = ['[NON]', '[ERR]', '[DBG]', '[INF]'];
var logLevel = VsPluginLog.LEV_ERROR;
var logFileName = null;
var logResultMessage = [true, ""]
var logResultMessage = [true, ''];
function getDateString() {
let nowDate = new Date();
@ -35,7 +35,7 @@ function getDateString() {
function saveLog(dateStr, levStr, detail) {
if (logFileName) {
let logStr = dateStr + " " + levStr + " " + detail + "\n";
let logStr = dateStr + ' ' + levStr + ' ' + detail + '\n';
fs.appendFileSync(logFileName, logStr);
}
}
@ -43,36 +43,38 @@ function saveLog(dateStr, levStr, detail) {
VsPluginLog.init = function (level, fileName) {
logLevel = level in [VsPluginLog.LEV_NONE, VsPluginLog.LEV_ERROR, VsPluginLog.LEV_DEBUG, VsPluginLog.LEV_INFO]
? level : VsPluginLog.LEV_ERROR;
logFileName = fileName ? fileName : "napi_generator.log";
}
logFileName = fileName ? fileName : 'napi_generator.log';
};
function recordLog(lev, ...args) {
let dataStr = getDateString();
let detail = args.join(" ");
let detail = args.join(' ');
saveLog(dataStr, LEV_STR[lev], detail);
if (lev == VsPluginLog.LEV_ERROR) {
logResultMessage = [false, detail];
}
if (logLevel < lev) return;
if (logLevel < lev) {
return;
}
VsPluginLog.logInfo(dataStr + LEV_STR[lev] + detail);
}
VsPluginLog.logError = function (...args) {
recordLog(VsPluginLog.LEV_ERROR, args);
}
};
VsPluginLog.logDebug = function (...args) {
recordLog(VsPluginLog.LEV_DEBUG, args);
}
};
VsPluginLog.logInfo = function (...args) {
recordLog(VsPluginLog.LEV_INFO, args);
}
};
VsPluginLog.getResult = function () {
return logResultMessage;
}
};
module.exports = {
VsPluginLog
}
};

View File

@ -15,18 +15,20 @@
const path = require('path');
function search(ss, data) {
ss = replaceAll(ss, "\\.", "\\.")
ss = replaceAll(ss, '\\.', '\\.');
let reg = new RegExp(ss);
let tt = reg.exec(data);
if (tt == null) return null;
let ret = { "regs": [] }
if (tt == null) {
return null
};
let ret = { 'regs': [] };
for (let i = 0; i < tt.length; i++) {
let p = data.indexOf(tt[i]);
if (tt[i] == null) {
ret["regs"].push([-1, -1])
ret['regs'].push([-1, -1]);
}
else {
ret["regs"].push([p, p + tt[i].length])
ret['regs'].push([p, p + tt[i].length]);
}
}
@ -34,8 +36,10 @@ function search(ss, data) {
}
function match(ss, data) {
let tt = search(ss, data)
if (tt != null && tt.regs[0][0] == 0) return tt;
let tt = search(ss, data);
if (tt != null && tt.regs[0][0] == 0) {
return tt;
}
return null;
}
@ -48,11 +52,11 @@ function getPathInPath(tpath) {
}
function all(sfrom) {
return new RegExp(sfrom, "g");
return new RegExp(sfrom, 'g');
}
function replaceAll(ss, sfrom, sto) {
return ss.replace(all(sfrom), sto)
return ss.replace(all(sfrom), sto);
}
module.exports = {
@ -62,4 +66,4 @@ module.exports = {
getPathInPath,
replaceAll,
all
}
};

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
const os = require('os');
const tsc = require("../../node_modules/typescript");
const tsc = require('../../node_modules/typescript');
const fs = require('fs');
let vscode = null;
try {
@ -25,7 +25,7 @@ catch (err) {
function replaceAll(s, sfrom, sto) {
while (s.indexOf(sfrom) >= 0) {
s = s.replace(sfrom, sto)
s = s.replace(sfrom, sto);
}
return s;
}
@ -37,36 +37,38 @@ function detectPlatform() {
return 'mac';
} else if (os.type() == 'Linux') {
return 'Linux';
}
} else {
return '';
}
}
function checkFileError(ifname) {
let program = tsc.createProgram([ifname], {})
let program = tsc.createProgram([ifname], {});
let emitResult = program.emit();
let allDiagnostics = tsc.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
let errorMsg = ''
let errorMsg = '';
allDiagnostics.forEach(diagnostic => {
if (diagnostic.file) {
let { line, character } = tsc.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
let message = tsc.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
let message = tsc.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
errorMsg += `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}\n`;
} else {
errorMsg += tsc.flattenDiagnosticMessageText(diagnostic.messageText, "\n") + "\n";
errorMsg += tsc.flattenDiagnosticMessageText(diagnostic.messageText, '\n') + '\n';
}
});
if (allDiagnostics.length > 0) {
return [false, errorMsg];
}
return [true, ""];
return [true, ''];
}
function utf8ArrayToStr(array) {
var out, i, len, c;
var char2, char3;
out = "";
out = '';
len = array.length;
i = 0;
while (i < len) {
@ -97,7 +99,7 @@ function utf8ArrayToStr(array) {
function readFile(fn) {
if (!fs.existsSync(fn)) {
return "";
return '';
}
let data = fs.readFileSync(fn);
data = utf8ArrayToStr(data);
@ -109,4 +111,4 @@ module.exports = {
detectPlatform,
checkFileError,
readFile
}
};

View File

@ -111,40 +111,40 @@
var mode = 0;
let vscode = acquireVsCodeApi();
function sendApiscanParamMsg() {
var fileNames = document.getElementById("asFilePath").value;
var genDir = document.getElementById("genASResultDir").value;
var buttonName = document.getElementById("okButton").textContent;
var fileNames = document.getElementById('asFilePath').value;
var genDir = document.getElementById('genASResultDir').value;
var buttonName = document.getElementById('okButton').textContent;
var result = {
msg: "api_scan",
msg: 'api_scan',
fileNames: fileNames,
genDir: genDir,
buttonName: buttonName,
}
};
vscode.postMessage(result);
}
function selectASFilePath() {
var fileNames = document.getElementById("asFilePath").value;
var fileNames = document.getElementById('asFilePath').value;
var result = {
msg: "selectASFilePath",
msg: 'selectASFilePath',
filePath: fileNames,
}
};
vscode.postMessage(result);
}
function selectPath(message) {
var genDir = document.getElementById("genASResultDir").value;
var genDir = document.getElementById('genASResultDir').value;
var result = {
msg: message,
filePath: genDir
}
};
vscode.postMessage(result);
}
function cancel() {
var result = {
msg: "cancel"
}
msg: 'cancel'
};
vscode.postMessage(result);
}
@ -153,15 +153,15 @@
const message = event.data.msg;
const path = event.data.path;
if (message === "selectASFilePath") {
document.getElementById("asFilePath").value = path;
document.getElementById("genASResultDir").value = path;
} else if (message === "selectASResultDir") {
document.getElementById("genASResultDir").value = path;
if (message === 'selectASFilePath') {
document.getElementById('asFilePath').value = path;
document.getElementById('genASResultDir').value = path;
} else if (message === 'selectASResultDir') {
document.getElementById('genASResultDir').value = path;
} else {
console.log("param is error");
console.log('param is error');
}
})
});
</script>

View File

@ -12,14 +12,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const xlsx = require("xlsx");
const fs = require("fs");
const path = require("path");
const stdio = require("stdio");
const xlsx = require('xlsx');
const fs = require('fs');
const path = require('path');
const stdio = require('stdio');
let ops = stdio.getopt({
'directory': { key: 'd', args: 1, description: "scan directory" },
'output': { key: 'o', args: 1, description: "output directory", default: "." },
'directory': { key: 'd', args: 1, description: 'scan directory' },
'output': { key: 'o', args: 1, description: 'output directory', default: '.' },
});
let distDir = ops.directory;
@ -42,29 +42,29 @@ function intersection(a, b) {
if (b.has(n1)) {
ret.add(n1);
}
})
});
return ret;
}
function collectFromSheet(sheet) {
let row = 2;
let collectInclude = new Set()
let collectFunction = new Set()
let collectInclude = new Set();
let collectFunction = new Set();
while (true) {
let idx = "B" + row;
let idx = 'B' + row;
if (!(idx in sheet)) {
break;
}
collectInclude.add(sheet[idx].w);
if (sheet["C" + row].w === "Function") {
collectFunction.add(sheet["D" + row].w);
if (sheet['C' + row].w === 'Function') {
collectFunction.add(sheet['D' + row].w);
}
row += 1;
}
return [collectInclude, collectFunction]
return [collectInclude, collectFunction];
}
let wb = xlsx.readFile(path.join(__dirname, "Andr_N_Games_api.xlsx"));
let wb = xlsx.readFile(path.join(__dirname, 'Andr_N_Games_api.xlsx'));
let c1 = collectFromSheet(wb.Sheets.Games);
let c2 = collectFromSheet(wb.Sheets.N);
@ -72,55 +72,55 @@ let c2 = collectFromSheet(wb.Sheets.N);
let androidFeature = {
include: union(c1[0], c2[0]),
function: union(c1[1], c2[1]),
}
};
//////////////////////////////////////////////////////
let projectFiles = {
c: [],
cpp: [],
h: [],
}
};
let projectFeature = {
"function": new Set(),
"include": new Set()
}
'function': new Set(),
'include': new Set()
};
function collectFromFile(fn) {
let data = fs.readFileSync(fn, { encoding: "utf8" });
let data = fs.readFileSync(fn, { encoding: 'utf8' });
for (let ss of data.matchAll(/([A-Za-z_][A-Za-z0-9_]*) *\(/g)) {
projectFeature["function"].add(ss[1]);
projectFeature['function'].add(ss[1]);
}
for (let ss of data.matchAll(/# *include *(<|") *([A-Za-z_][A-Za-z0-9_\-/]*(.h(pp)*)*) *(>|")/g)) {
let s = ss[2].split("/");
let s = ss[2].split('/');
s = s[s.length - 1];
projectFeature["include"].add(s);
projectFeature['include'].add(s);
}
}
function collectFile (pth, f) {
function collectFile(pth, f) {
let fn = path.join(pth, f);
let st;
try {
st = fs.statSync(fn);
} catch(err){
} catch (err) {
return;
}
if (st.isDirectory()) {
collectFeature(fn);
}
else if (st.isFile()) {
if (f.endsWith(".h")) {
if (f.endsWith('.h')) {
projectFiles.h.push(fn);
collectFromFile(fn);
}
else if (f.endsWith(".cpp")) {
else if (f.endsWith('.cpp')) {
projectFiles.cpp.push(fn);
collectFromFile(fn);
}
else if (f.endsWith(".c")) {
else if (f.endsWith('.c')) {
projectFiles.c.push(fn);
collectFromFile(fn);
}
@ -135,12 +135,12 @@ function collectFeature(pth) {
}
}
collectFeature(distDir)
collectFeature(distDir);
let result = {
function: intersection(androidFeature["function"], projectFeature["function"]),
include: intersection(androidFeature["include"], projectFeature["include"]),
}
function: intersection(androidFeature['function'], projectFeature['function']),
include: intersection(androidFeature['include'], projectFeature['include']),
};
console.log(result);
///////////////////////////////save to excel
function string2u8buff(s) {
@ -153,28 +153,28 @@ function string2u8buff(s) {
}
let wopts = {
bookType: "xlsx",
bookType: 'xlsx',
bookSST: false,
type: 'binary'
};
let workbook = xlsx.utils.book_new();
let s1 = []
let s1 = [];
for (let f of result.function) {
s1.push({ function: f })
s1.push({ function: f });
}
let sheet1 = xlsx.utils.json_to_sheet(s1);
xlsx.utils.book_append_sheet(workbook, sheet1, 'sheet1');
let s2 = []
let s2 = [];
for (let f of result.include) {
s2.push({ include: f })
s2.push({ include: f });
}
let sheet2 = xlsx.utils.json_to_sheet(s2);
xlsx.utils.book_append_sheet(workbook, sheet2, 'sheet2');
let wbout = xlsx.write(workbook, wopts);
let ddd = string2u8buff(wbout);
let outPath = path.join(outDir, "result.xlsx");
console.log("output:", outPath);
let outPath = path.join(outDir, 'result.xlsx');
console.log('output:', outPath);
fs.writeFileSync(outPath, ddd);

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);
}
@ -95,19 +95,19 @@ function installExtensions(message) {
extensionIds.length = 0;
}
if (checkApi === true) {
extensionIds.push('kaihong.ApiScan')
extensionIds.push('kaihong.ApiScan');
}
if (checkGn === true) {
extensionIds.push('kaihong.gn-gen')
extensionIds.push('kaihong.gn-gen');
}
if (checkService === true) {
extensionIds.push('kaihong.service-gen')
extensionIds.push('kaihong.service-gen');
}
if (checkTs === true) {
extensionIds.push('kaihong.ts-gen')
extensionIds.push('kaihong.ts-gen');
}
if (checkNapi === true) {
extensionIds.push('kaihong.napi-gen')
extensionIds.push('kaihong.napi-gen');
}
}
startInstallExtensions(extensionIds).catch((error) => {
@ -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;
@ -180,19 +180,19 @@ async function installStartExtension(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 {
console.error('the toolChain does not include this extension!')
console.error('the toolChain does not include this extension!');
}
}
@ -230,10 +230,10 @@ 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+'"';
return $1 + $2 + '"';
}
});
return html;
@ -245,4 +245,4 @@ function deactivate() {}
module.exports = {
activate,
deactivate
}
};

View File

@ -25,7 +25,7 @@ function utf8ArrayToStr(array) {
var res, i, length, ch;
var ch2, ch3;
res = "";
res = '';
length = array.length;
i = 0;
while (i < length) {
@ -70,7 +70,7 @@ function utf8ArrayToStr(array) {
function readFile(fn) {
if (!fs.existsSync(fn)) {
return "";
return '';
}
let data = fs.readFileSync(fn);
data = utf8ArrayToStr(data);
@ -79,4 +79,4 @@ function utf8ArrayToStr(array) {
module.exports = {
readFile
}
};

View File

@ -113,13 +113,13 @@
function onInput(event) {
var value = event.target.value;
value.replace(/\s*/g,"").toLowerCase();
value.replace(/\s*/g, '').toLowerCase();
checkInput(value);
}
// 匹配子串
function matchSubString(userInput) {
const keywords = ["apiscan", "gngen", "servicegen", "tsgen", "napi"];
const keywords = ['apiscan', 'gngen', 'servicegen', 'tsgen', 'napi'];
let matchedKeyword = null;
for (let i = 0; i < keywords.length; i++) {
if (keywords[i].startsWith(userInput)) {
@ -130,78 +130,78 @@
if (matchedKeyword) {
console.log(matchedKeyword);
} else {
console.log("未找到匹配的字符串");
console.log('未找到匹配的字符串');
}
return matchedKeyword;
}
function checkInput(value) {
if (matchSubString(value) === "apiscan") {
document.getElementById("api").style.display="flex";
document.getElementById("gn").style.display="none";
document.getElementById("service").style.display="none";
document.getElementById("ts").style.display="none";
document.getElementById("napi").style.display="none";
} else if (matchSubString(value) === "gngen") {
document.getElementById("api").style.display="none";
document.getElementById("gn").style.display="flex";
document.getElementById("service").style.display="none";
document.getElementById("ts").style.display="none";
document.getElementById("napi").style.display="none";
} else if (matchSubString(value) === "servicegen") {
document.getElementById("api").style.display="none";
document.getElementById("gn").style.display="none";
document.getElementById("service").style.display="flex";
document.getElementById("ts").style.display="none";
document.getElementById("napi").style.display="none";
} else if (matchSubString(value) === "tsgen") {
document.getElementById("api").style.display="none";
document.getElementById("gn").style.display="none";
document.getElementById("service").style.display="none";
document.getElementById("ts").style.display="flex";
document.getElementById("napi").style.display="none";
} else if (matchSubString(value) === "napi") {
document.getElementById("api").style.display="none";
document.getElementById("gn").style.display="none";
document.getElementById("service").style.display="none";
document.getElementById("ts").style.display="none";
document.getElementById("napi").style.display="flex";
if (matchSubString(value) === 'apiscan') {
document.getElementById('api').style.display = 'flex';
document.getElementById('gn').style.display = 'none';
document.getElementById('service').style.display = 'none';
document.getElementById('ts').style.display = 'none';
document.getElementById('napi').style.display = 'none';
} else if (matchSubString(value) === 'gngen') {
document.getElementById('api').style.display = 'none';
document.getElementById('gn').style.display ='flex';
document.getElementById('service').style.display = 'none';
document.getElementById('ts').style.display = 'none';
document.getElementById('napi').style.display = 'none';
} else if (matchSubString(value) === 'servicegen') {
document.getElementById('api').style.display = 'none';
document.getElementById('gn').style.display = 'none';
document.getElementById('service').style.display = 'flex';
document.getElementById('ts').style.display='none';
document.getElementById('napi').style.display = 'none';
} else if (matchSubString(value) === 'tsgen') {
document.getElementById('api').style.display = 'none';
document.getElementById('gn').style.display = 'none';
document.getElementById('service').style.display = 'none';
document.getElementById('ts').style.display = 'flex';
document.getElementById('napi').style.display = 'none';
} else if (matchSubString(value) === 'napi') {
document.getElementById('api').style.display = 'none';
document.getElementById('gn').style.display = 'none';
document.getElementById('service').style.display = 'none';
document.getElementById('ts').style.display = 'none';
document.getElementById('napi').style.display = 'flex';
} else if (value.trim() === '') {
clearSelect();
}
}
function clearSelect() {
document.getElementById("api").style.display="flex";
document.getElementById("gn").style.display="flex";
document.getElementById("service").style.display="flex";
document.getElementById("ts").style.display="flex";
document.getElementById("napi").style.display="flex";
document.getElementById('api').style.display = 'flex';
document.getElementById('gn').style.display = 'flex';
document.getElementById('service').style.display = 'flex';
document.getElementById('ts').style.display = 'flex';
document.getElementById('napi').style.display = 'flex';
}
function cancel() {
var result = {
msg: "cancel"
}
msg: 'cancel'
};
vscode.postMessage(result);
}
function sendParamMsg() {
if (importCheck) {
let checkApi = document.getElementById("isCheckApi").checked;
let checkGn = document.getElementById("isCheckGn").checked;
let checkService = document.getElementById("isCheckService").checked;
let checkTs = document.getElementById("isCheckTs").checked;
let checkNapi = document.getElementById("isCheckNapi").checked;
let checkApi = document.getElementById('isCheckApi').checked;
let checkGn = document.getElementById('isCheckGn').checked;
let checkService = document.getElementById('isCheckService').checked;
let checkTs = document.getElementById('isCheckTs').checked;
let checkNapi = document.getElementById('isCheckNapi').checked;
var result = {
msg: "param",
msg: 'param',
importIsCheck: importCheck,
checkApi: checkApi,
checkGn: checkGn,
checkService: checkService,
checkTs: checkTs,
checkNapi: checkNapi,
}
};
vscode.postMessage(result);
} else {
sendParamMsg2();
@ -211,26 +211,26 @@
function sendParamMsg2() {
if (chooseApi) {
var result = {
msg: "startApi"
}
msg: 'startApi'
};
} else if (chooseGn) {
var result = {
msg: "startGn"
}
msg: 'startGn'
};
} else if (chooseService) {
var result = {
msg: "startService"
}
msg: 'startService'
};
} else if (chooseTs) {
var result = {
msg: "startTs"
}
msg: 'startTs'
};
} else if (chooseNapi) {
var result = {
msg: "startNapi"
}
msg: 'startNapi'
};
} else {
console.error("ERROR!")
console.error('ERROR!');
}
vscode.postMessage(result);
}
@ -239,32 +239,32 @@
importCheck = obj.checked;
removeHighlight();
if (importCheck) {
document.getElementById("isCheckApi").style.display="";
document.getElementById("isCheckGn").style.display="";
document.getElementById("isCheckService").style.display="";
document.getElementById("isCheckTs").style.display="";
document.getElementById("isCheckNapi").style.display="";
document.getElementById('isCheckApi').style.display = '';
document.getElementById('isCheckGn').style.display = '';
document.getElementById('isCheckService').style.display = '';
document.getElementById('isCheckTs').style.display = '';
document.getElementById('isCheckNapi').style.display = '';
document.getElementById("isCheckApi").checked = false;
document.getElementById("isCheckGn").checked = false;
document.getElementById("isCheckService").checked = false;
document.getElementById("isCheckTs").checked = false;
document.getElementById("isCheckNapi").checked = false;
document.getElementById('isCheckApi').checked = false;
document.getElementById('isCheckGn').checked = false;
document.getElementById('isCheckService').checked = false;
document.getElementById('isCheckTs').checked = false;
document.getElementById('isCheckNapi').checked = false;
} else {
document.getElementById("isCheckApi").style.display="none";
document.getElementById("isCheckGn").style.display="none";
document.getElementById("isCheckService").style.display="none";
document.getElementById("isCheckTs").style.display="none";
document.getElementById("isCheckNapi").style.display="none";
document.getElementById('isCheckApi').style.display = 'none';
document.getElementById('isCheckGn').style.display = 'none';
document.getElementById('isCheckService').style.display = 'none';
document.getElementById('isCheckTs').style.display = 'none';
document.getElementById('isCheckNapi').style.display = 'none';
}
}
function chooseApiTool() {
document.getElementById("apiDescriptions").style.display="flex";
document.getElementById("gnDescriptions").style.display="none";
document.getElementById("serviceDescriptions").style.display="none";
document.getElementById("tsDescriptions").style.display="none";
document.getElementById("napiDescriptions").style.display="none";
document.getElementById('apiDescriptions').style.display = 'flex';
document.getElementById('gnDescriptions').style.display = 'none';
document.getElementById('serviceDescriptions').style.display = 'none';
document.getElementById('tsDescriptions').style.display = 'none';
document.getElementById('napiDescriptions').style.display = 'none';
chooseApi = true;
chooseGn = false;
chooseService = false;
@ -273,11 +273,11 @@
}
function chooseGnTool() {
document.getElementById("apiDescriptions").style.display="none";
document.getElementById("gnDescriptions").style.display="flex";
document.getElementById("serviceDescriptions").style.display="none";
document.getElementById("tsDescriptions").style.display="none";
document.getElementById("napiDescriptions").style.display="none";
document.getElementById('apiDescriptions').style.display = 'none';
document.getElementById('gnDescriptions').style.display = 'flex';
document.getElementById('serviceDescriptions').style.display = 'none';
document.getElementById('tsDescriptions').style.display = 'none';
document.getElementById('napiDescriptions').style.display = 'none';
chooseApi = false;
chooseGn = true;
chooseService = false;
@ -286,11 +286,11 @@
}
function chooseServiceTool() {
document.getElementById("apiDescriptions").style.display="none";
document.getElementById("gnDescriptions").style.display="none";
document.getElementById("serviceDescriptions").style.display="flex";
document.getElementById("tsDescriptions").style.display="none";
document.getElementById("napiDescriptions").style.display="none";
document.getElementById('apiDescriptions').style.display = 'none';
document.getElementById('gnDescriptions').style.display = 'none';
document.getElementById('serviceDescriptions').style.display = 'flex';
document.getElementById('tsDescriptions').style.display = 'none';
document.getElementById('napiDescriptions').style.display = 'none';
chooseApi = false;
chooseGn = false;
chooseService = true;
@ -299,11 +299,11 @@
}
function chooseTsTool() {
document.getElementById("apiDescriptions").style.display="none";
document.getElementById("gnDescriptions").style.display="none";
document.getElementById("serviceDescriptions").style.display="none";
document.getElementById("tsDescriptions").style.display="flex";
document.getElementById("napiDescriptions").style.display="none";
document.getElementById('apiDescriptions').style.display = 'none';
document.getElementById('gnDescriptions').style.display = 'none';
document.getElementById('serviceDescriptions').style.display = 'none';
document.getElementById('tsDescriptions').style.display = 'flex';
document.getElementById('napiDescriptions').style.display = 'none';
chooseApi = false;
chooseGn = false;
chooseService = false;
@ -312,11 +312,11 @@
}
function chooseNapiTool() {
document.getElementById("apiDescriptions").style.display="none";
document.getElementById("gnDescriptions").style.display="none";
document.getElementById("serviceDescriptions").style.display="none";
document.getElementById("tsDescriptions").style.display="none";
document.getElementById("napiDescriptions").style.display="flex";
document.getElementById('apiDescriptions').style.display = 'none';
document.getElementById('gnDescriptions').style.display = 'none';
document.getElementById('serviceDescriptions').style.display = 'none';
document.getElementById('tsDescriptions').style.display = 'none';
document.getElementById('napiDescriptions').style.display = 'flex';
chooseApi = false;
chooseGn = false;
chooseService = false;
@ -330,18 +330,18 @@
highlight(element);
}
if (obj === "isChooseApi") {
if (obj === 'isChooseApi') {
chooseApiTool();
} else if (obj === "isChooseGn") {
} else if (obj === 'isChooseGn') {
chooseGnTool();
} else if (obj === "isChooseService") {
} else if (obj === 'isChooseService') {
chooseServiceTool();
} else if (obj === "isChooseTs") {
} else if (obj === 'isChooseTs') {
chooseTsTool();
} else if (obj === "isChooseNapi") {
} else if (obj === 'isChooseNapi') {
chooseNapiTool();
} else {
console.error("ERROR!")
console.error('ERROR!');
}
}
@ -354,23 +354,23 @@
}
function checkTool(obj, name) {
if (name === "isCheckApi") {
let image = document.getElementById("isChooseApi")
if (name === 'isCheckApi') {
let image = document.getElementById('isChooseApi');
highlightTools(obj.checked, image);
} else if (name === "isCheckGn") {
let image = document.getElementById("isChooseGn")
} else if (name === 'isCheckGn') {
let image = document.getElementById('isChooseGn');
highlightTools(obj.checked, image);
} else if (name === "isCheckService") {
let image = document.getElementById("isChooseService")
} else if (name === 'isCheckService') {
let image = document.getElementById('isChooseService');
highlightTools(obj.checked, image);
} else if (name === "isCheckTs") {
let image = document.getElementById("isChooseTs")
} else if (name === 'isCheckTs') {
let image = document.getElementById('isChooseTs');
highlightTools(obj.checked, image);
} else if (name === "isCheckNapi") {
let image = document.getElementById("isChooseNapi")
} else if (name === 'isCheckNapi') {
let image = document.getElementById('isChooseNapi');
highlightTools(obj.checked, image);
} else {
console.error("ERROR!")
console.error('ERROR!');
}
}

View File

@ -17,13 +17,13 @@
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const fs = require('fs');
const re = require("./gen/tools/VsPluginRe");
const { VsPluginLog } = require("./gen/tools/VsPluginLog");
const re = require('./gen/tools/VsPluginRe');
const { VsPluginLog } = require('./gen/tools/VsPluginLog');
const { detectPlatform, readFile, writeFile } = require('./gen/tools/VsPluginTool');
const path = require('path');
const os = require('os');
let exeFilePath = null;
let flag = "";
let flag = '';
let isTrue = false;
let globalPanel = null;
@ -46,16 +46,16 @@ function activate(context) {
context.subscriptions.push(disposableMenu);
let platform = detectPlatform();
if (platform === 'win') {
exeFilePath = __dirname + "/gn-gen-win.exe";
exeFilePath = __dirname + '/gn-gen-win.exe';
} else if (platform === 'mac') {
exeFilePath = __dirname + "/gn-gen-macos";
exeFilePath = __dirname + '/gn-gen-macos';
} else if (platform === 'Linux') {
exeFilePath = __dirname + "/gn-gen-linux";
exeFilePath = __dirname + '/gn-gen-linux';
}
vscode.window.onDidChangeActiveColorTheme(colorTheme => {
let result = {
msg: "colorThemeChanged"
}
msg: 'colorThemeChanged'
};
globalPanel.webview.postMessage(result);
});
}
@ -69,28 +69,29 @@ function gnexecutor(outputCodeDir, originCodeDir, inputScriptDir, scriptType, tr
maxBuffer: 1024 * 1024 * 20
},
function (error, stdout, stderr) {
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 !== undefined) ?
error : "") + stdout);
return VsPluginLog.logError("VsPlugin:" + error + stdout);
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 !== undefined) ?
error : '') + stdout);
return VsPluginLog.logError('VsPlugin:' + error + stdout);
}
vscode.window.showInformationMessage("Generated successfully");
vscode.window.showInformationMessage('Generated successfully');
return '';
});
}
function genGnCommand(outputCodeDir, originCodeDir, inputScriptDir, scriptType,
transplantDir, subsystemName, componentName, compileOptions) {
let command = exeFilePath + " -o " + outputCodeDir + " -p " + originCodeDir + " -f " + inputScriptDir
+ " -t " + scriptType + " -s " + subsystemName + " -m " + componentName + " -d " + transplantDir;
if (compileOptions != "") {
command += " -a " + "\"" + compileOptions + "\"";
let command = exeFilePath + ' -o ' + outputCodeDir + ' -p ' + originCodeDir + ' -f ' + inputScriptDir +
' -t ' + scriptType + ' -s ' + subsystemName + ' -m ' + componentName + ' -d ' + transplantDir;
if (compileOptions != '') {
command += ' -a ' + '\'' + compileOptions + '\'';
}
command = re.replaceAll(command, '\\\\', '/');
console.log("command = " + command)
console.log('command = ' + command);
return command;
}
@ -134,9 +135,9 @@ function register(context, command) {
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);
@ -145,11 +146,11 @@ function register(context, command) {
// 路径有效性判断
if (uri.fsPath !== undefined) {
let fn = re.getFileInPath(uri.fsPath);
let tt = re.match("([a-zA-Z_0-9]+.[a-zA-Z_0-9])", fn);
let tt = re.match('([a-zA-Z_0-9]+.[a-zA-Z_0-9])', fn);
let result = {
msg: "selectinputScriptDir",
path: tt ? uri.fsPath : ""
}
msg: 'selectinputScriptDir',
path: tt ? uri.fsPath : ''
};
globalPanel.webview.postMessage(result);
}
});
@ -202,15 +203,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;
@ -240,12 +241,12 @@ function startNextPlugin() {
if (message.mode !== undefined && message.mode !== null) {
mode = message.mode;
}
flag = flag === "" ? '' : flag;
flag = flag === '' ? '' : flag;
const options = {
canSelectMany: false,//是否可以选择多个
canSelectFiles: mode === 0 ? true : false,//是否选择文件
canSelectFolders: mode === 0 ? false : true,//是否选择文件夹
defaultUri:vscode.Uri.file(flag),//默认打开本地路径
canSelectMany: false, //是否可以选择多个
canSelectFiles: mode === 0 ? true : false, //是否选择文件
canSelectFolders: mode === 0 ? false : true, //是否选择文件夹
defaultUri:vscode.Uri.file(flag), //默认打开本地路径
filters: {
'All files': ['*']
}
@ -254,72 +255,74 @@ function startNextPlugin() {
return vscode.window.showOpenDialog(options).then(fileUri => {
if (fileUri && fileUri[0]) {
console.log('Selected file: ' + fileUri[0].fsPath);
let filePath = "";
let filePath = '';
filePath = fileUri[0].fsPath.concat(',');
filePath = re.replaceAll(filePath, '\\\\', '/');
if (filePath.substring(1,2) === ":") {
let filePathTemp = filePath.substring(0,1).toUpperCase()
filePath = filePathTemp + filePath.substring(1,filePath.length)
if (filePath.substring(1, 2) === ':') {
let filePathTemp = filePath.substring(0, 1).toUpperCase();
filePath = filePathTemp + filePath.substring(1, filePath.length);
}
let result = {
msg: message.msg,
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 fileTempName = 'out';
let pos = flag.indexOf(fileTempName);
flag = flag.substr(0,pos-1);
flag = flag.substr(0, pos - 1);
isTrue = true;
}
panel.webview.postMessage(result);
return fileUri[0].fsPath
return fileUri[0].fsPath;
} else {
return '';
}
});
}
function checkMode(outputCodeDir, originCodeDir, inputScriptDir, scriptType,
transplantDir, subsystemName, componentName, compileOptions) {
outputCodeDir = re.replaceAll(outputCodeDir, " ", "");
if ("" === outputCodeDir) {
vscode.window.showErrorMessage("Please enter the outputCodeDir path!");
outputCodeDir = re.replaceAll(outputCodeDir, ' ', '');
if ('' === outputCodeDir) {
vscode.window.showErrorMessage('Please enter the outputCodeDir path!');
return;
}
originCodeDir = re.replaceAll(originCodeDir, " ", "");
if ("" === originCodeDir) {
vscode.window.showErrorMessage("Please enter the originCodeDir path!");
originCodeDir = re.replaceAll(originCodeDir, ' ', '');
if ('' === originCodeDir) {
vscode.window.showErrorMessage('Please enter the originCodeDir path!');
return;
}
inputScriptDir = re.replaceAll(inputScriptDir, " ", "");
if ("" === inputScriptDir) {
vscode.window.showErrorMessage("Please enter the inputScriptDir path!");
inputScriptDir = re.replaceAll(inputScriptDir, ' ', '');
if ('' === inputScriptDir) {
vscode.window.showErrorMessage('Please enter the inputScriptDir path!');
return;
}
if (inputScriptDir.indexOf(".") < 0) {
vscode.window.showErrorMessage("Please enter the correct file path!");
if (inputScriptDir.indexOf('.') < 0) {
vscode.window.showErrorMessage('Please enter the correct file path!');
return;
}
transplantDir = re.replaceAll(transplantDir, " ", "");
if ("" === transplantDir) {
vscode.window.showErrorMessage("Please enter the transplantDir path!");
transplantDir = re.replaceAll(transplantDir, ' ', '');
if ('' === transplantDir) {
vscode.window.showErrorMessage('Please enter the transplantDir path!');
return;
}
subsystemName = re.replaceAll(subsystemName, " ", "");
if ("" === subsystemName) {
vscode.window.showErrorMessage("Please enter the subsystemName!");
subsystemName = re.replaceAll(subsystemName, ' ', '');
if ('' === subsystemName) {
vscode.window.showErrorMessage('Please enter the subsystemName!');
return;
}
componentName = re.replaceAll(componentName, " ", "");
if ("" === componentName) {
vscode.window.showErrorMessage("Please enter the componentName!");
componentName = re.replaceAll(componentName, ' ', '');
if ('' === componentName) {
vscode.window.showErrorMessage('Please enter the componentName!');
return;
}
if (exeFileExit()) {
gnexecutor(outputCodeDir, originCodeDir, inputScriptDir, scriptType,
transplantDir, subsystemName, componentName, compileOptions);
} else {
vscode.window.showInformationMessage("Copy executable program to " + __dirname);
vscode.window.showInformationMessage('Copy executable program to ' + __dirname);
}
}
@ -341,10 +344,10 @@ function getWebViewContent(context, templatePath) {
const dirPath = path.dirname(reoriginCodeDir);
let html = fs.readFileSync(reoriginCodeDir, '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+'"';
return $1 + $2 + '"';
}
});
return html;
@ -353,4 +356,4 @@ function getWebViewContent(context, templatePath) {
module.exports = {
activate,
deactivate
}
};

View File

@ -23,10 +23,10 @@ VsPluginLog.LEV_ERROR = 1;
VsPluginLog.LEV_DEBUG = 2;
VsPluginLog.LEV_INFO = 3;
const LEV_STR = ["[NON]", "[ERR]", "[DBG]", "[INF]"]
const LEV_STR = ['[NON]', '[ERR]', '[DBG]', '[INF]'];
var logLevel = VsPluginLog.LEV_ERROR;
var logFileName = null;
var logResultMessage = [true, ""]
var logResultMessage = [true, ''];
function getDateString() {
let nowDate = new Date();
@ -35,7 +35,7 @@ function getDateString() {
function saveLog(dateStr, levStr, detail) {
if (logFileName) {
let logStr = dateStr + " " + levStr + " " + detail + "\n";
let logStr = dateStr + ' ' + levStr + ' ' + detail + '\n';
fs.appendFileSync(logFileName, logStr);
}
}
@ -43,36 +43,38 @@ function saveLog(dateStr, levStr, detail) {
VsPluginLog.init = function (level, fileName) {
logLevel = level in [VsPluginLog.LEV_NONE, VsPluginLog.LEV_ERROR, VsPluginLog.LEV_DEBUG, VsPluginLog.LEV_INFO]
? level : VsPluginLog.LEV_ERROR;
logFileName = fileName ? fileName : "napi_generator.log";
}
logFileName = fileName ? fileName : 'napi_generator.log';
};
function recordLog(lev, ...args) {
let dataStr = getDateString();
let detail = args.join(" ");
let detail = args.join(' ');
saveLog(dataStr, LEV_STR[lev], detail);
if (lev == VsPluginLog.LEV_ERROR) {
logResultMessage = [false, detail];
}
if (logLevel < lev) return;
if (logLevel < lev) {
return;
}
VsPluginLog.logInfo(dataStr + LEV_STR[lev] + detail);
}
VsPluginLog.logError = function (...args) {
recordLog(VsPluginLog.LEV_ERROR, args);
}
};
VsPluginLog.logDebug = function (...args) {
recordLog(VsPluginLog.LEV_DEBUG, args);
}
};
VsPluginLog.logInfo = function (...args) {
recordLog(VsPluginLog.LEV_INFO, args);
}
};
VsPluginLog.getResult = function () {
return logResultMessage;
}
};
module.exports = {
VsPluginLog
}
};