From 9f5c61e1bf5cc77c2700c68d56a673d633588178 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 09:59:02 +0800 Subject: [PATCH 01/26] =?UTF-8?q?"modifile=20src/cli/cmake2gn/src/main.js?= =?UTF-8?q?=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/cmake2gn/src/main.js | 38 ++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/cli/cmake2gn/src/main.js b/src/cli/cmake2gn/src/main.js index f6fc4ec4..88dac5d0 100644 --- a/src/cli/cmake2gn/src/main.js +++ b/src/cli/cmake2gn/src/main.js @@ -12,15 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const path = require("path"); -const stdio = require("stdio"); -const { AnalyzeCMake } = require("./src/analyze_cmake"); -const { AnalyzeMake } = require("./src/analyze_make"); -const { GenerateGn } = require("./src/generate_gn"); -const { Logger } = require("./src/logger"); -const { Tool } = require("./src/tool"); +const path = require('path'); +const stdio = require('stdio'); +const { AnalyzeCMake } = require('./src/analyze_cmake'); +const { AnalyzeMake } = require('./src/analyze_make'); +const { GenerateGn } = require('./src/generate_gn'); +const { Logger } = require('./src/logger'); +const { Tool } = require('./src/tool'); -if (process.execPath.endsWith("node") || process.execPath.endsWith("node.exe")) { +if (process.execPath.endsWith('node') || process.execPath.endsWith('node.exe')) { Tool.CURRENT_TOOL_PATH = __dirname;//工具目录,用来找到res内资源 } else { @@ -32,21 +32,21 @@ if (Tool.MOCK_TYPE == Tool.MOCK_ENUM.MOCK_RUN) { } let ops = stdio.getopt({ - 'type': { key: 't', args: 1, description: "", default: "cmake" }, + 'type': { key: 't', args: 1, description: '', default: 'cmake' }, 'filename': { key: 'f', args: 1, description: "The make file's relative path \ ( third_party/opencv/CMakeLists.txt , make file can be Makefile/CMakeLists.txt)" }, 'ohos_product_output': { - key: 'o', args: 1, description: "ohos product output relative path", - default: "out/rk3568" + key: 'o', args: 1, description: 'ohos product output relative path', + default: 'out/rk3568' }, - 'ohos_project_path': { key: 'p', args: 1, description: "ohos project path ( /home/xxx/ohos_project )" }, - 'cmake_args': { key: 'a', args: 1, description: "like: (-DABC,-DQWE)", default: "" }, - 'subsystem_name': { key: 's', args: 1, description: "subsystem", default: "test_subsystem" }, - 'part_name': { key: 'm', args: 1, description: "part", default: "test_part" }, - 'porting_to': { key: 'd', args: 1, description: "porting to", default: "" }, + 'ohos_project_path': { key: 'p', args: 1, description: 'ohos project path ( /home/xxx/ohos_project )' }, + 'cmake_args': { key: 'a', args: 1, description: 'like: (-DABC,-DQWE)', default: '' }, + 'subsystem_name': { key: 's', args: 1, description: 'subsystem', default: 'test_subsystem' }, + 'part_name': { key: 'm', args: 1, description: 'part', default: 'test_part' }, + 'porting_to': { key: 'd', args: 1, description: 'porting to', default: '' }, }); Tool.OHOS_PROJECT_PATH = ops.ohos_project_path; @@ -62,12 +62,12 @@ Tool.OHOS_PART_NAME = ops.part_name; let compileFile = path.parse(path.join(Tool.OHOS_PROJECT_PATH, ops.filename)); -if (ops.type == "cmake") {//cmake +if (ops.type == 'cmake') {//cmake AnalyzeCMake.analyze(compileFile, ops.cmake_args.substring(1, ops.cmake_args.length - 1)); } -else if (ops.type == "make") {//make +else if (ops.type == 'make') {//make AnalyzeMake.analyze(compileFile); } else { - Logger.err("not support " + ops.filename); + Logger.err('not support ' + ops.filename); } -- Gitee From 44521921cb8f12f693fe6e93c6d4158251f119c2 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 09:59:29 +0800 Subject: [PATCH 02/26] =?UTF-8?q?"modifile=20src/cli/cmake2gn/src/src/anal?= =?UTF-8?q?yze=5Fcmake.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/cmake2gn/src/src/analyze_cmake.js | 48 +++++++++++------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/src/cli/cmake2gn/src/src/analyze_cmake.js b/src/cli/cmake2gn/src/src/analyze_cmake.js index bcc4ddc4..cf07f876 100644 --- a/src/cli/cmake2gn/src/src/analyze_cmake.js +++ b/src/cli/cmake2gn/src/src/analyze_cmake.js @@ -12,12 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const path = require("path"); -const { Logger } = require("./logger"); -const { Tool } = require("./tool"); -const childProcess = require("child_process"); -const fs = require("fs"); -const { AnalyzeMake } = require("./analyze_make"); +const path = require('path'); +const { Logger } = require('./logger'); +const { Tool } = require('./tool'); +const childProcess = require('child_process'); +const fs = require('fs'); +const { AnalyzeMake } = require('./analyze_make'); class AnalyzeCMake { constructor() { @@ -25,11 +25,11 @@ class AnalyzeCMake { } static mkdirBuildTemp(compileFile){ let buildTmp; - if(Tool.OHOS_PORTING_TO==""){ - buildTmp = path.join(compileFile.dir, "build_tmp");//cmake编译的临时目录 + if(Tool.OHOS_PORTING_TO==''){ + buildTmp = path.join(compileFile.dir, 'build_tmp');//cmake编译的临时目录 } else{ - buildTmp = path.join(Tool.OHOS_PROJECT_PATH,Tool.OHOS_PORTING_TO, "build_tmp");//cmake编译的临时目录 + buildTmp = path.join(Tool.OHOS_PROJECT_PATH,Tool.OHOS_PORTING_TO, 'build_tmp');//cmake编译的临时目录 } if (fs.existsSync(buildTmp)) { fs.rmSync(buildTmp, { recursive: true, force: true });//🌻 @@ -38,32 +38,32 @@ class AnalyzeCMake { } static analyze(compileFile, cmakeArgs) {//在工程目录创建一个buildTmp目录,执行cmake初始化工程,执行make得到命令行序列 - if (!fs.existsSync(path.join(Tool.OHOS_PROJECT_PATH, Tool.OHOS_PRODUCT_OUTPUT_PATH, "build.ninja"))) { - Logger.err("param ohos need to looks like out/rk3568"); + if (!fs.existsSync(path.join(Tool.OHOS_PROJECT_PATH, Tool.OHOS_PRODUCT_OUTPUT_PATH, 'build.ninja'))) { + Logger.err('param ohos need to looks like out/rk3568'); return; } let buildTmp = AnalyzeCMake.mkdirBuildTemp(compileFile); fs.mkdirSync(buildTmp); Tool.pushd(buildTmp); let ohosToolchainCmake = Tool.getCMakeToolchain(); - let ohosToolchainCmakeData = fs.readFileSync(ohosToolchainCmake, { encoding: "utf8" }); - while (ohosToolchainCmakeData.indexOf("CC_REPLACE_OHOS_ROOT") >= 0) { - ohosToolchainCmakeData = ohosToolchainCmakeData.replace("CC_REPLACE_OHOS_ROOT", + let ohosToolchainCmakeData = fs.readFileSync(ohosToolchainCmake, { encoding: 'utf8' }); + while (ohosToolchainCmakeData.indexOf('CC_REPLACE_OHOS_ROOT') >= 0) { + ohosToolchainCmakeData = ohosToolchainCmakeData.replace('CC_REPLACE_OHOS_ROOT', Tool.swapPath(Tool.OHOS_PROJECT_PATH, true)); } - while (ohosToolchainCmakeData.indexOf("CC_REPLACE_OHOS_TARGET") >= 0) { - ohosToolchainCmakeData = ohosToolchainCmakeData.replace("CC_REPLACE_OHOS_TARGET", + while (ohosToolchainCmakeData.indexOf('CC_REPLACE_OHOS_TARGET') >= 0) { + ohosToolchainCmakeData = ohosToolchainCmakeData.replace('CC_REPLACE_OHOS_TARGET', Tool.OHOS_PRODUCT_OUTPUT_PATH); } - ohosToolchainCmake = path.join(buildTmp, "ohos.toolchain.cmake"); + ohosToolchainCmake = path.join(buildTmp, 'ohos.toolchain.cmake'); fs.writeFileSync(ohosToolchainCmake, ohosToolchainCmakeData); ohosToolchainCmake=Tool.swapPath(ohosToolchainCmake); let args = [compileFile.dir, - "-DCMAKE_TOOLCHAIN_FILE=%s".format(ohosToolchainCmake),"-G","Unix Makefiles", - "-DCMAKE_MAKE_PROGRAM=%s".format(Tool.swapPath(Tool.getMakeRaw())), + '-DCMAKE_TOOLCHAIN_FILE=%s'.format(ohosToolchainCmake),'-G','Unix Makefiles', + '-DCMAKE_MAKE_PROGRAM=%s'.format(Tool.swapPath(Tool.getMakeRaw())), ]; if (cmakeArgs.length > 0) { - args.push(...cmakeArgs.split(",")); + args.push(...cmakeArgs.split(',')); } let ret = childProcess.spawn(Tool.swapPath(Tool.getCMake()), args); ret.stdout.on('data', (data) => { @@ -74,14 +74,14 @@ class AnalyzeCMake { }); ret.on('close', (code) => { if (code == 0) { - Logger.info("------------------------cmake ok"); - AnalyzeMake.analyze(path.join(buildTmp, "Makefile")); //调用make生成命令行 + Logger.info('------------------------cmake ok'); + AnalyzeMake.analyze(path.join(buildTmp, 'Makefile')); //调用make生成命令行 } - else Logger.err("cmake fail"); + else Logger.err('cmake fail'); }); } } module.exports = { AnalyzeCMake -}; \ No newline at end of file +} \ No newline at end of file -- Gitee From fb500fc30723a3ca7d752d7f40836060590abac0 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:00:21 +0800 Subject: [PATCH 03/26] =?UTF-8?q?"modifile=20src/cli/cmake2gn/src/src/anal?= =?UTF-8?q?yze=5Fcommand.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/cmake2gn/src/src/analyze_command.js | 324 ++++++++++---------- 1 file changed, 162 insertions(+), 162 deletions(-) diff --git a/src/cli/cmake2gn/src/src/analyze_command.js b/src/cli/cmake2gn/src/src/analyze_command.js index 993f8c1f..3d5fb095 100644 --- a/src/cli/cmake2gn/src/src/analyze_command.js +++ b/src/cli/cmake2gn/src/src/analyze_command.js @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { Logger } = require("./logger"); -const fs = require("fs"); -const path = require("path"); -const { Tool } = require("./tool"); +const { Logger } = require('./logger'); +const fs = require('fs'); +const path = require('path'); +const { Tool } = require('./tool'); class AnalyzeCommand { constructor() { @@ -23,27 +23,27 @@ class AnalyzeCommand { } static isCmd(cmd, name) { - let cmdName = cmd.split(" ")[0]; + let cmdName = cmd.split(' ')[0]; let v1 = cmdName.endsWith(name); - let v2 = cmdName.endsWith(name + ".exe"); + let v2 = cmdName.endsWith(name + '.exe'); return v1 || v2; } static COMPILE_CMDS = { - "clang": 0, - "ar": 1, - "clang++": 2 + 'clang': 0, + 'ar': 1, + 'clang++': 2 }; static COLLECT_COMMANDS = []; static storeCommands() { - fs.writeFileSync(path.join(Tool.CURRENT_TOOL_PATH, "cmds.txt"), - AnalyzeCommand.COLLECT_COMMANDS.join("\n"), { encoding: "utf8" }); + fs.writeFileSync(path.join(Tool.CURRENT_TOOL_PATH, 'cmds.txt'), + AnalyzeCommand.COLLECT_COMMANDS.join('\n'), { encoding: 'utf8' }); } static getCompileCmdId(cmd) { - let cmdName = cmd.split(" ")[0]; + let cmdName = cmd.split(' ')[0]; for (let c in AnalyzeCommand.COMPILE_CMDS) { - if (cmdName.endsWith(c) || cmdName.endsWith(c + ".exe")) { + if (cmdName.endsWith(c) || cmdName.endsWith(c + '.exe')) { return AnalyzeCommand.COMPILE_CMDS[c];//返回命令ID } } @@ -51,8 +51,8 @@ class AnalyzeCommand { } static analyze(cmd) { let cmds; - if (cmd.indexOf("&&") >= 0) { - cmds = cmd.split("&&"); + if (cmd.indexOf('&&') >= 0) { + cmds = cmd.split('&&'); } else { cmds = [cmd]; @@ -69,19 +69,19 @@ class AnalyzeCommand { return result; } static exAnalyzeCmake(cmd) { - let ss = cmd.split(" "); - if (ss.indexOf("-P") > 0) {//需要 cmake执行脚本,在这里直接执行 or 移到BUILD.gn里面执行 - const childProcess = require("child_process"); + let ss = cmd.split(' '); + if (ss.indexOf('-P') > 0) {//需要 cmake执行脚本,在这里直接执行 or 移到BUILD.gn里面执行 + const childProcess = require('child_process'); childProcess.execSync(cmd); AnalyzeCommand.COLLECT_COMMANDS.push(cmd); return false; } - let cmakeLinkScriptOffset = ss.indexOf("cmake_link_script"); + let cmakeLinkScriptOffset = ss.indexOf('cmake_link_script'); if (cmakeLinkScriptOffset >= 0) {//需要 这里可能要做一些错误判断 let cmakeLinkScriptFile = ss[cmakeLinkScriptOffset + 1]; let cmakeLinkScriptData = fs.readFileSync(path.join(process.cwd(), cmakeLinkScriptFile), - { encoding: "utf8" }); - let cmds = cmakeLinkScriptData.split("\n");//link.txt中可能有多条命令链接 + { encoding: 'utf8' }); + let cmds = cmakeLinkScriptData.split('\n');//link.txt中可能有多条命令链接 let rets = []; for (let c of cmds) { let r = AnalyzeCommand.analyzeOneCmd(c); @@ -99,53 +99,53 @@ class AnalyzeCommand { return false; } static isCmdScriptWithVersion(cmd, cmdType) { - let cmdName = cmd.split(" ")[0]; - let pos = cmdName.lastIndexOf("/"); + let cmdName = cmd.split(' ')[0]; + let pos = cmdName.lastIndexOf('/'); let scrType = cmdName.substring(pos + 1, cmdName.length); return scrType.startsWith(cmdType); } static analyzeOneCmd(cmd) { - while (cmd.startsWith("\n") || cmd.startsWith(" ")) { + while (cmd.startsWith('\n') || cmd.startsWith(' ')) { cmd = cmd.substring(1); } if (cmd.length <= 0) { return false; } - if (cmd.match("^make(\\[\\d+\\]:)|: (Entering)|(Leaving) directory")) {//跳过进出目录的log + if (cmd.match('^make(\\[\\d+\\]:)|: (Entering)|(Leaving) directory')) {//跳过进出目录的log //需要 改变工作目录 return false; } - if (cmd.startsWith("cd ")) { + if (cmd.startsWith('cd ')) { let t = AnalyzeCommand.splitString(cmd); Tool.pushd(t[1]);//改变工作目录 return false; } - if (AnalyzeCommand.isCmd(cmd, "ccache")) {//去掉ccache头 - cmd = cmd.substring(cmd.indexOf("ccache") + "ccache".length); + if (AnalyzeCommand.isCmd(cmd, 'ccache')) {//去掉ccache头 + cmd = cmd.substring(cmd.indexOf('ccache') + 'ccache'.length); return AnalyzeCommand.analyzeOneCmd(cmd); } - if (AnalyzeCommand.isCmd(cmd, "cmake")) {//跳过cmake的log,需要解析link命令行 + if (AnalyzeCommand.isCmd(cmd, 'cmake')) {//跳过cmake的log,需要解析link命令行 return AnalyzeCommand.exAnalyzeCmake(cmd); } - if (AnalyzeCommand.isCmd(cmd, "make") || - AnalyzeCommand.isCmd(cmd, "ranlib")) {//跳过这些命令 + if (AnalyzeCommand.isCmd(cmd, 'make') || + AnalyzeCommand.isCmd(cmd, 'ranlib')) {//跳过这些命令 return false; } if (AnalyzeCommand.getCompileCmdId(cmd) >= 0) {//解析编译命令行 AnalyzeCommand.COLLECT_COMMANDS.push(cmd); return [AnalyzeCommand.analyzeCompileCommand(cmd)]; } - if (AnalyzeCommand.isCmd(cmd, "perl") || - AnalyzeCommand.isCmd(cmd, "autoreconf") || - AnalyzeCommand.isCmdScriptWithVersion(cmd, "python")) { + if (AnalyzeCommand.isCmd(cmd, 'perl') || + AnalyzeCommand.isCmd(cmd, 'autoreconf') || + AnalyzeCommand.isCmdScriptWithVersion(cmd, 'python')) { // 需要即时执行(可能会生成依赖源文件),如果不执行,后续编译命令可能会报错,找不到源文件 Logger.info(cmd); - const childProcess = require("child_process"); + const childProcess = require('child_process'); childProcess.execSync(cmd); return false; } - Logger.err("未解析的命令行:" + cmd); + Logger.err('未解析的命令行:' + cmd); return false; } @@ -153,26 +153,26 @@ class AnalyzeCommand { return { type: 0,//0 compile command,1 other command workDir: process.cwd(), - command: "", + command: '', inputs: [], - target: "", + target: '', isLink: false,//是否编译,.a/.o/可执行程序,需要生成目标 includes: [], defines: [ - "_XOPEN_SOURCE=600",//ohos的编译环境缺失宏 - "FE_TONEAREST=0x00000000", - "FE_UPWARD=0x00400000", - "FE_DOWNWARD=0x00800000", - "FE_TOWARDZERO=0x00c00000", + '_XOPEN_SOURCE=600',//ohos的编译环境缺失宏 + 'FE_TONEAREST=0x00000000', + 'FE_UPWARD=0x00400000', + 'FE_DOWNWARD=0x00800000', + 'FE_TOWARDZERO=0x00c00000', ], cflags: [ - "-Wno-implicit-function-declaration", - "-Wno-unused-function", - "-Wno-comments",//允许注释后面有个\ - "-Wno-string-conversion",//允许char*当做bool使用 - "-Wno-header-hygiene",//不检测命名空间污染 - "-frtti",//支持typeid(xxx) - "-fexceptions",//支持try catch + '-Wno-implicit-function-declaration', + '-Wno-unused-function', + '-Wno-comments',//允许注释后面有个\ + '-Wno-string-conversion',//允许char*当做bool使用 + '-Wno-header-hygiene',//不检测命名空间污染 + '-frtti',//支持typeid(xxx) + '-fexceptions',//支持try catch ],//c和c++选项 cflagsCc: [],//c++选项 cflagsC: [],//c选项 @@ -184,7 +184,7 @@ class AnalyzeCommand { let startp = -1; let isContinuChar = 0; for (let p = 0; p < s.length; p++) { - if (s[p] == "\"" && s[p-1] != "\\") { + if (s[p] == '\"' && s[p-1] != '\\') { isContinuChar = 1 - isContinuChar; } if (startp >= 0) { @@ -205,45 +205,45 @@ class AnalyzeCommand { static mockTarget(t) { if (t.target) { - fs.writeFileSync(t.target, " "); + fs.writeFileSync(t.target, ' '); } } static clangCheck1(e) { - let ss = ["--sysroot=", - "-pthread", - "-Qunused-arguments", - "-ffunction-sections", - "-fdata-sections", - "-fvisibility=hidden", - "-fvisibility-inlines-hidden", - "-O3", - "-Os", - "-fPIC", - "-pedantic", - "-fwrapv", - "-shared", - "-lm", - "-lpthread", - "-lz", - "-MD", - "-isystem" + let ss = ['--sysroot=', + '-pthread', + '-Qunused-arguments', + '-ffunction-sections', + '-fdata-sections', + '-fvisibility=hidden', + '-fvisibility-inlines-hidden', + '-O3', + '-Os', + '-fPIC', + '-pedantic', + '-fwrapv', + '-shared', + '-lm', + '-lpthread', + '-lz', + '-MD', + '-isystem' ]; for (let s of ss) { - if (e.startsWith(s) || e == "-w") { + if (e.startsWith(s) || e == '-w') { return true; } } return false; } static clangCheck2(local, e) { - if (e.startsWith("-MT") || e.startsWith("-MF")) { + if (e.startsWith('-MT') || e.startsWith('-MF')) { if (e.length == 3) { local.p++; } return true; } - if (e.startsWith("-s")) { + if (e.startsWith('-s')) { if (e.length == 2) { local.p++; } @@ -252,7 +252,7 @@ class AnalyzeCommand { return false; } static clangCheck3(local, e) { - if (e.startsWith("-D")) {//需要记录到defines里面的参数 + if (e.startsWith('-D')) {//需要记录到defines里面的参数 //需要 是否-D开头的,全部记录到defines里面 if (e.length == 2) {//-D xxx local.ret.defines.push(local.eles[local.p++]); @@ -265,7 +265,7 @@ class AnalyzeCommand { return false; } static clangCheck4(local, e) { - if (e.startsWith("-I")) {//需要记录到includes的参数 + if (e.startsWith('-I')) {//需要记录到includes的参数 if (e.length == 2) {//-I xxx local.ret.includes.push(local.eles[local.p++]); } @@ -285,23 +285,23 @@ class AnalyzeCommand { return false; } static clangCheck5(local, e) { - if (this.validCFlag(e, Tool.getAllowedC().compileflag) || (e == "-D__clang__")) { + if (this.validCFlag(e, Tool.getAllowedC().compileflag) || (e == '-D__clang__')) { local.ret.cflags.push(e); //需要记录到flags里面的参数 return true; } return false; } static clangCheck6(local, e) { - if (e == "-o") { + if (e == '-o') { if (e.length == 2) {//-o xxx local.ret.target = local.eles[local.p++]; } else {//-oxxx local.ret.target = e.substring(2); } - if (local.ret.target.endsWith(".a") || - local.ret.target.endsWith(".so") || - (!e.endsWith(".c") && !e.endsWith(".o"))) { + if (local.ret.target.endsWith('.a') || + local.ret.target.endsWith('.so') || + (!e.endsWith('.c') && !e.endsWith('.o'))) { local.ret.isLink = true; } return true; @@ -314,14 +314,14 @@ class AnalyzeCommand { local.ret.inputs.push(e); return true; } - if (e.endsWith(".rsp")) { + if (e.endsWith('.rsp')) { console.log(Tool.CURRENT_DIR); let rspth = path.join(Tool.CURRENT_DIR, e.substring(1)); - let data = fs.readFileSync(rspth, { encoding: "utf8" }); - if (data.endsWith("\r\n")) { + let data = fs.readFileSync(rspth, { encoding: 'utf8' }); + if (data.endsWith('\r\n')) { data = data.substring(0, data.length - 2); } - let datas = data.split(" "); + let datas = data.split(' '); for (let d of datas) { for (let s of ss) { if (d.endsWith(s)) { @@ -343,40 +343,40 @@ class AnalyzeCommand { while (local.p < local.eles.length) { let e = local.eles[local.p++]; - if (e.endsWith("clang") || e.endsWith("clang.exe")) { + if (e.endsWith('clang') || e.endsWith('clang.exe')) { local.ret.command = e; } else if (AnalyzeCommand.clangCheck1(e)) { } else if (AnalyzeCommand.clangCheck2(local, e)) { } - else if (e.startsWith("-Wl,--dynamic-linker,") || e.startsWith("-rdynamic")) {//-----直接忽略的链接参数 + else if (e.startsWith('-Wl,--dynamic-linker,') || e.startsWith('-rdynamic')) {//-----直接忽略的链接参数 local.ret.isLink = true; } else if (AnalyzeCommand.clangCheck3(local, e)) { } else if (AnalyzeCommand.clangCheck4(local, e)) { } else if (AnalyzeCommand.clangCheck5(local, e)) { } - else if (e.startsWith("-std=")) { + else if (e.startsWith('-std=')) { local.ret.cflagsCc.push(e); } - else if (e.startsWith("-W")) {//需要 -W开头的怎么处理,-W -Wall -Werror=return-type -Wno-unnamed-type-template-args - if (e.startsWith("-Wno-")) { + else if (e.startsWith('-W')) {//需要 -W开头的怎么处理,-W -Wall -Werror=return-type -Wno-unnamed-type-template-args + if (e.startsWith('-Wno-')) { local.ret.cflags.push(e); } } else if (AnalyzeCommand.clangCheck6(local, e)) { } - else if (e == "-c") {//编译 + else if (e == '-c') {//编译 local.ret.isLink = false; } else if (AnalyzeCommand.clangCheck7(local, e)) { } else { - Logger.err(cmd + "\nclang未解析参数 " + e); + Logger.err(cmd + '\nclang未解析参数 ' + e); process.exit(); } } - Logger.info("----clang-----" + local.ret.workDir + "\n\t" + local.ret.isLink + "," + local.ret.target); + Logger.info('----clang-----' + local.ret.workDir + '\n\t' + local.ret.isLink + ',' + local.ret.target); return local.ret; } static analyzeCcAr(cmd) { - if (cmd.endsWith("\r")) { + if (cmd.endsWith('\r')) { cmd = cmd.substring(0, cmd.length - 1); } let ret = AnalyzeCommand.resultTemplete(); @@ -385,61 +385,61 @@ class AnalyzeCommand { let p = 0; while (p < eles.length) { let e = eles[p++]; - if (e.endsWith("ar") || e.endsWith("ar.exe")) { + if (e.endsWith('ar') || e.endsWith('ar.exe')) { ret.command = e; } - else if (e.endsWith(".a")) { + else if (e.endsWith('.a')) { ret.target = e; } - else if (e.endsWith(".o")) { + else if (e.endsWith('.o')) { ret.inputs.push(e); } - else if (e == "qc") { + else if (e == 'qc') { } else { - Logger.err(cmd + "\nar未解析参数 " + e); + Logger.err(cmd + '\nar未解析参数 ' + e); process.exit(); } } - Logger.info("---ar----" + ret.workDir + "\n\t" + ret.isLink + "," + ret.target); + Logger.info('---ar----' + ret.workDir + '\n\t' + ret.isLink + ',' + ret.target); return ret; } static clangxxCheck1(e) { - let ss = ["--sysroot=", - "-pthread", - "-Qunused-arguments", - "-ffunction-sections", - "-fdata-sections", - "-fvisibility=hidden", - "-fvisibility-inlines-hidden", - "-funwind-tables", - "-fwrapv", - "-O3", - "-fPIC", - "-shared", - "-ldl", - "-lm", - "-lpthread", - "-lrt", - "-fPIE", - "-g", - "-ftemplate-depth=1024", - "-pedantic-errors" + let ss = ['--sysroot=', + '-pthread', + '-Qunused-arguments', + '-ffunction-sections', + '-fdata-sections', + '-fvisibility=hidden', + '-fvisibility-inlines-hidden', + '-funwind-tables', + '-fwrapv', + '-O3', + '-fPIC', + '-shared', + '-ldl', + '-lm', + '-lpthread', + '-lrt', + '-fPIE', + '-g', + '-ftemplate-depth=1024', + '-pedantic-errors' ]; for (let s of ss) { if (e.startsWith(s)) { return true; } } - if (e == "-w") {//-----直接忽略的编译参数(和链接参数) + if (e == '-w') {//-----直接忽略的编译参数(和链接参数) return true; } return false; } static clangxxCheck2(local, e) { - if (e.startsWith("-isystem")) {//需要 不清楚这个有什么用 - if (e == "-isystem") {//-isystem xxxx + if (e.startsWith('-isystem')) {//需要 不清楚这个有什么用 + if (e == '-isystem') {//-isystem xxxx local.ret.includes.push(local.eles[local.p++]); } else {//-Ixxx @@ -450,7 +450,7 @@ class AnalyzeCommand { return false; } static clangxxCheck3(local, e) { - if (e.startsWith("-D")) {//需要记录到defines里面的参数 + if (e.startsWith('-D')) {//需要记录到defines里面的参数 //需要 是否-D开头的,全部记录到defines里面 if (e.length == 2) {//-D xxx local.ret.defines.push(local.eles[local.p++]); @@ -463,7 +463,7 @@ class AnalyzeCommand { return false; } static clangxxCheck4(local, e) { - if (e.startsWith("-I")) {//需要记录到includes的参数 + if (e.startsWith('-I')) {//需要记录到includes的参数 if (e.length == 2) {//-I xxx local.ret.includes.push(local.eles[local.p++]); } @@ -482,9 +482,9 @@ class AnalyzeCommand { return false; } static clangxxCheck6(local, e) { - if (e.startsWith("-Xclang")) {//透传参数 + if (e.startsWith('-Xclang')) {//透传参数 let v = local.eles[local.p++]; - if (v != "-emit-pch") {//需要丢弃这个选项 + if (v != '-emit-pch') {//需要丢弃这个选项 local.ret.cflags.push(e); local.ret.cflags.push(v); } @@ -493,8 +493,8 @@ class AnalyzeCommand { return false; } static clangxxCheck7(local, e) { - if (e.startsWith("-W")) {//需要 -W开头的怎么处理,-W -Wall -Werror=return-type -Wno-unnamed-type-template-args - if (e.startsWith("-Wno-")) { + if (e.startsWith('-W')) {//需要 -W开头的怎么处理,-W -Wall -Werror=return-type -Wno-unnamed-type-template-args + if (e.startsWith('-Wno-')) { local.ret.cflags.push(e); } return true; @@ -502,16 +502,16 @@ class AnalyzeCommand { return false; } static clangxxCheck8(local, e) { - if (e == "-o") { + if (e == '-o') { if (e.length == 2) {//-o xxx local.ret.target = local.eles[local.p++]; } else {//-oxxx local.ret.target = e.substring(2); } - if (local.ret.target.endsWith(".a") || - local.ret.target.endsWith(".so") || - (!e.endsWith(".c") && !e.endsWith(".o"))) { + if (local.ret.target.endsWith('.a') || + local.ret.target.endsWith('.so') || + (!e.endsWith('.c') && !e.endsWith('.o'))) { local.ret.isLink = true; } return true; @@ -530,24 +530,24 @@ class AnalyzeCommand { return false; } static clangxxCheck9(local, e) { - if (this.validSuffix(e, Tool.getAllowedCxx().fileSuffix) || (e.indexOf(".so.") > 0)) { + if (this.validSuffix(e, Tool.getAllowedCxx().fileSuffix) || (e.indexOf('.so.') > 0)) { local.ret.inputs.push(e); return true; } - if (e.endsWith(".rsp")) { + if (e.endsWith('.rsp')) { console.log(Tool.CURRENT_DIR); let rspth = path.join(Tool.CURRENT_DIR, e.substring(1)); - let data = fs.readFileSync(rspth, { encoding: "utf8" }); - if (data.endsWith("\r\n")) { + let data = fs.readFileSync(rspth, { encoding: 'utf8' }); + if (data.endsWith('\r\n')) { data = data.substring(0, data.length - 2); } - let datas = data.split(" "); - let pp = [".c", - ".o", + let datas = data.split(' '); + let pp = ['.c', + '.o', '.o"', - ".a", - ".S", - ".so" + '.a', + '.S', + '.so' ]; for (let d of datas) { for (let p of pp) { @@ -561,8 +561,8 @@ class AnalyzeCommand { return false; } static analyzeCcClangxx(cmd) { - if (cmd.indexOf("\"")) { - cmd = cmd.replace(/\"/g, ""); + if (cmd.indexOf('\"')) { + cmd = cmd.replace(/\"/g, ''); } let local = { ret: AnalyzeCommand.resultTemplete(), @@ -571,59 +571,59 @@ class AnalyzeCommand { }; while (local.p < local.eles.length) { let e = local.eles[local.p++]; - if (e.endsWith("clang++") || e.endsWith("clang++.exe")) { + if (e.endsWith('clang++') || e.endsWith('clang++.exe')) { local.ret.command = e; } else if (AnalyzeCommand.clangxxCheck1(e)) { } - else if (e.startsWith("-fno-rtti")) { - local.ret.cflags.splice(local.ret.cflags.indexOf("-frtti"), 1); + else if (e.startsWith('-fno-rtti')) { + local.ret.cflags.splice(local.ret.cflags.indexOf('-frtti'), 1); } - else if (e.startsWith("-fno-exceptions")) { - local.ret.cflags.splice(local.ret.cflags.indexOf("-fexceptions"), 1); + else if (e.startsWith('-fno-exceptions')) { + local.ret.cflags.splice(local.ret.cflags.indexOf('-fexceptions'), 1); } else if (AnalyzeCommand.clangxxCheck2(local, e)) { } else if (AnalyzeCommand.clangxxCheck3(local, e)) { } else if (AnalyzeCommand.clangxxCheck4(local, e)) { } else if (AnalyzeCommand.clangxxCheck5(local, e)) { } else if (AnalyzeCommand.clangxxCheck6(local, e)) { } - else if (e.startsWith("-std=")) { + else if (e.startsWith('-std=')) { local.ret.cflagsCc.push(e); } else if (AnalyzeCommand.clangxxCheck7(local, e)) { } else if (AnalyzeCommand.clangxxCheck8(local, e)) { } - else if (e == "-c") {//编译 + else if (e == '-c') {//编译 local.ret.isLink = false; } else if (AnalyzeCommand.clangxxCheck9(local, e)) { } else { - Logger.err(cmd + "\nclang++未解析参数 " + e); + Logger.err(cmd + '\nclang++未解析参数 ' + e); process.exit(); } } - Logger.info("---clang++----" + local.ret.workDir + "\n\t" + local.ret.isLink + "," + local.ret.target); + Logger.info('---clang++----' + local.ret.workDir + '\n\t' + local.ret.isLink + ',' + local.ret.target); return local.ret; } static analyzeCompileCommand(cmd) { //整理命令行 - while (cmd.indexOf("\\\n") >= 0) {//去除\换行 - cmd = cmd.replace("\\\n", ""); + while (cmd.indexOf('\\\n') >= 0) {//去除\换行 + cmd = cmd.replace('\\\n', ''); } - while (cmd.indexOf("\t") >= 0) {//所有tab换成空格 - cmd = cmd.replace("\t", " "); + while (cmd.indexOf('\t') >= 0) {//所有tab换成空格 + cmd = cmd.replace('\t', ' '); } - while (cmd.endsWith("\n") || cmd.endsWith(" ")) { + while (cmd.endsWith('\n') || cmd.endsWith(' ')) { cmd = cmd.substring(0, cmd.length - 1); } let ret = null; switch (AnalyzeCommand.getCompileCmdId(cmd)) { - case AnalyzeCommand.COMPILE_CMDS["clang"]: + case AnalyzeCommand.COMPILE_CMDS['clang']: ret = AnalyzeCommand.analyzeCcClang(cmd); break; - case AnalyzeCommand.COMPILE_CMDS["ar"]: + case AnalyzeCommand.COMPILE_CMDS['ar']: ret = AnalyzeCommand.analyzeCcAr(cmd); break; - case AnalyzeCommand.COMPILE_CMDS["clang++"]: + case AnalyzeCommand.COMPILE_CMDS['clang++']: ret = AnalyzeCommand.analyzeCcClangxx(cmd); break; } @@ -631,7 +631,7 @@ class AnalyzeCommand { AnalyzeCommand.mockTarget(ret);//解析出的目标,touch一个出来,否则会出现不同Makefile中依赖无法找到的问题 return ret; } - Logger.err("解析编译命令行失败:" + cmd); + Logger.err('解析编译命令行失败:' + cmd); return false; } } -- Gitee From d8c0df01b7062ca10a2b4ef0bb7edfc52dc8a1ed Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:01:18 +0800 Subject: [PATCH 04/26] =?UTF-8?q?"modifile=20src/cli/cmake2gn/src/src/anal?= =?UTF-8?q?yze=5Fmake.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/cmake2gn/src/src/analyze_make.js | 46 ++++++++++++------------ 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/cli/cmake2gn/src/src/analyze_make.js b/src/cli/cmake2gn/src/src/analyze_make.js index 43a1f0c8..3297aef8 100644 --- a/src/cli/cmake2gn/src/src/analyze_make.js +++ b/src/cli/cmake2gn/src/src/analyze_make.js @@ -12,12 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const childProcess = require("child_process"); -const fs = require("fs"); -const path = require("path"); -const { AnalyzeCommand } = require("./analyze_command"); -const { Logger } = require("./logger"); -const { Tool } = require("./tool"); +const childProcess = require('child_process'); +const fs = require('fs'); +const path = require('path'); +const { AnalyzeCommand } = require('./analyze_command'); +const { Logger } = require('./logger'); +const { Tool } = require('./tool'); class AnalyzeMake { constructor() { @@ -26,13 +26,13 @@ class AnalyzeMake { static USE_UDP_COLLECTOR = true; static collectByUdp(makeProjectPath) { - const dgram = require("dgram"); - let udpServer_ = dgram.createSocket("udp4"); + const dgram = require('dgram'); + let udpServer_ = dgram.createSocket('udp4'); let analyzeResult = []; udpServer_.bind(6000); udpServer_.on('listening', () => { Tool.pushd(makeProjectPath); - let ret = childProcess.spawn(Tool.getMake(), ["-C", makeProjectPath, "-n"]); + let ret = childProcess.spawn(Tool.getMake(), ['-C', makeProjectPath, '-n']); ret.stdout.on('data', (data) => {//要有,不然不进入close }); ret.stderr.on('data', (data) => { @@ -40,7 +40,7 @@ class AnalyzeMake { }); ret.on('close', (code) => { if (code == 0) { - Logger.info("-----------------------------make ok"); + Logger.info('-----------------------------make ok'); udpServer_.close(); udpServer_ = null; @@ -48,11 +48,11 @@ class AnalyzeMake { Tool.generateTarget(makeProjectPath, analyzeResult);//生成结果目标 } - else Logger.err("make fail"); + else Logger.err('make fail'); }); }); udpServer_.on('error', (e) => { - Logger.err("udp error"); + Logger.err('udp error'); }); udpServer_.on('message', (msg, rinfo) => { let acmd = msg.toString(); @@ -60,13 +60,13 @@ class AnalyzeMake { if (ret.length > 0) { analyzeResult.push(...ret); } - udpServer_.send("ok", 0, 2, rinfo.port, rinfo.address);//反馈ok给make继续执行 + udpServer_.send('ok', 0, 2, rinfo.port, rinfo.address);//反馈ok给make继续执行 }); } static analyzeBreakup() { - let acmd = ""; + let acmd = ''; for (let l of dlist) { - if (l.endsWith("\\")) { // 合并带有换行符的命令 + if (l.endsWith('\\')) { // 合并带有换行符的命令 acmd += l; } else { @@ -78,14 +78,14 @@ class AnalyzeMake { analyzeResult.push(...ret); } } - acmd = ""; + acmd = ''; } } } static analyze(makeProjectFile) { let makeProjectPath = path.parse(makeProjectFile); if (!fs.existsSync(makeProjectFile)) { - Logger.err("Makefile not exist in " + makeProjectPath.dir); + Logger.err('Makefile not exist in ' + makeProjectPath.dir); return; } if (AnalyzeMake.USE_UDP_COLLECTOR) { @@ -93,17 +93,17 @@ class AnalyzeMake { return; } Tool.pushd(makeProjectPath.dir); - let ret = childProcess.spawn("make", ["-C", makeProjectPath.dir, "-n"]); + let ret = childProcess.spawn('make', ['-C', makeProjectPath.dir, '-n']); let cmdlist = []; let analyzeResult = []; - let procData = ""; + let procData = ''; ret.stdout.on('data', (data) => { procData += data.toString(); - let p = procData.lastIndexOf("\n"); + let p = procData.lastIndexOf('\n'); if (p < 0) { return; } - let dlist = procData.substring(0, p).split("\n"); + let dlist = procData.substring(0, p).split('\n'); procData = procData.substring(p + 1); AnalyzeMake.analyzeBreakup(dlist, cmdlist, analyzeResult); }); @@ -112,10 +112,10 @@ class AnalyzeMake { }); ret.on('close', (code) => { if (code == 0) { - Logger.info("-----------------------------make ok"); + Logger.info('-----------------------------make ok'); Tool.generateTarget(makeProjectPath.dir, analyzeResult);//生成结果目标 } - else Logger.err("make fail"); + else Logger.err('make fail'); }); } } -- Gitee From 0175f9b8356a9dd0f18ab527a43521f921304982 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:02:39 +0800 Subject: [PATCH 05/26] =?UTF-8?q?"modifile=20src/cli/cmake2gn/src/src/gene?= =?UTF-8?q?rate=5Fgn.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/cmake2gn/src/src/generate_gn.js | 108 ++++++++++++------------ 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/src/cli/cmake2gn/src/src/generate_gn.js b/src/cli/cmake2gn/src/src/generate_gn.js index d88bcfc7..d796e813 100644 --- a/src/cli/cmake2gn/src/src/generate_gn.js +++ b/src/cli/cmake2gn/src/src/generate_gn.js @@ -12,24 +12,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const path = require("path"); -const fs = require("fs"); -const { Logger } = require("./logger"); -const { Tool } = require("./tool"); -const { exit } = require("process"); +const path = require('path'); +const fs = require('fs'); +const { Logger } = require('./logger'); +const { Tool } = require('./tool'); +const { exit } = require('process'); function saveMockData(projectPath, analyzeResult) { let ss = JSON.stringify({ projectPath: projectPath, analyzeResult: analyzeResult }, null, 4); - fs.writeFileSync(path.join(Tool.CURRENT_TOOL_PATH, "mock.json"), ss); - Logger.err("save mock exit"); + fs.writeFileSync(path.join(Tool.CURRENT_TOOL_PATH, 'mock.json'), ss); + Logger.err('save mock exit'); } function preProcessResult(analyzeResult) {//把所有路径搞成绝对路径 for (let r of analyzeResult) { - if (!r.target.startsWith("/")) { + if (!r.target.startsWith('/')) { if (!path.isAbsolute(r.target)) { r.target = path.join(r.workDir, r.target); } @@ -38,14 +38,14 @@ function preProcessResult(analyzeResult) {//把所有路径搞成绝对路径 if (r.inputs[i].startsWith('"') && r.inputs[i].endsWith('"')) { r.inputs[i] = r.inputs[i].substring(1, r.inputs[i].length - 1); } - if (!r.inputs[i].startsWith("/")) { + if (!r.inputs[i].startsWith('/')) { if (!path.isAbsolute(r.inputs[i])) { r.inputs[i] = path.join(r.workDir, r.inputs[i]); } } } for (let i = 0; i < r.includes.length; i++) { - if (!r.includes[i].startsWith("/")) { + if (!r.includes[i].startsWith('/')) { if (!path.isAbsolute(r.includes[i])) { r.includes[i] = path.join(r.workDir, r.includes[i]); } @@ -57,22 +57,22 @@ function preProcessResult(analyzeResult) {//把所有路径搞成绝对路径 function checkoutLibName(name) {//比如/home/libabc.so,返回["dynamic",abc] let pn = path.parse(name); let tname = pn.base; - if (tname.endsWith(".a")) { + if (tname.endsWith('.a')) { tname = tname.substring(0, tname.length - 2); - if (tname.startsWith("lib")) { + if (tname.startsWith('lib')) { tname = tname.substring(3); } - return ["static", tname]; + return ['static', tname]; } - else if (tname.endsWith(".so") || tname.indexOf(".so.") > 0) { - tname = tname.substring(0, tname.indexOf(".so")); - if (tname.startsWith("lib")) { + else if (tname.endsWith('.so') || tname.indexOf('.so.') > 0) { + tname = tname.substring(0, tname.indexOf('.so')); + if (tname.startsWith('lib')) { tname = tname.substring(3); } - return ["dynamic", tname]; + return ['dynamic', tname]; } else { - return ["executable", tname]; + return ['executable', tname]; } } @@ -81,10 +81,10 @@ class GenerateGn { } static mockGenerate() { - let ss = fs.readFileSync(path.join(Tool.CURRENT_TOOL_PATH, "mock.json"), { encoding: "utf8" }); + let ss = fs.readFileSync(path.join(Tool.CURRENT_TOOL_PATH, 'mock.json'), { encoding: 'utf8' }); let ret = JSON.parse(ss); GenerateGn.generate(ret.projectPath, ret.analyzeResult); - Logger.err("generate mock exit"); + Logger.err('generate mock exit'); } static generate(projectPath, analyzeResult) { @@ -107,12 +107,12 @@ class GenerateGn { } let num = 0; for (let gnPath in genList) {//genList的key即为需要生成gn的目录 - Logger.info("%d-------------------generate dir %s".format(num, gnPath)); + Logger.info('%d-------------------generate dir %s'.format(num, gnPath)); GenerateGn.generateGn(gnPath, genList, projectPath); num++; } GenerateGn.generateTargetGroup(projectPath); - Logger.info("-------------------generate gn ok"); + Logger.info('-------------------generate gn ok'); } static COLLECT_TARGET = { static: [], @@ -120,23 +120,23 @@ class GenerateGn { executable: [] }; static generateTargetGroup(projectPath) { - let gnName = path.join(projectPath, "BUILD.gn"); + let gnName = path.join(projectPath, 'BUILD.gn'); let gnStr = 'import("//build/ohos.gni")\n\n'; if (fs.existsSync(gnName)) { - gnStr = fs.readFileSync(gnName, { encoding: "utf8" }); + gnStr = fs.readFileSync(gnName, { encoding: 'utf8' }); } let staticTargets = []; for (let t of GenerateGn.COLLECT_TARGET.static) { - staticTargets.push(Tool.swapPath(t.path) + ":" + t.name); + staticTargets.push(Tool.swapPath(t.path) + ':' + t.name); } let dynamicTargets = []; for (let t of GenerateGn.COLLECT_TARGET.dynamic) { - dynamicTargets.push(Tool.swapPath(t.path) + ":" + t.name); + dynamicTargets.push(Tool.swapPath(t.path) + ':' + t.name); } let executableTargets = []; for (let t of GenerateGn.COLLECT_TARGET.executable) { - executableTargets.push(Tool.swapPath(t.path) + ":" + t.name); + executableTargets.push(Tool.swapPath(t.path) + ':' + t.name); } gnStr += ` @@ -165,17 +165,17 @@ group("all_targets") { } `; while (gnStr.indexOf(Tool.OHOS_PROJECT_PATH) >= 0) { - gnStr = gnStr.replace(Tool.OHOS_PROJECT_PATH, "/"); + gnStr = gnStr.replace(Tool.OHOS_PROJECT_PATH, '/'); } - fs.writeFileSync(gnName, gnStr, { encoding: "utf8" }); + fs.writeFileSync(gnName, gnStr, { encoding: 'utf8' }); } static genTargetStr(targetName) { switch (targetName[0]) { - case "static": + case 'static': return 'ohos_static_library("' + targetName[1] + '")'; - case "dynamic": + case 'dynamic': return 'ohos_shared_library("' + targetName[1] + '")'; - case "executable": + case 'executable': return 'ohos_executable("' + targetName[1] + '")'; } } @@ -195,18 +195,18 @@ group("all_targets") { } static genTargetStr2(collectDetails, targetStr, targetName) { if (collectDetails.cflags.size > 0 || collectDetails.cflagsCc.size > 0) {//放到config里面才生效 - let configDetail = ""; - let removeConfigs = ""; + let configDetail = ''; + let removeConfigs = ''; if (collectDetails.cflags.size > 0) { - configDetail += GenerateGn.genDetail("cflags", collectDetails.cflags); + configDetail += GenerateGn.genDetail('cflags', collectDetails.cflags); } if (collectDetails.cflagsCc.size > 0) { - configDetail += GenerateGn.genDetail("cflags_cc", collectDetails.cflagsCc); + configDetail += GenerateGn.genDetail('cflags_cc', collectDetails.cflagsCc); } - if (collectDetails.cflags.has("-frtti")) { + if (collectDetails.cflags.has('-frtti')) { removeConfigs += ` "//build/config/compiler:no_rtti",\n`; } - if (collectDetails.cflags.has("-fexceptions")) { + if (collectDetails.cflags.has('-fexceptions')) { removeConfigs += ` "//build/config/compiler:no_exceptions",\n`; } targetStr = `config("%s_config") {%s} @@ -218,16 +218,16 @@ configs = [ ":%s_config" ] `.format(targetName[1], configDetail, targetStr, removeConfigs, targetName[1]); } if (collectDetails.sources.size > 0) { - targetStr += GenerateGn.genDetail("sources", collectDetails.sources); + targetStr += GenerateGn.genDetail('sources', collectDetails.sources); } if (collectDetails.includeDirs.size > 0) { - targetStr += GenerateGn.genDetail("include_dirs", collectDetails.includeDirs); + targetStr += GenerateGn.genDetail('include_dirs', collectDetails.includeDirs); } if (collectDetails.defines.size > 0) { - targetStr += GenerateGn.genDetail("defines", collectDetails.defines); + targetStr += GenerateGn.genDetail('defines', collectDetails.defines); } if (collectDetails.deps.size > 0) { - targetStr += GenerateGn.genDetail("deps", collectDetails.deps); + targetStr += GenerateGn.genDetail('deps', collectDetails.deps); } targetStr += ` @@ -240,7 +240,7 @@ subsystem_name = "%s" } static generateGn(gnPath, genList, projectPath) { if (!gnPath.startsWith(projectPath)) { - Logger.err("target path not in project path\ntarget:%s\nproject:%s".format(gnPath, projectPath)); + Logger.err('target path not in project path\ntarget:%s\nproject:%s'.format(gnPath, projectPath)); } let gnStr = 'import("//build/ohos.gni")\n\n'; let targetCount = 0; @@ -263,17 +263,17 @@ subsystem_name = "%s" } if (targetCount > 0) { - let gnName = path.join(gnPath, "BUILD.gn"); - Logger.info("输出:" + gnName + "\n" + gnStr); - fs.writeFileSync(gnName, gnStr, { encoding: "utf8" }); + let gnName = path.join(gnPath, 'BUILD.gn'); + Logger.info('输出:' + gnName + '\n' + gnStr); + fs.writeFileSync(gnName, gnStr, { encoding: 'utf8' }); } else { - Logger.info(" no target"); + Logger.info(' no target'); } } static genDetail(name, detail) { - let ss = ""; + let ss = ''; for (let s of detail) { s=Tool.swapPath(s); if (ss.length > 0) ss += '",\n "'; @@ -286,7 +286,7 @@ subsystem_name = "%s" `.format(name, ss); while (ret.indexOf(Tool.OHOS_PROJECT_PATH) >= 0) { - ret = ret.replace(Tool.OHOS_PROJECT_PATH, "/"); + ret = ret.replace(Tool.OHOS_PROJECT_PATH, '/'); } return ret; } @@ -297,7 +297,7 @@ subsystem_name = "%s" for (let gen of gens) { if (gen.target == name) { let tt = checkoutLibName(gen.target); - return gen.workDir + ":" + tt[1]; + return gen.workDir + ':' + tt[1]; } } } @@ -310,23 +310,23 @@ subsystem_name = "%s" let badd = true; switch (collectFileStat) { case 0: - if (a == "-Xclang") { + if (a == '-Xclang') { collectFileStat = 1; badd = false; } break; case 1: - if (a == "-include" || a == "-include-pch") { + if (a == '-include' || a == '-include-pch') { collectFileStat = 2; badd = false; } else { - collectDetails.cflags.add("-Xclang"); + collectDetails.cflags.add('-Xclang'); collectFileStat = 0; } break; case 2: - if (a == "-Xclang") { + if (a == '-Xclang') { collectFileStat = 3; badd = false; } -- Gitee From 4fda1030c74cdfe9843e4b9ae11c46f67f6e32ae Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:03:49 +0800 Subject: [PATCH 06/26] =?UTF-8?q?"modifile=20src/cli/cmake2gn/src/src/logg?= =?UTF-8?q?er.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/cmake2gn/src/src/logger.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cli/cmake2gn/src/src/logger.js b/src/cli/cmake2gn/src/src/logger.js index e432df78..f0e5719c 100644 --- a/src/cli/cmake2gn/src/src/logger.js +++ b/src/cli/cmake2gn/src/src/logger.js @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { Tool } = require("./tool"); +const { Tool } = require('./tool'); class Logger { constructor() { @@ -23,7 +23,7 @@ class Logger { Tool.VSCODE_INST.window.showErrorMessage(msg); } - console.log("ERR :", msg); + console.log('ERR :', msg); if (dontexit) { return false; } @@ -36,7 +36,7 @@ class Logger { Tool.VSCODE_INST.window.showInformationMessage(msg); } - console.log("INFO (%d) %s".format(Logger.INFO_NUM++, msg)); + console.log('INFO (%d) %s'.format(Logger.INFO_NUM++, msg)); } } -- Gitee From 9ce1c4c68ba2b94f1d69ef277f5e2a72cd86ae7c Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:04:23 +0800 Subject: [PATCH 07/26] =?UTF-8?q?"modifile=20src/cli/cmake2gn/src/src/tool?= =?UTF-8?q?.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/cmake2gn/src/src/tool.js | 88 ++++++++++++++++---------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/src/cli/cmake2gn/src/src/tool.js b/src/cli/cmake2gn/src/src/tool.js index 2da5983c..13847ffe 100644 --- a/src/cli/cmake2gn/src/src/tool.js +++ b/src/cli/cmake2gn/src/src/tool.js @@ -13,18 +13,18 @@ * limitations under the License. */ const path = require('path'); -const fs = require("fs"); +const fs = require('fs'); class Tool { constructor() { } static CURRENT_TOOL_PATH = null;//生成工具或插件所在路径,用于找到res - static OHOS_PROJECT_PATH = "/home/xx/ohos"; - static OHOS_PORTING_TO = "third_party/opencv"; - static OHOS_PRODUCT_OUTPUT_PATH = "out/rk3568-khdvk";//输出目录 - static OHOS_SUBSYSTEM_NAME = "common"; - static OHOS_PART_NAME = "common"; + static OHOS_PROJECT_PATH = '/home/xx/ohos'; + static OHOS_PORTING_TO = 'third_party/opencv'; + static OHOS_PRODUCT_OUTPUT_PATH = 'out/rk3568-khdvk';//输出目录 + static OHOS_SUBSYSTEM_NAME = 'common'; + static OHOS_PART_NAME = 'common'; static globalJsonCfg = null; // cfg.json 配置文件 static allowedCxx = null; // cxx编译中允许处理的文件后缀列表 static allowedC = null; // c编译中允许处理的文件后缀列表 @@ -36,58 +36,58 @@ class Tool { static getCMakeToolchain() { switch (process.platform) { case 'win32': - return path.join(Tool.CURRENT_TOOL_PATH, "res/win/ohos.toolchain.cmake"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/win/ohos.toolchain.cmake'); case 'linux': - return path.join(Tool.CURRENT_TOOL_PATH, "res/linux/ohos.toolchain.cmake"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/linux/ohos.toolchain.cmake'); case 'darwin': - return path.join(Tool.CURRENT_TOOL_PATH, "res/mac/ohos.toolchain.cmake"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/mac/ohos.toolchain.cmake'); default: - Logger.err("不支持 %s 平台".format(process.platform)); - return ""; + Logger.err('不支持 %s 平台'.format(process.platform)); + return ''; } } static getMakeRaw() { switch (process.platform) { case 'win32': - return path.join(Tool.CURRENT_TOOL_PATH, "res/win/bin/make_raw.exe"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/win/bin/make_raw.exe'); case 'linux': - return path.join(Tool.CURRENT_TOOL_PATH, "res/linux/bin/make_raw"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/linux/bin/make_raw'); case 'darwin': - return path.join(Tool.CURRENT_TOOL_PATH, "res/mac/bin/make_raw"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/mac/bin/make_raw'); default: - Logger.err("不支持 %s 平台".format(process.platform)); - return ""; + Logger.err('不支持 %s 平台'.format(process.platform)); + return ''; } } static getMake() { switch (process.platform) { case 'win32': - return path.join(Tool.CURRENT_TOOL_PATH, "res/win/bin/make.exe"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/win/bin/make.exe'); case 'linux': - return path.join(Tool.CURRENT_TOOL_PATH, "res/linux/bin/make"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/linux/bin/make'); case 'darwin': - return path.join(Tool.CURRENT_TOOL_PATH, "res/mac/bin/make"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/mac/bin/make'); default: - Logger.err("不支持 %s 平台".format(process.platform)); - return ""; + Logger.err('不支持 %s 平台'.format(process.platform)); + return ''; } } static getCMake() { switch (process.platform) { case 'win32': - return path.join(Tool.OHOS_PROJECT_PATH, "prebuilts/cmake/windows-x86/bin/cmake.exe"); + return path.join(Tool.OHOS_PROJECT_PATH, 'prebuilts/cmake/windows-x86/bin/cmake.exe'); case 'linux': case 'darwin': - return path.join(Tool.OHOS_PROJECT_PATH, "prebuilts/cmake/linux-x86/bin/cmake"); + return path.join(Tool.OHOS_PROJECT_PATH, 'prebuilts/cmake/linux-x86/bin/cmake'); default: - Logger.err("不支持 %s 平台".format(process.platform)); - return ""; + Logger.err('不支持 %s 平台'.format(process.platform)); + return ''; } } static swapPath(p, swapd) { - while (p.indexOf("\\") >= 0) { - p = p.replace("\\", "/"); + while (p.indexOf('\\') >= 0) { + p = p.replace('\\', '/'); } return p; } @@ -138,7 +138,7 @@ class Tool { GenerateGn.generate(projectPath, analyzeResult); break; default: - Logger.err("generate target not support"); + Logger.err('generate target not support'); break; } } @@ -156,11 +156,11 @@ class Tool { */ static getJsonCfg() { if (this.globalJsonCfg == null) { - let jsonFilePath = path.join(Tool.CURRENT_TOOL_PATH, "res/cfg.json"); - let jsonFile = fs.readFileSync(jsonFilePath, { encoding: "utf8" }); + let jsonFilePath = path.join(Tool.CURRENT_TOOL_PATH, 'res/cfg.json'); + let jsonFile = fs.readFileSync(jsonFilePath, { encoding: 'utf8' }); this.globalJsonCfg = JSON.parse(jsonFile); - this.globalJsonCfg.fileSuffix = this.globalJsonCfg.fileSuffix ? "," + this.globalJsonCfg.fileSuffix : ""; - this.globalJsonCfg.compileflag = this.globalJsonCfg.compileflag ? "," + this.globalJsonCfg.compileflag : ""; + this.globalJsonCfg.fileSuffix = this.globalJsonCfg.fileSuffix ? ',' + this.globalJsonCfg.fileSuffix : ''; + this.globalJsonCfg.compileflag = this.globalJsonCfg.compileflag ? ',' + this.globalJsonCfg.compileflag : ''; } return this.globalJsonCfg; @@ -174,13 +174,13 @@ class Tool { if (this.allowedCxx == null) { this.allowedCxx = {}; let jsonCfg = this.getJsonCfg(); - let allowedCxxSuffix = ".cpp, .cxx, .cc, .o, .z, .so, .a" + jsonCfg.fileSuffix; + let allowedCxxSuffix = '.cpp, .cxx, .cc, .o, .z, .so, .a' + jsonCfg.fileSuffix; this.allowedCxx.fileSuffix = - allowedCxxSuffix.split(",").map(item => item.trim()).filter(item => item != ""); - let allowedFlag = "--target=, -march=, -mfloat-abi=, -mfpu=, -fsigned-char, -ffast-math, -rdynamic, " - + "-UNDEBUG, -fno-threadsafe-statics, -fno-common, -fno-strict-aliasing, -fcolor-diagnostics, " - + "-fstrict-aliasing, -fdiagnostics-show-option" + jsonCfg.compileflag; - this.allowedCxx.compileflag = allowedFlag.split(",").map(item => item.trim()).filter(item => item != ""); + allowedCxxSuffix.split(',').map(item => item.trim()).filter(item => item != ''); + let allowedFlag = '--target=, -march=, -mfloat-abi=, -mfpu=, -fsigned-char, -ffast-math, -rdynamic, ' + + '-UNDEBUG, -fno-threadsafe-statics, -fno-common, -fno-strict-aliasing, -fcolor-diagnostics, ' + + '-fstrict-aliasing, -fdiagnostics-show-option' + jsonCfg.compileflag; + this.allowedCxx.compileflag = allowedFlag.split(',').map(item => item.trim()).filter(item => item != ''); } return this.allowedCxx; } @@ -194,12 +194,12 @@ class Tool { this.allowedC = {}; let jsonCfg = this.getJsonCfg(); let allowedCSuffix = '.c, .o, .o", .a, .S, .so' + jsonCfg.fileSuffix; - this.allowedC.fileSuffix = allowedCSuffix.split(",").map(item => item.trim()).filter(item => item != ""); - let allowedFlag = "--target=, -march=, -mfloat-abi=, -mfpu=, -fno-common, -fcolor-diagnostics, -ggdb, " - + "-fno-strict-aliasing, -ldl, -flto, -fno-builtin, -fno-stack-protector, -fvisibility=default, " - + "-fsigned-char, -fstack-protector-strong, -fdiagnostics-show-option" + this.allowedC.fileSuffix = allowedCSuffix.split(',').map(item => item.trim()).filter(item => item != ''); + let allowedFlag = '--target=, -march=, -mfloat-abi=, -mfpu=, -fno-common, -fcolor-diagnostics, -ggdb, ' + + '-fno-strict-aliasing, -ldl, -flto, -fno-builtin, -fno-stack-protector, -fvisibility=default, ' + + '-fsigned-char, -fstack-protector-strong, -fdiagnostics-show-option' + jsonCfg.compileflag; - this.allowedC.compileflag = allowedFlag.split(",").map(item => item.trim()).filter(item => item != ""); + this.allowedC.compileflag = allowedFlag.split(',').map(item => item.trim()).filter(item => item != ''); } return this.allowedC; } @@ -207,7 +207,7 @@ class Tool { 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; -- Gitee From 606961d0d47d1df9cf3fe524a79f7f7eb56e5bbd Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:05:43 +0800 Subject: [PATCH 08/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/analy?= =?UTF-8?q?ze/enum.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/analyze/enum.js | 72 ++++++++++++------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/enum.js b/src/cli/dts2cpp/src/gen/analyze/enum.js index a7f28808..1987a9f6 100644 --- a/src/cli/dts2cpp/src/gen/analyze/enum.js +++ b/src/cli/dts2cpp/src/gen/analyze/enum.js @@ -12,80 +12,80 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { NumberIncrease } = require("../tools/common"); -const re = require("../tools/re"); +const { NumberIncrease } = require('../tools/common'); +const re = require('../tools/re'); /** Enum解析 */ function analyzeEnum(data) { - let body = re.replaceAll(data, "\n", "").split(",") + let body = re.replaceAll(data, '\n', '').split(','); let result = { element: [], function: [], enumValueType: 0 // 0代表数字,1代表字符串 - } + }; for (let i in body) { - let bodyContent = body[i] + let bodyContent = body[i]; while (bodyContent.length > 0 && bodyContent[0] == ' ') { - bodyContent = bodyContent.substring(1, bodyContent.length) + bodyContent = bodyContent.substring(1, bodyContent.length); } while (bodyContent.length > 0 && bodyContent[-1] == ' ') { - bodyContent = bodyContent.substring(0, bodyContent.length - 1) + bodyContent = bodyContent.substring(0, bodyContent.length - 1); } - if (bodyContent == "") { - break + if (bodyContent == '') { + break; } - analyzeEnumResult(result, bodyContent, i) + analyzeEnumResult(result, bodyContent, i); } - return result + return result; } function analyzeEnumResult(result, bodyContent, index) { - let regString = re.match(" *([a-zA-Z0-9_]+) * = *\"([\x21-\x7e]+)*\"", bodyContent) - let regSingleQuotes = re.match(" *([a-zA-Z0-9_]+) * = *'([\x21-\x7e]+)*'", bodyContent) - let regNumber = re.match(" *([a-zA-Z0-9_]+) * = *([a-zA-Z_0-9<>-]+)", bodyContent) - let reg = re.match(" *([a-zA-Z0-9_]+) *", bodyContent) + let regString = re.match(' *([a-zA-Z0-9_]+) * = *\"([\x21-\x7e]+)*\"', bodyContent); + let regSingleQuotes = re.match(" *([a-zA-Z0-9_]+) * = *'([\x21-\x7e]+)*'", bodyContent); + let regNumber = re.match(" *([a-zA-Z0-9_]+) * = *([a-zA-Z_0-9<>-]+)", bodyContent); + let reg = re.match(' *([a-zA-Z0-9_]+) *', bodyContent); if (regString) { - let elementName = re.getReg(bodyContent, regString.regs[1]) - let elementValue = re.getReg(bodyContent, regString.regs[2]) + let elementName = re.getReg(bodyContent, regString.regs[1]); + let elementValue = re.getReg(bodyContent, regString.regs[2]); result.element.push({ name: elementName, value: elementValue, type: 'string' - }) - result.enumValueType = 1 + }); + result.enumValueType = 1; } else if (regSingleQuotes) { - let elementName = re.getReg(bodyContent, regSingleQuotes.regs[1]) - let elementValue = re.getReg(bodyContent, regSingleQuotes.regs[2]) + let elementName = re.getReg(bodyContent, regSingleQuotes.regs[1]); + let elementValue = re.getReg(bodyContent, regSingleQuotes.regs[2]); result.element.push({ name: elementName, value: elementValue, type: 'string' - }) - result.enumValueType = 1 + }); + result.enumValueType = 1; } else if (regNumber) { - let elementName = re.getReg(bodyContent, regNumber.regs[1]) - let elementValue = re.getReg(bodyContent, regNumber.regs[2]) - typeof (elementValue) + let elementName = re.getReg(bodyContent, regNumber.regs[1]); + let elementValue = re.getReg(bodyContent, regNumber.regs[2]); + typeof (elementValue); result.element.push({ name: elementName, value: elementValue, - type: "NUMBER_TYPE_" + NumberIncrease.getAndIncrease() - }) - result.enumValueType = 0 + type: 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease() + }); + result.enumValueType = 0; } else if (reg) { - let elementName = re.getReg(bodyContent, reg.regs[1]) - let elementValue = index + let elementName = re.getReg(bodyContent, reg.regs[1]); + let elementValue = index; result.element.push({ name: elementName, value: elementValue, - type: "NUMBER_TYPE_" + NumberIncrease.getAndIncrease() - }) - result.enumValueType = 0 + type: 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease() + }); + result.enumValueType = 0; } - return result + return result; } module.exports = { analyzeEnum, analyzeEnumResult -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From 30635f6e88934abc760dcba93f315f06df9a5fa4 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:05:47 +0800 Subject: [PATCH 09/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/analy?= =?UTF-8?q?ze/function.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/analyze/function.js | 236 ++++++++++---------- 1 file changed, 118 insertions(+), 118 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/function.js b/src/cli/dts2cpp/src/gen/analyze/function.js index ae341fa1..8db4a80c 100644 --- a/src/cli/dts2cpp/src/gen/analyze/function.js +++ b/src/cli/dts2cpp/src/gen/analyze/function.js @@ -12,193 +12,193 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); +const re = require('../tools/re'); const { FuncType, NumberIncrease, isEnum, EnumValueType, enumIndex, isType, typeIndex, isOnObjCallback, - getOnObjCallbackType, getLogErrInfo } = require("../tools/common"); -const { analyzeParams } = require("./params"); -const { analyzeReturn } = require("./return"); -const { NapiLog } = require("../tools/NapiLog"); -const { randomInt } = require("crypto"); -const { print } = require("../tools/tool"); + getOnObjCallbackType, getLogErrInfo } = require('../tools/common'); +const { analyzeParams } = require('./params'); +const { analyzeReturn } = require('./return'); +const { NapiLog } = require('../tools/NapiLog'); +const { randomInt } = require('crypto'); +const { print } = require('../tools/tool'); function analyzeSubInterface(data) { - let body = re.replaceAll(data, "\n", "").split(";") // # replace(" ", ""). + let body = re.replaceAll(data, '\n', '').split(';'); // # replace(" ", ""). let result = { value: [], function: [], parentNameList: [], childList: [], parentList: [] - } + }; for (let i in body) { - let t = body[i] + let t = body[i]; while (t.length > 0 && t[0] === ' ') // 去除前面的空格 - t = t.substring(1, t.length) + t = t.substring(1, t.length); while (t.length > 0 && t[-1] === ' ') // 去除后面的空格 - t = t.substring(0, t.length - 1) - if (t === "") break // 如果t为空直接返回 - let tt = re.match(" *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\] ]+)", t) + t = t.substring(0, t.length - 1); + if (t === '') break; // 如果t为空直接返回 + let tt = re.match(' *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\] ]+)', t); if (tt) { // 变量 - let valueName = re.getReg(t, tt.regs[1]) - let valueType = re.getReg(t, tt.regs[2]) - let index = valueType.indexOf("number") + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[2]); + let index = valueType.indexOf('number'); while (index !== -1) { - valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) - index = valueType.indexOf("number") + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); } result.value.push({ name: valueName, type: valueType - }) + }); } } - return result + return result; } function getFuncParaType(v, interfaceName, data, results) { - let arrayType = re.match("(Async)*Callback<(Array<([a-zA-Z_0-9]+)>)>", v["type"]) - let parameter = v["type"] + let arrayType = re.match('(Async)*Callback<(Array<([a-zA-Z_0-9]+)>)>', v['type']); + let parameter = v['type']; if (arrayType) { - parameter = re.getReg(v["type"], arrayType.regs[2]) + parameter = re.getReg(v['type'], arrayType.regs[2]); } if (isEnum(parameter, data)) { - let index = enumIndex(parameter, data) + let index = enumIndex(parameter, data); if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { - v["type"] = v["type"].replace(parameter, "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) + v['type'] = v['type'].replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); } else if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v["type"] = v["type"].replace(parameter, "string") + v['type'] = v['type'].replace(parameter, 'string'); } else { - NapiLog.logError("analyzeFunction getFuncParaType is not support this type %s." + NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s.' .format(data.enum[index].body.enumValueType), getLogErrInfo); - return null + return null; } } // interface & class中的方法参数类型是enum的情况 else if (isEnum(parameter, results)) { - let index = enumIndex(parameter, results) + let index = enumIndex(parameter, results); if (results.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { - v["type"] = v["type"].replace(parameter, "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) - v["realType"] = v["type"] + v['type'] = v['type'].replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + v['realType'] = v['type']; } else if (results.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v["type"] = v["type"].replace(parameter, "string") + v['type'] = v['type'].replace(parameter, 'string'); } else { - NapiLog.logError("analyzeFunction getFuncParaType is not support this type %s." + NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s.' .format(results.enum[index].body.enumValueType), getLogErrInfo()); - return null + return null; } } - let interfaceType = re.match("{([A-Za-z0-9_]+:[A-Za-z0-9_,]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$", v["type"]) + let interfaceType = re.match('{([A-Za-z0-9_]+:[A-Za-z0-9_,]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$', v['type']); if (interfaceType) { - v["type"] = interfaceName + v['type'] = interfaceName; } - if (parameter.indexOf("number") >= 0) { - v["type"] = v["type"].replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) - v["realType"] = v["type"] + if (parameter.indexOf('number') >= 0) { + v['type'] = v['type'].replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + v['realType'] = v['type']; } // type的处理 if (isType(parameter, data)) { - let index = typeIndex(parameter, data) + let index = typeIndex(parameter, data); if (data.type[index].isEnum) { - v["type"] = v["type"].replace(parameter, "string") + v['type'] = v['type'].replace(parameter, 'string'); } } - return v + return v; } function analyzeFuncNoNameInterface(data, values, results) { - values = re.replaceAll(re.replaceAll(values, " ", ""), "\n", "") - let interfaceName = "" - let matchNoName = "([:{<}>,;a-zA-Z_0-9]*)\\?*(:[A-Za-z0-9_,;]*)?:((Async)*Callback<)?{(([A-Za-z0-9_]+:"+ - "[A-Za-z0-9_,;]+)*)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}(}|,|;|>)?$" - let matchs = re.match(matchNoName, values) + values = re.replaceAll(re.replaceAll(values, ' ', ''), '\n', ''); + let interfaceName = ''; + let matchNoName = '([:{<}>,;a-zA-Z_0-9]*)\\?*(:[A-Za-z0-9_,;]*)?:((Async)*Callback<)?{(([A-Za-z0-9_]+:'+ + '[A-Za-z0-9_,;]+)*)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}(}|,|;|>)?$'; + let matchs = re.match(matchNoName, values); if (matchs) { - let st = values.lastIndexOf("{") - let end = values.indexOf("}") + let st = values.lastIndexOf('{'); + let end = values.indexOf('}'); let number = NumberIncrease.getAndIncrease(); - interfaceName = "AUTO_INTERFACE_%s".format(number) - let interfaceBody = values.substring(st+1, end) - let typeInterface = "{%s}".format(interfaceBody) - values = re.replaceAll(values, typeInterface, interfaceName) - interfaceBody = re.replaceAll(interfaceBody, ",", ";") - if (Object.prototype.hasOwnProperty.call(data, "interface")) { + interfaceName = 'AUTO_INTERFACE_%s'.format(number); + let interfaceBody = values.substring(st+1, end); + let typeInterface = '{%s}'.format(interfaceBody); + values = re.replaceAll(values, typeInterface, interfaceName); + interfaceBody = re.replaceAll(interfaceBody, ',', ';'); + if (Object.prototype.hasOwnProperty.call(data, 'interface')) { data.interface.push({ name: interfaceName, body: analyzeSubInterface(interfaceBody) - }) - } else if (Object.prototype.hasOwnProperty.call(results, "interface")) { + }); + } else if (Object.prototype.hasOwnProperty.call(results, 'interface')) { results.interface.push({ name: interfaceName, body: analyzeSubInterface(interfaceBody) - }) + }); } } - matchs = re.match(matchNoName, values) + matchs = re.match(matchNoName, values); if(matchs) { - let resNoNameInter = analyzeFuncNoNameInterface(data, values) - values = resNoNameInter.values + let resNoNameInter = analyzeFuncNoNameInterface(data, values); + values = resNoNameInter.values; } let result = { interfaceName: interfaceName, values: values - } - return result + }; + return result; } function analyseSubReturn(ret, data, results) { // 匿名interface返回值 function fun4(input: string): { read: number; written: number }; - let tt = null - if (ret.indexOf(":") > 0) { - ret = re.replaceAll(re.replaceAll(ret, " ", ""), "\n", "") - ret = re.replaceAll(ret, ",", ";") - ret = ret.substring(1, ret.length - 1) - tt = ret.split(";") + let tt = null; + if (ret.indexOf(':') > 0) { + ret = re.replaceAll(re.replaceAll(ret, ' ', ''), '\n', ''); + ret = re.replaceAll(ret, ',', ';'); + ret = ret.substring(1, ret.length - 1); + tt = ret.split(';'); } if (tt) { - let len = tt.length - let res = "" - let interfaceName = "" + let len = tt.length; + let res = ''; + let interfaceName = ''; for (let i=0; i= 0) { - ret = ret.replaceAll("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) + if (ret.indexOf('number') >= 0) { + ret = ret.replaceAll('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); } - return ret + return ret; } function getObjCallFunc(results, onObjCbType, values, ret) { if (results !== undefined) { results.callFunction.push({ - "name": onObjCbType, - "body": values, - "ret": ret - }) + 'name': onObjCbType, + 'body': values, + 'ret': ret + }); } } function getFuncResult(name, funcType, values, ret, isStatic) { @@ -208,66 +208,66 @@ function getFuncResult(name, funcType, values, ret, isStatic) { value: values, ret: ret, isStatic: isStatic - } - return result + }; + return result; } function getArrowCallFunc(tmp, results) { - let callbackFunc = null + let callbackFunc = null; if (tmp[2][0] !== undefined) { - callbackFunc = tmp[2][0] // 当方法的参数是回调方法,并且回调方法写法为=>函数 + callbackFunc = tmp[2][0]; // 当方法的参数是回调方法,并且回调方法写法为=>函数 } if (results !== undefined && callbackFunc !== null) { - results.callFunction.push(callbackFunc) + results.callFunction.push(callbackFunc); } } /**函数解析 */ function analyzeFunction(data, isStatic, name, values, ret, results, interfaceName = '') { - let res = analyzeFuncNoNameInterface(data, values, results) - let tmp - let funcType + let res = analyzeFuncNoNameInterface(data, values, results); + let tmp; + let funcType; if (res) { - tmp = analyzeParams(name, res.values) + tmp = analyzeParams(name, res.values); if (tmp !== null) { - values = tmp[0] - funcType = tmp[1] - getArrowCallFunc(tmp, results) + values = tmp[0]; + funcType = tmp[1]; + getArrowCallFunc(tmp, results); } } - tmp = analyzeReturn(ret) - ret = tmp[0] + tmp = analyzeReturn(ret); + ret = tmp[0]; if (tmp[1]) { // 返回类型为 Promise, 解析成等价的AsyncCallback方法 - funcType = FuncType.ASYNC + funcType = FuncType.ASYNC; // 返回值是Promise的匿名interface let paramTypeVal = analyseSubReturn(ret.substring(8, ret.length - 1), data, results); // 将返回值Promise改为AsyncCallback,作为方法的入参 - let paramType = ret.replace("Promise", "AsyncCallback") + let paramType = ret.replace('Promise', 'AsyncCallback'); if (paramTypeVal) { // 匿名interface处理 - let paramAsync = paramType.substring(14, paramType.length - 1) + let paramAsync = paramType.substring(14, paramType.length - 1); paramType = paramType.replace(paramAsync, paramTypeVal); } - values.push({name: "promise", optional: false, type: paramType, realType: paramType}) - ret = "void" // 返回值由Promise改为void,与AsyncCallback接口保持一致 + values.push({name: 'promise', optional: false, type: paramType, realType: paramType}); + ret = 'void'; // 返回值由Promise改为void,与AsyncCallback接口保持一致 } for (let j in values) { - let v = values[j] - v = getFuncParaType(v, res.interfaceName, data, results) + let v = values[j]; + v = getFuncParaType(v, res.interfaceName, data, results); if (v === null) { - NapiLog.logError("analyzeFunction is not support this type %s.".format(v), getLogErrInfo()); + NapiLog.logError('analyzeFunction is not support this type %s.'.format(v), getLogErrInfo()); } } - ret = analyseSubReturn(ret, data, results) - let result = getFuncResult(name, funcType, values, ret, isStatic) + ret = analyseSubReturn(ret, data, results); + let result = getFuncResult(name, funcType, values, ret, isStatic); if (isOnObjCallback(name)) { - let onObjCbType = getOnObjCallbackType(name, interfaceName) - getObjCallFunc(results, onObjCbType, values, ret) + let onObjCbType = getOnObjCallbackType(name, interfaceName); + getObjCallFunc(results, onObjCbType, values, ret); } - return result + return result; } module.exports = { @@ -276,4 +276,4 @@ module.exports = { getFuncParaType, analyzeFuncNoNameInterface, analyseSubReturn -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From dff868b4822f7cc95f6068b9648969521ca2530e Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:06:59 +0800 Subject: [PATCH 10/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/analy?= =?UTF-8?q?ze/interface.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/analyze/interface.js | 92 ++++++++++---------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/interface.js b/src/cli/dts2cpp/src/gen/analyze/interface.js index ec67febd..2cda0b4c 100644 --- a/src/cli/dts2cpp/src/gen/analyze/interface.js +++ b/src/cli/dts2cpp/src/gen/analyze/interface.js @@ -12,98 +12,98 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); -const { NumberIncrease } = require("../tools/common"); -const { addUniqFunc2List } = require("../tools/tool"); -const { analyzeFunction } = require("./function"); +const re = require('../tools/re'); +const { NumberIncrease } = require('../tools/common'); +const { addUniqFunc2List } = require('../tools/tool'); +const { analyzeFunction } = require('./function'); /* 匿名interface */ function analyzeNoNameInterface(valueType, valueName, rsltInterface) { - valueType = re.replaceAll(valueType, " ", "") - let matchs = re.match("{(([A-Za-z0-9_]+:[A-Za-z0-9_,;]+)*)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$", valueType) + valueType = re.replaceAll(valueType, ' ', ''); + let matchs = re.match('{(([A-Za-z0-9_]+:[A-Za-z0-9_,;]+)*)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$', valueType); if (matchs) { let number = NumberIncrease.getAndIncrease(); - let interfaceTypeName = 'AUTO_INTERFACE_%s_%s'.format(valueName, number) - let interfaceBody = valueType.substring(1, valueType.length-1) - interfaceBody = re.replaceAll(interfaceBody, ",", ";\n") + let interfaceTypeName = 'AUTO_INTERFACE_%s_%s'.format(valueName, number); + let interfaceBody = valueType.substring(1, valueType.length-1); + interfaceBody = re.replaceAll(interfaceBody, ',', ';\n'); rsltInterface.push({ name: interfaceTypeName, body: analyzeInterface(interfaceBody, rsltInterface) - }) - valueType = interfaceTypeName + }); + valueType = interfaceTypeName; } - return valueType + return valueType; } /* 去除单行注释// */ function parseNotes(data) { - let notes = data.indexOf("//") >= 0 ? data.substring(data.indexOf("//"), data.length) : ""; - while(notes != "") { - notes = notes.substring(0, notes.indexOf("\n")); - data = data.replace(notes, ""); - notes = "" - let st = data.indexOf("//"); + let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; + while(notes != '') { + notes = notes.substring(0, notes.indexOf('\n')); + data = data.replace(notes, ''); + notes = ''; + let st = data.indexOf('//'); if(st >= 0) { notes = data.substring(st, data.length); } } - return data + return data; } /**interface解析 */ function analyzeInterface(data, rsltInterface = null, results, interfaceName = '') { // same as class - let body = data - body = body.indexOf("//") < 0 ? body : parseNotes(body) - let arr = [...body.matchAll(/;\s*\n+/g)] + let body = data; + body = body.indexOf('//') < 0 ? body : parseNotes(body); + let arr = [...body.matchAll(/;\s*\n+/g)]; for (let i = 0; i < arr.length; i++) { - let result = arr[i] - body = re.replaceAll(body, result[0], ";\n") + let result = arr[i]; + body = re.replaceAll(body, result[0], ';\n'); } - body = body.split(";\n") + body = body.split(';\n'); let result = { value: [], function: [] - } + }; for (let i in body) { - let t = body[i] - t = re.replaceAll(t, "\n", "") - while (t.length > 0 && t[0] == ' ') t = t.substring(1, t.length) // 去除前面的空格 - while (t.length > 0 && t[-1] == ' ') t = t.substring(0, t.length - 1) // 去除后面的空格 - if (t == "") break // 如果t为空直接返回 - let tt = re.match(" *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)", t) - if (tt && t.indexOf("=>") < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理 - let valueName = re.getReg(t, tt.regs[1]) - let valueType = re.getReg(t, tt.regs[3]) - let index = valueType.indexOf("number") + let t = body[i]; + t = re.replaceAll(t, '\n', ''); + while (t.length > 0 && t[0] == ' ') t = t.substring(1, t.length); // 去除前面的空格 + while (t.length > 0 && t[-1] == ' ') t = t.substring(0, t.length - 1); // 去除后面的空格 + if (t == '') break; // 如果t为空直接返回 + let tt = re.match(' *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t); + if (tt && t.indexOf('=>') < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理 + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[3]); + let index = valueType.indexOf('number'); let optionalFlag = re.getReg(t, tt.regs[2]) == '?' ? true : false; while (index !== -1) { - valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) - index = valueType.indexOf("number") + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); } - valueType = analyzeNoNameInterface(valueType, valueName, rsltInterface) + valueType = analyzeNoNameInterface(valueType, valueName, rsltInterface); result.value.push({ name: valueName, type: valueType, realType: valueType, optional: optionalFlag - }) + }); } tt = re.match("(static )* *(\\$*[A-Za-z0-9_]+) *[:]? *\\(([\n 'a-zA-Z\'\'\"\":;=,_0-9?<>{}()=>|[\\]]*)\\)" - + " *(:|=>)? *([A-Za-z0-9_<>{}:;, .[\\]]+)?", t) + + ' *(:|=>)? *([A-Za-z0-9_<>{}:;, .[\\]]+)?', t); if (tt) { // 接口函数成员 - let ret = re.getReg(t, tt.regs[5]) == ''? 'void': re.getReg(t, tt.regs[5]) + let ret = re.getReg(t, tt.regs[5]) == ''? 'void': re.getReg(t, tt.regs[5]); let funcDetail = analyzeFunction(data, re.getReg(t, tt.regs[1]) != '', re.getReg(t, tt.regs[2]), - re.getReg(t, tt.regs[3]), ret, results, interfaceName) + re.getReg(t, tt.regs[3]), ret, results, interfaceName); if (funcDetail != null) { // 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法) - addUniqFunc2List(funcDetail, result.function) + addUniqFunc2List(funcDetail, result.function); } } } - return result + return result; } module.exports = { analyzeInterface, parseNotes -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From 99c1fcc03fae4ce2617191b5f451e3b0c754002a Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:07:39 +0800 Subject: [PATCH 11/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/analy?= =?UTF-8?q?ze/namespace.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/analyze/namespace.js | 290 +++++++++---------- 1 file changed, 145 insertions(+), 145 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/namespace.js b/src/cli/dts2cpp/src/gen/analyze/namespace.js index 221fff1a..112be802 100644 --- a/src/cli/dts2cpp/src/gen/analyze/namespace.js +++ b/src/cli/dts2cpp/src/gen/analyze/namespace.js @@ -12,27 +12,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); -const { removeEmptyLine, checkOutBody, addUniqFunc2List } = require("../tools/tool"); -const { analyzeFunction } = require("./function"); -const { analyzeInterface, parseNotes } = require("./interface"); -const { analyzeEnum } = require("./enum"); -const { NapiLog } = require("../tools/NapiLog"); -const { analyzeType, analyzeType2, analyzeType2Result } = require("./type"); -const { NumberIncrease, EnumValueType, getLogErrInfo } = require("../tools/common"); +const re = require('../tools/re'); +const { removeEmptyLine, checkOutBody, addUniqFunc2List } = require('../tools/tool'); +const { analyzeFunction } = require('./function'); +const { analyzeInterface, parseNotes } = require('./interface'); +const { analyzeEnum } = require('./enum'); +const { NapiLog } = require('../tools/NapiLog'); +const { analyzeType, analyzeType2, analyzeType2Result } = require('./type'); +const { NumberIncrease, EnumValueType, getLogErrInfo } = require('../tools/common'); function preProcessData(data) { - data = data.indexOf("//") < 0 ? data : parseNotes(data); - data = re.replaceAll(data, "\n{", "{"); + data = data.indexOf('//') < 0 ? data : parseNotes(data); + data = re.replaceAll(data, '\n{', '{'); return data; } function getDataByResult(result) { - let data = null + let data = null; if (result !== null) { - data = result + data = result; } - return data + return data; } /**namespace解析 */ @@ -47,42 +47,42 @@ function analyzeNamespace(data) { class: [], namespace: [], callFunction: [], - } + }; while (data !== '\n') { - let oldData = data - data = removeEmptyLine(data) - let matchs = re.match(" *\n*", data) + let oldData = data; + data = removeEmptyLine(data); + let matchs = re.match(' *\n*', data); data = preProcessData(data); // 只剩下空格和回车时,解析完成 - if (matchs && matchs.regs[0][1] === data.length) break - let parseEnumResult = parseEnum(matchs, data, result) - data = getDataByResult(parseEnumResult) + if (matchs && matchs.regs[0][1] === data.length) break; + let parseEnumResult = parseEnum(matchs, data, result); + data = getDataByResult(parseEnumResult); result = parseEnumType(result); - let parseInterResult = parseInterface(matchs, data, result) - data = getDataByResult(parseInterResult) + let parseInterResult = parseInterface(matchs, data, result); + data = getDataByResult(parseInterResult); - let parseFunctionResult = parseFunction(matchs, data, result) - data = getDataByResult(parseFunctionResult) + let parseFunctionResult = parseFunction(matchs, data, result); + data = getDataByResult(parseFunctionResult); - let parseTypeResult = parseType(matchs, data, result) - data = getDataByResult(parseTypeResult) + let parseTypeResult = parseType(matchs, data, result); + data = getDataByResult(parseTypeResult); - let parseClassResult = parseClass(matchs, data, result) - data = getDataByResult(parseClassResult) + let parseClassResult = parseClass(matchs, data, result); + data = getDataByResult(parseClassResult); - let parseNamespaceResult = parseNamespace(matchs, data, result) - data = getDataByResult(parseNamespaceResult) + let parseNamespaceResult = parseNamespace(matchs, data, result); + data = getDataByResult(parseNamespaceResult); - data = removeReg(matchs, data, result) + data = removeReg(matchs, data, result); if (oldData === data) { - NapiLog.logError("解析Namespace失败"); - NapiLog.logError("[", data.substring(0, data.length > 128 ? 128 : data.length), "]"); + NapiLog.logError('解析Namespace失败'); + NapiLog.logError('[', data.substring(0, data.length > 128 ? 128 : data.length), ']'); break; } } - return result + return result; } function parseEnumType(result) { @@ -91,13 +91,13 @@ function parseEnumType(result) { } for (let i in result.enum) { - let enumm = result.enum[i] + let enumm = result.enum[i]; // interface 匹配 for (let i in result.interface) { - let interf = result.interface[i] + let interf = result.interface[i]; if(!isValidValue(interf)) { - NapiLog.logError("parseEnumType interf is null!"); + NapiLog.logError('parseEnumType interf is null!'); return null; } @@ -105,7 +105,7 @@ function parseEnumType(result) { for (let j in interf.body.function) { let func = interf.body.function[j]; if(!isValidValue(func)) { - NapiLog.logError("parseEnumType func is null!"); + NapiLog.logError('parseEnumType func is null!'); return null; } @@ -113,17 +113,17 @@ function parseEnumType(result) { for (let k in func.value) { let v = func.value[k]; if(!isValidValue(v)) { - NapiLog.logError("parseEnumType func.value is null!"); + NapiLog.logError('parseEnumType func.value is null!'); return null; } if (v.type === enumm.name) { if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { - v.type = "NUMBER_TYPE_" + NumberIncrease.getAndIncrease(); + v.type = 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease(); } else if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v.type = "string"; + v.type = 'string'; } else { - NapiLog.logError("parseEnumType for interface function value is not support this type %s." + NapiLog.logError('parseEnumType for interface function value is not support this type %s.' .format(enumm.body.enumValueType), getLogErrInfo()); return null; } @@ -133,64 +133,64 @@ function parseEnumType(result) { } } } - return result + return result; } function parseNamespace(matchs, data, result) { - matchs = re.match("(export )*namespace ([a-zA-Z0-9]+) ({)", data) + matchs = re.match('(export )*namespace ([a-zA-Z0-9]+) ({)', data); if (matchs) { - let namespaceName = re.getReg(data, matchs.regs[2]) - let namespaceBody = checkOutBody(data, matchs.regs[3][0], null, true) + let namespaceName = re.getReg(data, matchs.regs[2]); + let namespaceBody = checkOutBody(data, matchs.regs[3][0], null, true); result.namespace.push({ name: namespaceName, body: analyzeNamespace(namespaceBody) - }) - data = data.substring(matchs.regs[3][0] + namespaceBody.length + 2, data.length) + }); + data = data.substring(matchs.regs[3][0] + namespaceBody.length + 2, data.length); if (matchs.regs[1][0] !== -1) { - result.exports.push(namespaceName) + result.exports.push(namespaceName); } } - return data + return data; } function parseClass(matchs, data, result) { matchs = re.match( - "(export )*class ([A-Za-z_0-9]+)()* *(extends [a-zA-Z_0-9, ]+)* *(implements [a-zA-Z_0-9, ]+)* *({)" - , data) + '(export )*class ([A-Za-z_0-9]+)()* *(extends [a-zA-Z_0-9, ]+)* *(implements [a-zA-Z_0-9, ]+)* *({)' + , data); if (matchs) { // class类型也解析成interface结构,该结构在后面生成C++代码时会按napi_define_class处理成C++的class - return createInterfaceData(matchs, data, result) + return createInterfaceData(matchs, data, result); } - return data + return data; } function parseEnum(matchs, data, result) { - matchs = re.match("(export )*enum *([A-Za-z_0-9]+) *({)", data) + matchs = re.match('(export )*enum *([A-Za-z_0-9]+) *({)', data); if (matchs !== null) { let enumName = re.getReg(data, matchs.regs[2]); - let enumBody = checkOutBody(data, matchs.regs[3][0], null, null) + let enumBody = checkOutBody(data, matchs.regs[3][0], null, null); result.enum.push({ name: enumName, body: analyzeEnum(enumBody.substring(1, enumBody.length - 1)) - }) - data = data.substring(matchs.regs[3][0] + enumBody.length) + }); + data = data.substring(matchs.regs[3][0] + enumBody.length); if (matchs.regs[1][0] !== -1) { - result.exports.push(enumName) + result.exports.push(enumName); } } - matchs = re.match("(export )*const ([A-Za-z_0-9]+) *[:=]{1} ([A-Za-z_0-9]+);", data) + matchs = re.match('(export )*const ([A-Za-z_0-9]+) *[:=]{1} ([A-Za-z_0-9]+);', data); if (matchs) { - let constName = re.getReg(data, matchs.regs[1]) + let constName = re.getReg(data, matchs.regs[1]); result.const.push({ name: constName, body: re.getReg(data, matchs.regs[2]) - }) - data = re.removeReg(data, matchs.regs[0]) + }); + data = re.removeReg(data, matchs.regs[0]); if (matchs.regs[1][0] !== -1) { - result.exports.push(constName) + result.exports.push(constName); } } - return data + return data; } function isValidValue(value) { @@ -202,104 +202,104 @@ function isValidValue(value) { function getTypeInfo(result, typeName, typeType, isEnum) { if (!isValidValue(result) || !isValidValue(result.type)) { - NapiLog.logError("getTypeInfo: result or result.type is invalid!"); + NapiLog.logError('getTypeInfo: result or result.type is invalid!'); } result.type.push({ name: typeName, body: typeType, isEnum: isEnum - }) + }); } function parseType(matchs, data, result) { - matchs = re.match("(export )*type ([a-zA-Z]+) *= *([\\(\\):=a-zA-Z<> |]+);", data) + matchs = re.match('(export )*type ([a-zA-Z]+) *= *([\\(\\):=a-zA-Z<> |]+);', data); if (matchs) { let typeName = re.getReg(data, matchs.regs[2]); let typeType = re.getReg(data, matchs.regs[3]); - let index = typeType.indexOf("number") + let index = typeType.indexOf('number'); if (index !== -1) { - typeType = typeType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) + typeType = typeType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); } getTypeInfo(result, typeName, typeType, false); - data = re.removeReg(data, matchs.regs[0]) + data = re.removeReg(data, matchs.regs[0]); if (matchs.regs[1][0] !== -1) { - result.exports.push(typeName) + result.exports.push(typeName); } } - matchs = re.match("(export )*type ([a-zA-Z]+) *= *([\\(\\):=a-zA-Z<> |\n']+);", data) + matchs = re.match("(export )*type ([a-zA-Z]+) *= *([\\(\\):=a-zA-Z<> |\n']+);", data); if (matchs) { let typeName = re.getReg(data, matchs.regs[2]); let typeBody = re.getReg(data, matchs.regs[3]); getTypeInfo(result, typeName, analyzeType2(typeBody.substring(1, typeBody.length - 1)), true); - data = re.removeReg(data, matchs.regs[0]) + data = re.removeReg(data, matchs.regs[0]); if (matchs.regs[1][0] !== -1) { - result.exports.push(typeName) + result.exports.push(typeName); } } - matchs = re.match("(export )*type ([a-zA-Z]+) *= *({)", data) + matchs = re.match('(export )*type ([a-zA-Z]+) *= *({)', data); if (matchs) { let typeName = re.getReg(data, matchs.regs[2]); - let typeBody = checkOutBody(data, matchs.regs[3][0], null, true) + let typeBody = checkOutBody(data, matchs.regs[3][0], null, true); if (typeBody === null) { - NapiLog.logError("ParseType typeBody is null!"); + NapiLog.logError('ParseType typeBody is null!'); } - let bodyObj = analyzeType(typeBody.substring(1, typeBody.length - 1), result.type) + let bodyObj = analyzeType(typeBody.substring(1, typeBody.length - 1), result.type); getTypeInfo(result, typeName, bodyObj, false); - data = data.substring(matchs.regs[3][0] + typeBody.length + 2, data.length) + data = data.substring(matchs.regs[3][0] + typeBody.length + 2, data.length); if (matchs.regs[1][0] !== -1) { - result.exports.push(typeName) + result.exports.push(typeName); } } - return data + return data; } function parseFunction(matchs, data, result) { - matchs = re.match("(export )*function (\\$*[A-Za-z0-9_]+) *(\\()", data) + matchs = re.match('(export )*function (\\$*[A-Za-z0-9_]+) *(\\()', data); if (null == matchs) { - matchs = re.match("(export )*function (static )*(\\$*[A-Za-z0-9_]+) *(\\()", data) + matchs = re.match('(export )*function (static )*(\\$*[A-Za-z0-9_]+) *(\\()', data); } if (null == matchs) { - matchs = re.match("(export )*function (static )*(register\\$*[A-Za-z0-9_]+) *(\\()", data) + matchs = re.match('(export )*function (static )*(register\\$*[A-Za-z0-9_]+) *(\\()', data); } if (matchs) { let funcName = re.getReg(data, - matchs.regs.length === 5 ? [matchs.regs[2][0], matchs.regs[3][1]] : matchs.regs[2]) + matchs.regs.length === 5 ? [matchs.regs[2][0], matchs.regs[3][1]] : matchs.regs[2]); let funcValue = checkOutBody(data, - matchs.regs.length === 5 ? matchs.regs[4][0] : matchs.regs[3][0], ["(", ")"], null) + matchs.regs.length === 5 ? matchs.regs[4][0] : matchs.regs[3][0], ['(', ')'], null); let funcRet = checkOutBody(data.substring(matchs.regs.length === 5 ? - matchs.regs[4][0] : matchs.regs[3][0] + funcValue.length), 0, ["", "\n"], null) + matchs.regs[4][0] : matchs.regs[3][0] + funcValue.length), 0, ['', '\n'], null); data = data.substring(matchs.regs.length === 5 ? - matchs.regs[4][0] : matchs.regs[3][0] + funcValue.length + funcRet.length) - let matchFunc = re.match(" *: *([A-Za-z0-9_<>{}\\[\\]:;, .=]+);*", funcRet) - let matchFuncArray = re.match(" *: *([A-Za-z0-9]+)(\\[]);*", funcRet) + matchs.regs[4][0] : matchs.regs[3][0] + funcValue.length + funcRet.length); + let matchFunc = re.match(' *: *([A-Za-z0-9_<>{}\\[\\]:;, .=]+);*', funcRet); + let matchFuncArray = re.match(' *: *([A-Za-z0-9]+)(\\[]);*', funcRet); if (matchFuncArray) { - funcRet = re.getReg(funcRet, [matchFuncArray.regs[1][0], matchFuncArray.regs[2][1]]) + funcRet = re.getReg(funcRet, [matchFuncArray.regs[1][0], matchFuncArray.regs[2][1]]); } else if (matchFunc) { - funcRet = re.getReg(funcRet, matchFunc.regs[1]) + funcRet = re.getReg(funcRet, matchFunc.regs[1]); } else { - funcRet = "void" + funcRet = 'void'; } - funcRet = re.replaceAll(re.replaceAll(funcRet, " ", ""), "\n", "") + funcRet = re.replaceAll(re.replaceAll(funcRet, ' ', ''), '\n', ''); - if(funcRet[funcRet.length-1] === ";"){ - funcRet = funcRet.substring(0, funcRet.length-1) + if(funcRet[funcRet.length-1] === ';'){ + funcRet = funcRet.substring(0, funcRet.length-1); } let funcDetail = analyzeFunction( - result, false, funcName, funcValue.substring(1, funcValue.length - 1), funcRet, result) + result, false, funcName, funcValue.substring(1, funcValue.length - 1), funcRet, result); if (funcDetail !== null) { // 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法) - addUniqFunc2List(funcDetail, result.function) + addUniqFunc2List(funcDetail, result.function); } if (matchs.regs[1][0] !== -1) { - result.exports.push(funcName) + result.exports.push(funcName); } } - return data + return data; } /** @@ -311,27 +311,27 @@ function parseFunction(matchs, data, result) { */ function getParentNameList(firstKey, secondKey, parentStr) { if (parentStr === '') { - return [] + return []; } - let firstParents = '' - let secondParents = '' + let firstParents = ''; + let secondParents = ''; if (parentStr.indexOf(secondKey) > 0) { // 同时出现extends和implements关键字的情况 (如 extends xx1, xx2 implements yy1, yy2) - firstParents = parentStr.split(secondKey)[0].split(firstKey)[1] - secondParents = parentStr.split(secondKey)[1].trim() + firstParents = parentStr.split(secondKey)[0].split(firstKey)[1]; + secondParents = parentStr.split(secondKey)[1].trim(); } else { // 只有extends或implements一种关键字的情况 (如 extends xx1, xx2 或者 implements yy1, yy2) - firstParents = parentStr.split(firstKey)[1] + firstParents = parentStr.split(firstKey)[1]; } - let nameList = firstParents.split(",") + let nameList = firstParents.split(','); if (secondParents !== '') { - let secondList = secondParents.split(",") - nameList.push(...secondList) + let secondList = secondParents.split(','); + nameList.push(...secondList); } - return nameList + return nameList; } /** @@ -342,71 +342,71 @@ function getParentNameList(firstKey, secondKey, parentStr) { * @returns data 原始ts文件内容中剩余未解析的部分 */ function createInterfaceData (matchs, data, result) { - let interfaceName = re.getReg(data, matchs.regs[2]) - let interfaceBody = checkOutBody(data, matchs.regs[6][0], null, null) + let interfaceName = re.getReg(data, matchs.regs[2]); + let interfaceBody = checkOutBody(data, matchs.regs[6][0], null, null); let bodyObj = analyzeInterface(interfaceBody.substring(1, interfaceBody.length - 1), result.interface, - result, interfaceName) - let extendsParent = re.getReg(data, matchs.regs[4]) - let implementParent = re.getReg(data, matchs.regs[5]) - bodyObj.parentNameList = [] + result, interfaceName); + let extendsParent = re.getReg(data, matchs.regs[4]); + let implementParent = re.getReg(data, matchs.regs[5]); + bodyObj.parentNameList = []; if(extendsParent !== '') { - bodyObj.parentNameList = getParentNameList("extends", "implements", extendsParent) + bodyObj.parentNameList = getParentNameList('extends', 'implements', extendsParent); } if(implementParent !== '') { - bodyObj.parentNameList = getParentNameList("implements", "extends", implementParent) + bodyObj.parentNameList = getParentNameList('implements', 'extends', implementParent); } for (let i in bodyObj.parentNameList) { - bodyObj.parentNameList[i] = bodyObj.parentNameList[i].trim() + bodyObj.parentNameList[i] = bodyObj.parentNameList[i].trim(); if (bodyObj.parentNameList[i] === interfaceName) { // 接口不能自己继承自己 - NapiLog.logError("The interface [%s] can not extends with itself.".format(interfaceName)) - return data + NapiLog.logError('The interface [%s] can not extends with itself.'.format(interfaceName)); + return data; } } - bodyObj.parentList = [] // 该接口继承的父类型列表 - bodyObj.childList = [] // 继承自该接口的子类型列表 + bodyObj.parentList = []; // 该接口继承的父类型列表 + bodyObj.childList = []; // 继承自该接口的子类型列表 result.interface.push({ name: interfaceName, body: bodyObj - }) - let rr = matchs.regs[6][0] - rr = matchs.regs[6][0] + interfaceBody.length - let tmp = data[rr] - data = data.substring(matchs.regs[6][0] + interfaceBody.length, data.length) + }); + let rr = matchs.regs[6][0]; + rr = matchs.regs[6][0] + interfaceBody.length; + let tmp = data[rr]; + data = data.substring(matchs.regs[6][0] + interfaceBody.length, data.length); if (matchs.regs[1][0] !== -1) { - result.exports.push(interfaceName) + result.exports.push(interfaceName); } - return data + return data; } function parseInterface(matchs, data, result) { matchs = re.match( - "(export )*interface ([A-Za-z_0-9]+)()* *(extends [a-zA-Z_0-9, ]+)* *(implements [a-zA-Z_0-9, ]+)* *({)" - , data) + '(export )*interface ([A-Za-z_0-9]+)()* *(extends [a-zA-Z_0-9, ]+)* *(implements [a-zA-Z_0-9, ]+)* *({)' + , data); if (matchs) { - return createInterfaceData (matchs, data, result) + return createInterfaceData (matchs, data, result); } - return data + return data; } function removeReg(matchs, data, result) { - matchs = re.match("export { ([a-zA-Z]+) };", data) + matchs = re.match('export { ([a-zA-Z]+) };', data); if (matchs) { - let exportName = re.getReg(data, matchs.regs[1]) - result.exports.push(exportName) - data = re.removeReg(data, matchs.regs[0]) + let exportName = re.getReg(data, matchs.regs[1]); + result.exports.push(exportName); + data = re.removeReg(data, matchs.regs[0]); } - matchs = re.match("export import [a-zA-Z]+ = [a-zA-Z\\.]+;", data) + matchs = re.match('export import [a-zA-Z]+ = [a-zA-Z\\.]+;', data); if (matchs) { - data = re.removeReg(data, matchs.regs[0]) + data = re.removeReg(data, matchs.regs[0]); } - matchs = re.match("readonly [a-zA-Z]+: [a-z\\[\\]]+;*", data) + matchs = re.match('readonly [a-zA-Z]+: [a-z\\[\\]]+;*', data); if (matchs) { - data = re.removeReg(data, matchs.regs[0]) + data = re.removeReg(data, matchs.regs[0]); } - return data + return data; } module.exports = { analyzeNamespace, @@ -416,4 +416,4 @@ module.exports = { parseInterface, parseClass, parseType -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From b13788124cf267e3228179ca57378f83b708dd13 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:08:41 +0800 Subject: [PATCH 12/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/analy?= =?UTF-8?q?ze/params.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/analyze/params.js | 84 +++++++++++------------ 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/params.js b/src/cli/dts2cpp/src/gen/analyze/params.js index 42498551..77baa679 100644 --- a/src/cli/dts2cpp/src/gen/analyze/params.js +++ b/src/cli/dts2cpp/src/gen/analyze/params.js @@ -12,14 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); -const { checkOutBody, print } = require("../tools/tool"); -const { FuncType, NumberIncrease,isFuncType, isArrowFunc,isRegisterFunc } = require("../tools/common"); -const { NapiLog } = require("../tools/NapiLog"); +const re = require('../tools/re'); +const { checkOutBody, print } = require('../tools/tool'); +const { FuncType, NumberIncrease,isFuncType, isArrowFunc,isRegisterFunc } = require('../tools/common'); +const { NapiLog } = require('../tools/NapiLog'); function isSyncFuncType(type, funcType) { let isSync = false; - if (funcType === FuncType.DIRECT && type.indexOf("Callback") >= 0 && type.indexOf("AsyncCallback") < 0 || + if (funcType === FuncType.DIRECT && type.indexOf('Callback') >= 0 && type.indexOf('AsyncCallback') < 0 || isFuncType(type) || isArrowFunc(type)) { isSync = true; } @@ -35,62 +35,62 @@ function isSyncFuncType(type, funcType) { function analyzeCallbackFunction(valueType, valueName, rsltCallFunction) { if (valueType.indexOf('=>') > 0) { - valueType = re.replaceAll(valueType, ' ', '') + valueType = re.replaceAll(valueType, ' ', ''); } - let matchs = re.match("\\(([a-zA-Z_0-9:,]+)*\\)=>([a-zA-Z_0-9]+)", valueType) + let matchs = re.match('\\(([a-zA-Z_0-9:,]+)*\\)=>([a-zA-Z_0-9]+)', valueType); if (matchs) { let number = NumberIncrease.getAndIncrease(); - let functionTypeName = 'AUTO_CALLFUNCTION_%s_%s'.format(valueName, number) + let functionTypeName = 'AUTO_CALLFUNCTION_%s_%s'.format(valueName, number); let functionRet = re.getReg(valueType, matchs.regs[2]); let functionBody = re.getReg(valueType, matchs.regs[1]); - let tmp = analyzeParams(functionTypeName, functionBody) - let bodyRes = tmp[0] + let tmp = analyzeParams(functionTypeName, functionBody); + let bodyRes = tmp[0]; for (let i in bodyRes) { - let hasProperty = Object.prototype.hasOwnProperty.call(bodyRes[i], "type") - if (hasProperty && bodyRes[i].type === "number") { - bodyRes[i].type = "NUMBER_TYPE_" + NumberIncrease.getAndIncrease(); + let hasProperty = Object.prototype.hasOwnProperty.call(bodyRes[i], 'type'); + if (hasProperty && bodyRes[i].type === 'number') { + bodyRes[i].type = 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease(); } } rsltCallFunction.push({ - "name": functionTypeName, - "body": bodyRes, - "ret": functionRet - }) - valueType = functionTypeName + 'name': functionTypeName, + 'body': bodyRes, + 'ret': functionRet + }); + valueType = functionTypeName; } - return valueType + return valueType; } /**函数参数解析 */ function analyzeParams(funcName, values) { - let result = [] - let rsltCallFunction = [] - let funcType = FuncType.DIRECT + let result = []; + let rsltCallFunction = []; + let funcType = FuncType.DIRECT; let optionalParamCount = 0; // 可选参数的个数 while (values.length > 0) { - let v = checkOutBody(values, 0, ["", ","]) + let v = checkOutBody(values, 0, ['', ',']); if (v === null) { - v = values + v = values; } - values = values.substring(v.length, values.length) - let matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *([a-zA-Z<,>|_0-9\\[\\]\\(\\):='{}]+)", v) - if (matchs === null && (funcName === "on" || funcName === "off")) { + values = values.substring(v.length, values.length); + let matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *([a-zA-Z<,>|_0-9\\[\\]\\(\\):='{}]+)", v); + if (matchs === null && (funcName === 'on' || funcName === 'off')) { // on和off的第一个参数的类型可以是一串字符 - matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *\"([a-zA-Z|_0-9\\[\\]\\(\\):='{}]+)\"", v) + matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *\"([a-zA-Z|_0-9\\[\\]\\(\\):='{}]+)\"", v); } if (matchs !== null) { - let type = re.getReg(v, matchs.regs[3]) - if (type.indexOf("Map") < 0 && !isArrowFunc(type)) { - type = type.replace(/,/g, "") + let type = re.getReg(v, matchs.regs[3]); + if (type.indexOf('Map') < 0 && !isArrowFunc(type)) { + type = type.replace(/,/g, ''); } - let valueName = re.getReg(v, matchs.regs[1]) - type = analyzeCallbackFunction(type, valueName, rsltCallFunction) + let valueName = re.getReg(v, matchs.regs[1]); + type = analyzeCallbackFunction(type, valueName, rsltCallFunction); let optionalFlag = re.getReg(v, matchs.regs[2]) === '?' ? true : false; let checkParamOk = true; @@ -98,28 +98,28 @@ function analyzeParams(funcName, values) { optionalParamCount++; } else if (optionalParamCount > 0) { // 可选参数之后不能再有必选参数,须是可选参数。 - NapiLog.logError("Invalid parameter [%s] of function [%s],".format(v, funcName) - + " the required parameter cannot follow an optional parameter."); + NapiLog.logError('Invalid parameter [%s] of function [%s],'.format(v, funcName) + + ' the required parameter cannot follow an optional parameter.'); checkParamOk = false; } if (checkParamOk) { - result.push({ "name": re.getReg(v, matchs.regs[1]), "type": type, "optional": optionalFlag, "realType": type}) - if (type.indexOf("AsyncCallback") >= 0) { - funcType = FuncType.ASYNC + result.push({ 'name': re.getReg(v, matchs.regs[1]), 'type': type, 'optional': optionalFlag, 'realType': type}); + if (type.indexOf('AsyncCallback') >= 0) { + funcType = FuncType.ASYNC; } if (isSyncFuncType(type, funcType)) { - funcType = FuncType.SYNC + funcType = FuncType.SYNC; } } } else { - NapiLog.logError("Failed to analyse parameter [%s] of function [%s].".format(v, funcName)); + NapiLog.logError('Failed to analyse parameter [%s] of function [%s].'.format(v, funcName)); } } - return [result, funcType, rsltCallFunction] + return [result, funcType, rsltCallFunction]; } module.exports = { analyzeParams -} +}; -- Gitee From dfc25dceb715b910f3cee17be7e27a068d10e0c8 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:10:16 +0800 Subject: [PATCH 13/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/analy?= =?UTF-8?q?ze/return.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/analyze/return.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/return.js b/src/cli/dts2cpp/src/gen/analyze/return.js index 1fec3b3a..138290b1 100644 --- a/src/cli/dts2cpp/src/gen/analyze/return.js +++ b/src/cli/dts2cpp/src/gen/analyze/return.js @@ -12,17 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); +const re = require('../tools/re'); /**函数返回值解析 */ function analyzeReturn(ret) { - let isPromise = false - if (ret.indexOf("Promise") >= 0) { - isPromise = true + let isPromise = false; + if (ret.indexOf('Promise') >= 0) { + isPromise = true; } - return [ret, isPromise] + return [ret, isPromise]; } module.exports = { analyzeReturn -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From f9efbad72f6f76cee49b5f2699801e143253f450 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:11:32 +0800 Subject: [PATCH 14/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/analy?= =?UTF-8?q?ze/type.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/analyze/type.js | 84 ++++++++++++------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/type.js b/src/cli/dts2cpp/src/gen/analyze/type.js index f89658a4..0d75eb29 100644 --- a/src/cli/dts2cpp/src/gen/analyze/type.js +++ b/src/cli/dts2cpp/src/gen/analyze/type.js @@ -12,97 +12,97 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); -const { NumberIncrease } = require("../tools/common"); +const re = require('../tools/re'); +const { NumberIncrease } = require('../tools/common'); /* 去除单行注释// */ function parseNotes(data) { - let notes = data.indexOf("//") >= 0 ? data.substring(data.indexOf("//"), data.length) : ""; - while(notes != "") { - notes = notes.substring(0, notes.indexOf("\n")); - data = data.replace(notes, ""); - notes = "" - let st = data.indexOf("//"); + let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; + while(notes != '') { + notes = notes.substring(0, notes.indexOf('\n')); + data = data.replace(notes, ''); + notes = ''; + let st = data.indexOf('//'); if(st >= 0) { notes = data.substring(st, data.length); } } - return data + return data; } /**type解析 */ function analyzeType(data, rsltInterface = null) { // same as class - let body = data - body = body.indexOf("//") < 0 ? body : parseNotes(body) - body = re.replaceAll(body, "\n", "").split(";") + let body = data; + body = body.indexOf('//') < 0 ? body : parseNotes(body); + body = re.replaceAll(body, '\n', '').split(';'); let result = { value: [], // function: [] - } + }; for (let i in body) { - let t = body[i] + let t = body[i]; while (t.length > 0 && t[0] == ' ') // 去除前面的空格 - t = t.substring(1, t.length) + t = t.substring(1, t.length); while (t.length > 0 && t[-1] == ' ') // 去除后面的空格 - t = t.substring(0, t.length - 1) - if (t == "") break // 如果t为空直接返回 - let tt = re.match(" *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)", t) - if (tt && t.indexOf("=>") < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理 - let valueName = re.getReg(t, tt.regs[1]) - let valueType = re.getReg(t, tt.regs[3]) - let index = valueType.indexOf("number") + t = t.substring(0, t.length - 1); + if (t == '') break; // 如果t为空直接返回 + let tt = re.match(' *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t); + if (tt && t.indexOf('=>') < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理 + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[3]); + let index = valueType.indexOf('number'); let optionalFlag = re.getReg(t, tt.regs[2]) == '?' ? true : false; while (index !== -1) { - valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) - index = valueType.indexOf("number") + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); } result.value.push({ name: valueName, type: valueType, optional: optionalFlag - }) + }); } } - return result + return result; } function analyzeType2(data) { - let body = re.replaceAll(data, " ", "").split("'|'") + let body = re.replaceAll(data, ' ', '').split("'|'"); let result = { element: [], function: [], enumValueType: 0 // 0代表数字,1代表字符串 - } + }; for (let i in body) { - let bodyContent = body[i] + let bodyContent = body[i]; while (bodyContent.length > 0 && bodyContent[0] == ' ') { - bodyContent = bodyContent.substring(1, bodyContent.length) + bodyContent = bodyContent.substring(1, bodyContent.length); } while (bodyContent.length > 0 && bodyContent[-1] == ' ') { - bodyContent = bodyContent.substring(0, bodyContent.length - 1) + bodyContent = bodyContent.substring(0, bodyContent.length - 1); } - if (bodyContent == "") { - break + if (bodyContent == '') { + break; } - analyzeType2Result(result, bodyContent, i) + analyzeType2Result(result, bodyContent, i); } - return result + return result; } function analyzeType2Result(result, bodyContent, index) { - let regString = re.match(" *([a-zA-Z0-9_]+) *", bodyContent) + let regString = re.match(' *([a-zA-Z0-9_]+) *', bodyContent); if (regString) { - let elementName = re.getReg(bodyContent, regString.regs[1]) + let elementName = re.getReg(bodyContent, regString.regs[1]); elementName = 'NAME_' + elementName.toUpperCase() - let elementValue = re.getReg(bodyContent, regString.regs[1]) + let elementValue = re.getReg(bodyContent, regString.regs[1]); result.element.push({ name: elementName, value: elementValue, type: 'string' - }) - result.enumValueType = 1 + }); + result.enumValueType = 1; } - return result + return result; } module.exports = { @@ -110,4 +110,4 @@ module.exports = { analyzeType2, analyzeType2Result, parseNotes -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From 559ae5b6666284772e44020278bf1a639591bfa3 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:11:36 +0800 Subject: [PATCH 15/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/cmd?= =?UTF-8?q?=5Fgen.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/cmd_gen.js | 44 +++++++++++++++--------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/cmd_gen.js b/src/cli/dts2cpp/src/gen/cmd_gen.js index b94cb0fe..66369acf 100644 --- a/src/cli/dts2cpp/src/gen/cmd_gen.js +++ b/src/cli/dts2cpp/src/gen/cmd_gen.js @@ -12,25 +12,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const main = require("./main"); -const tsMain = require("../tsGen/tsMain"); -const re = require("./tools/re"); -const { checkFileError } = require("./tools/common"); -const { NapiLog } = require("./tools/NapiLog"); -const path = require("path"); -const stdio = require("stdio"); +const main = require('./main'); +const tsMain = require('../tsGen/tsMain'); +const re = require('./tools/re'); +const { checkFileError } = require('./tools/common'); +const { NapiLog } = require('./tools/NapiLog'); +const path = require('path'); +const stdio = require('stdio'); var fs = require('fs'); -const { print } = require("./tools/tool"); +const { print } = require('./tools/tool'); let ops = stdio.getopt({ - 'filename': { key: 'f', args: 1, description: ".d.ts file", default: "" }, - 'directory': { key: 'd', args: 1, description: ".d.ts directory", default: "" }, - 'imports': { key: 'i', args: 1, description: "enable or disable support imports self-define file", default: false }, - 'out': { key: 'o', args: 1, description: "output directory", default: "." }, - 'loglevel': { key: 'l', args: 1, description: "Log Level : 0~3", default: "1" }, + 'filename': { key: 'f', args: 1, description: '.d.ts file', default: '' }, + 'directory': { key: 'd', args: 1, description: '.d.ts directory', default: '' }, + 'imports': { key: 'i', args: 1, description: 'enable or disable support imports self-define file', default: false }, + 'out': { key: 'o', args: 1, description: 'output directory', default: '.' }, + 'loglevel': { key: 'l', args: 1, description: 'Log Level : 0~3', default: '1' }, // 新增控制number类型转C++类型参数 - 'numbertype':{key: 'n', args: 1, description: "optional elemtype: basic cpp elemtype", default: "uint32_t"}, - 'tsGen':{key: 't', args: 1, description: "enable or disable generate typescript file", default: false }, + 'numbertype':{key: 'n', args: 1, description: 'optional elemtype: basic cpp elemtype', default: 'uint32_t'}, + 'tsGen':{key: 't', args: 1, description: 'enable or disable generate typescript file', default: false }, /* 新增业务代码可配置参数:写在json文件里: * [{"includeName":"xxx.h", "cppName":"xxx.cpp","interfaceName": "functest", @@ -41,13 +41,13 @@ let ops = stdio.getopt({ }); -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; var imports = ops.imports; if (fileNames == null && pathDir == null) { - 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 != '') { readDirFiles(); } else if (fileNames != '') { @@ -78,7 +78,7 @@ function handleDirFiles(files) { if (i === files.length) { return; } - let data = fs.statSync(path.join(pathDir + '', files[i])) + let data = fs.statSync(path.join(pathDir + '', files[i])); if (data.isFile()) { let fileName = files[i]; checkGenerate(pathDir + '/' + fileName); @@ -107,16 +107,16 @@ function getJsonCfg(currentPath) { let jsonCfg = null; // cfg.json 配置文件 currentPath = currentPath.replace(/(^\s*)|(\s*$)/g, ''); // trim before and after espace let jsonFilePath = path.join(currentPath); - let jsonFile = fs.readFileSync(jsonFilePath, { encoding: "utf8" }); + let jsonFile = fs.readFileSync(jsonFilePath, { encoding: 'utf8' }); jsonCfg = JSON.parse(jsonFile); return jsonCfg; } function checkGenerate(fileName) { - NapiLog.logInfo("check file []".format(fileName)) + NapiLog.logInfo('check file []'.format(fileName)); let suffix = fileName.split('.').pop().toLowerCase(); if (ops.tsGen == 'true' && suffix === 'h') { - NapiLog.logInfo("convert .h file to .ts file...") + NapiLog.logInfo('convert .h file to .ts file...'); tsMain.doGenerate(fileName, ops.out); return; } @@ -124,7 +124,7 @@ function checkGenerate(fileName) { let tt = re.match('(@ohos\.)*([.a-z_A-Z0-9]+).d.ts', fn); if (tt) { let result = checkFileError(fileName); - let jsonConfig + let jsonConfig; if (ops.serviceCode) { jsonConfig = getJsonCfg(ops.serviceCode); } -- Gitee From d322c95989dfa834058d63968ae8c78dbfb9cfa7 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:13:04 +0800 Subject: [PATCH 16/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/debug?= =?UTF-8?q?.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/debug.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/debug.js b/src/cli/dts2cpp/src/gen/debug.js index 5f51395d..9a38dd05 100644 --- a/src/cli/dts2cpp/src/gen/debug.js +++ b/src/cli/dts2cpp/src/gen/debug.js @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const main = require("../../hdc/appCodeGen/src/main"); -const { getJsonCfg } = require("../../hdc/appCodeGen/src/app_code_gen"); -const { NapiLog } = require("./tools/NapiLog"); -const re = require("./tools/re"); +const main = require('../../hdc/appCodeGen/src/main'); +const { getJsonCfg } = require('../../hdc/appCodeGen/src/app_code_gen'); +const { NapiLog } = require('./tools/NapiLog'); +const re = require('./tools/re'); //let file_path = `./@ohos.napitest.d.ts` @@ -33,16 +33,16 @@ const re = require("./tools/re"); // let file_path = `D:\\DOC\\NAPI\\feature\\supported\\@ohos.napitestsupportSingle.d.ts` // let file_path = './test/storytest/test_type/@ohos.test.d.ts' -let file_path = 'D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\@ohos.napitest.d.ts' -let fn = re. getFileInPath(file_path) -let jsonCfg = `D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\funTestCfg.json` -NapiLog.init(NapiLog.LEV_INFO, "napi_gen.log") -NapiLog.logError("Begin to test."); -let funcConfig +let file_path = 'D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\@ohos.napitest.d.ts'; +let fn = re. getFileInPath(file_path); +let jsonCfg = `D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\funTestCfg.json`; +NapiLog.init(NapiLog.LEV_INFO, 'napi_gen.log'); +NapiLog.logError('Begin to test.'); +let funcConfig; if (jsonCfg) { funcConfig = getJsonCfg(jsonCfg); } -let tt = re.match("(@ohos\.)*([.a-z_A-Z0-9]+).d.ts", fn) // @ohos\.[a-zA-Z0-9]+\.d\.ts +let tt = re.match('(@ohos\.)*([.a-z_A-Z0-9]+).d.ts', fn); // @ohos\.[a-zA-Z0-9]+\.d\.ts if (tt) { - main.doGenerate(file_path, "D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\appOut", funcConfig) + main.doGenerate(file_path, 'D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\appOut', funcConfig); } -- Gitee From f6e1237d508275ff429ec237bf3f2b309c8cc4cc Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:14:33 +0800 Subject: [PATCH 17/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/exten?= =?UTF-8?q?d/binding=5Fgyp.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/extend/binding_gyp.js | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/extend/binding_gyp.js b/src/cli/dts2cpp/src/gen/extend/binding_gyp.js index d285bc73..2e6fd626 100644 --- a/src/cli/dts2cpp/src/gen/extend/binding_gyp.js +++ b/src/cli/dts2cpp/src/gen/extend/binding_gyp.js @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { writeFile } = require("../tools/FileRW"); -const re = require("../tools/re"); +const { writeFile } = require('../tools/FileRW'); +const re = require('../tools/re'); let gypTemplete = ` { @@ -29,30 +29,30 @@ let gypTemplete = ` } ] } -` +`; /**创建nodejs编译文件,用于在ubuntu测试 */ function generateGYP(destDir, implName, license, bindingCpp) { - let ss = gypTemplete.replaceAll("[implName]", implName) - ss = ss.replaceAll("[businessCodeCpp]", bindingCpp) + let ss = gypTemplete.replaceAll('[implName]', implName); + ss = ss.replaceAll('[businessCodeCpp]', bindingCpp); if (license) { - let s2 = license.substring(2, license.length - 2).split("\n"); - license = ""; + let s2 = license.substring(2, license.length - 2).split('\n'); + license = ''; for (let i = 1; i < s2.length; i++) { if (s2[i].length > 0) { - while (s2[i][0] == " ") s2[i] = s2[i].substring(1); - if (s2[i].length > 3 && s2[i][0] == "*") { - license += "#" + s2[i].substring(1) + "\n"; + while (s2[i][0] == ' ') s2[i] = s2[i].substring(1); + if (s2[i].length > 3 && s2[i][0] == '*') { + license += '#' + s2[i].substring(1) + '\n'; } } } } - writeFile(re.pathJoin(destDir, "binding.gyp"), null != license ? (license + "\n" + ss) : ss) + writeFile(re.pathJoin(destDir, 'binding.gyp'), null != license ? (license + '\n' + ss) : ss); - writeFile(re.pathJoin(destDir, "test.sh"), "node-gyp configure build && sleep 0.5 && node --expose-gc test.js") + writeFile(re.pathJoin(destDir, 'test.sh'), 'node-gyp configure build && sleep 0.5 && node --expose-gc test.js'); } module.exports = { generateGYP -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From 97b9c9091491743ec7c166865658580f22d08edf Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:15:31 +0800 Subject: [PATCH 18/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/exten?= =?UTF-8?q?d/build=5Fgn.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/extend/build_gn.js | 28 +++++++++++----------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/extend/build_gn.js b/src/cli/dts2cpp/src/gen/extend/build_gn.js index db3fa035..4079c089 100644 --- a/src/cli/dts2cpp/src/gen/extend/build_gn.js +++ b/src/cli/dts2cpp/src/gen/extend/build_gn.js @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { writeFile } = require("../tools/FileRW"); -const re = require("../tools/re"); +const { writeFile } = require('../tools/FileRW'); +const re = require('../tools/re'); let gnTemplete = `\ import("//build/ohos.gni") @@ -46,30 +46,30 @@ ohos_shared_library("[implName]") part_name = "[partName]" subsystem_name = "[subsystemName]" } -` +`; /**创建nodejs编译文件,用于在ubuntu测试 */ function generateGN(destDir, implName, license, partName, buildCpp) { let subsystemName = implName; - let gnFile = gnTemplete.replaceAll("[implName]", implName); - gnFile = gnFile.replaceAll("[businessCodeCpp]", buildCpp) - gnFile = gnFile.replaceAll("[subsystemName]", subsystemName); - gnFile = gnFile.replaceAll("[partName]", partName); + let gnFile = gnTemplete.replaceAll('[implName]', implName); + gnFile = gnFile.replaceAll('[businessCodeCpp]', buildCpp); + gnFile = gnFile.replaceAll('[subsystemName]', subsystemName); + gnFile = gnFile.replaceAll('[partName]', partName); if (license) { - let s2 = license.substring(2, license.length - 2).split("\n"); - license = ""; + let s2 = license.substring(2, license.length - 2).split('\n'); + license = ''; for (let i = 1; i < s2.length; i++) { if (s2[i].length > 0) { - while (s2[i][0] == " ") s2[i] = s2[i].substring(1); - if (s2[i].length > 3 && s2[i][0] == "*") { - license += "#" + s2[i].substring(1) + "\n"; + while (s2[i][0] == ' ') s2[i] = s2[i].substring(1); + if (s2[i].length > 3 && s2[i][0] == '*') { + license += '#' + s2[i].substring(1) + '\n'; } } } } - writeFile(re.pathJoin(destDir, "BUILD.gn"), null != license ? (license + "\n" + gnFile) : gnFile) + writeFile(re.pathJoin(destDir, 'BUILD.gn'), null != license ? (license + '\n' + gnFile) : gnFile); } module.exports = { generateGN -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From be4a2769ac10356376f258887e28140c9d5959a2 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:15:37 +0800 Subject: [PATCH 19/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/exten?= =?UTF-8?q?d/tool=5Futility.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/extend/tool_utility.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/extend/tool_utility.js b/src/cli/dts2cpp/src/gen/extend/tool_utility.js index 21cae6f0..735ad6bd 100644 --- a/src/cli/dts2cpp/src/gen/extend/tool_utility.js +++ b/src/cli/dts2cpp/src/gen/extend/tool_utility.js @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { writeFile } = require("../tools/FileRW"); -const re = require("../tools/re"); +const { writeFile } = require('../tools/FileRW'); +const re = require('../tools/re'); let xNapiToolH = `\ #ifndef CC_TOOL_H @@ -254,7 +254,7 @@ private: }; #endif -` +`; let xNapiToolCpp = ` @@ -1777,13 +1777,13 @@ void XNapiTool::CallThreadSafeFunc(std::string eventName) { return; } } -` +`; function generateBase(destDir, license) { - writeFile(re.pathJoin(destDir, "tool_utility.h"), null != license ? (license + "\n" + xNapiToolH) : xNapiToolH) - writeFile(re.pathJoin(destDir, "tool_utility.cpp"), null != license ? (license + "\n" + xNapiToolCpp):xNapiToolCpp) + writeFile(re.pathJoin(destDir, 'tool_utility.h'), null != license ? (license + '\n' + xNapiToolH) : xNapiToolH); + writeFile(re.pathJoin(destDir, 'tool_utility.cpp'), null != license ? (license + '\n' + xNapiToolCpp):xNapiToolCpp); } module.exports = { generateBase -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From b4e7ba21c660b9865909709410b60d2407b87960 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:16:02 +0800 Subject: [PATCH 20/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/gener?= =?UTF-8?q?ate.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/generate.js | 180 ++++++++++++++-------------- 1 file changed, 90 insertions(+), 90 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/generate.js b/src/cli/dts2cpp/src/gen/generate.js index 11c5c4cd..caab0c86 100644 --- a/src/cli/dts2cpp/src/gen/generate.js +++ b/src/cli/dts2cpp/src/gen/generate.js @@ -14,17 +14,17 @@ */ // 生成BUILD.gn // 生成tool_utility.h,生成tool_utility.cpp -const { replaceAll } = require("./tools/tool"); -const { generateNamespace } = require("./generate/namespace"); -const { writeFile } = require("./tools/FileRW"); -const re = require("./tools/re"); -const { generateGYP } = require("./extend/binding_gyp"); -const { generateGN } = require("./extend/build_gn"); -const { generateBase } = require("./extend/tool_utility"); -const { NumberIncrease, jsonCfgList } = require("./tools/common"); -const os = require("os"); -const path = require('path') -const { NapiLog } = require("./tools/NapiLog"); +const { replaceAll } = require('./tools/tool'); +const { generateNamespace } = require('./generate/namespace'); +const { writeFile } = require('./tools/FileRW'); +const re = require('./tools/re'); +const { generateGYP } = require('./extend/binding_gyp'); +const { generateGN } = require('./extend/build_gn'); +const { generateBase } = require('./extend/tool_utility'); +const { NumberIncrease, jsonCfgList } = require('./tools/common'); +const os = require('os'); +const path = require('path'); +const { NapiLog } = require('./tools/NapiLog'); var fs = require('fs'); let moduleHTemplete = `\ @@ -43,7 +43,7 @@ let moduleHTemplete = `\ [implH_detail] #endif // IMPL_[impl_name_upper]_H -` +`; let moduleCppTmplete = `\ #include @@ -129,7 +129,7 @@ extern "C" __attribute__((constructor)) void Register_[implName]_Module(void) { napi_module_register(&g_[implName]_Module); } -` +`; let implHTemplete = `\ #ifndef IMPL_[impl_name_upper]_H @@ -146,86 +146,86 @@ let implHTemplete = `\ [numberUsing] [implH_detail] #endif // IMPL_[impl_name_upper]_H -` +`; let implCppTemplete = `\ #include "[implName].h" #include "[implName]_middle.h" [include_configure_hCode] [implCpp_detail] -` -var genFileList = [] +`; +var genFileList = []; function deleteFolder(folderPath) { if (fs.existsSync(folderPath)) { - fs.rmSync(folderPath, {"recursive": true}) + fs.rmSync(folderPath, {'recursive': true}); } } function createFolder(folderPath) { if (!fs.existsSync(folderPath)) { - fs.mkdirSync(folderPath) + fs.mkdirSync(folderPath); } } function formatCode(destDir) { - let sysInfo = os.platform() - let clangFmtName = sysInfo === 'win32' ? "clang-format.exe" : "clang-format" + let sysInfo = os.platform(); + let clangFmtName = sysInfo === 'win32' ? 'clang-format.exe' : 'clang-format'; let callPath = NapiLog.getCallPath(); - callPath = callPath.substring(callPath.indexOf("[") + 1, callPath.indexOf("src")); - let dumyClangFmtFile = path.join(callPath, clangFmtName) - let dumyFmtCfgFile = path.join(callPath, ".clang-format") + callPath = callPath.substring(callPath.indexOf('[') + 1, callPath.indexOf('src')); + let dumyClangFmtFile = path.join(callPath, clangFmtName); + let dumyFmtCfgFile = path.join(callPath, '.clang-format'); if(!fs.existsSync(dumyClangFmtFile)) { - NapiLog.logInfo("Warning: clang-format does not exist, can not format cpp file."); - return + NapiLog.logInfo('Warning: clang-format does not exist, can not format cpp file.'); + return; } // 使用pkg打包的napi_generator工具,其中的clang-format程序在运行时是解压到一个名为snapshot的虚拟目录中的,如C:\snapshot\napi_generator\ // 虚拟目录中的clang-format程序不能直接运行,必须先将它拷贝到本地硬盘的真实目录下。 - createFolder(path.resolve("./tmpLocal")) - let localClangFmtFile = path.resolve("./tmpLocal/" + clangFmtName) // clang-format可执行程序 - let localFmtCfgFile = path.resolve("./tmpLocal/.clang-format") // clang-format格式化配置文件 - fs.copyFileSync(dumyClangFmtFile, localClangFmtFile) - fs.copyFileSync(dumyFmtCfgFile, localFmtCfgFile) + createFolder(path.resolve('./tmpLocal')); + let localClangFmtFile = path.resolve('./tmpLocal/' + clangFmtName); // clang-format可执行程序 + let localFmtCfgFile = path.resolve('./tmpLocal/.clang-format'); // clang-format格式化配置文件 + fs.copyFileSync(dumyClangFmtFile, localClangFmtFile); + fs.copyFileSync(dumyFmtCfgFile, localFmtCfgFile); - let execSync = require("child_process").execSync + let execSync = require('child_process').execSync; if (sysInfo != 'win32') { // linux系统下需要为临时复制的clang-format程序增加可执行权限 - execSync("chmod +x " + "\"" + localClangFmtFile + "\"") + execSync('chmod +x ' + '\"' + localClangFmtFile + '\"'); } for (let i = 0; i < genFileList.length; ++i) { // 文件路径前后要用引号包含,防止因为路径中存在空格而导致命令执行失败 (windows的文件夹允许有空格) - let cmd = "\"" + localClangFmtFile + "\" -style=file -i \"" + path.resolve(path.join(destDir, genFileList[i])) - + "\"" + let cmd = '\"' + localClangFmtFile + '\" -style=file -i \"' + path.resolve(path.join(destDir, genFileList[i])) + + '\"'; try { - execSync(cmd) // C++文件格式化 + execSync(cmd); // C++文件格式化 } catch (err) { - NapiLog.logError("Failed to format code, exception: " + err.stderr) + NapiLog.logError('Failed to format code, exception: ' + err.stderr); } } // 格式化结束后,删除临时目录文件 - deleteFolder(path.resolve("./tmpLocal")) + deleteFolder(path.resolve('./tmpLocal')); } function analyzeJsonCfg(jsonCfg) { let len = jsonCfg.length; - let jsonConfig = [] + let jsonConfig = []; // 将json文件的数据存入jsonCfgList中 for (let i = 0; i < len; i++) { - let interfaceBody = null - if (jsonCfg[i].interfaceName.indexOf("::") > 0) { - let tt = jsonCfg[i].interfaceName.split("::") + let interfaceBody = null; + if (jsonCfg[i].interfaceName.indexOf('::') > 0) { + let tt = jsonCfg[i].interfaceName.split('::'); interfaceBody = { className: tt[0], funcName: tt[1], - } + }; } else { interfaceBody = { - className: "", + className: '', funcName: jsonCfg[i].interfaceName, - } + }; } jsonConfig.push({ @@ -233,9 +233,9 @@ function analyzeJsonCfg(jsonCfg) { cppName: jsonCfg[i].cppName, interfaceName: interfaceBody, serviceCode: jsonCfg[i].serviceCode.replaceAll('\\n', '\n'), - }) + }); } - jsonCfgList.push(jsonConfig) + jsonCfgList.push(jsonConfig); } function generateAll(structOfTs, destDir, moduleName, numberType, jsonCfg) { @@ -250,82 +250,82 @@ function generateAll(structOfTs, destDir, moduleName, numberType, jsonCfg) { analyzeJsonCfg(jsonCfg); } - let result = generateNamespace(ns0.name, ns0.body) + let result = generateNamespace(ns0.name, ns0.body); - jsonCfgList.pop() + jsonCfgList.pop(); - let numberUsing = "" - var numbertype = "uint32_t"; - if(numberType != "" && numberType != undefined){ + let numberUsing = ''; + var numbertype = 'uint32_t'; + if(numberType != '' && numberType != undefined){ numbertype = numberType; } for (let i = 1; i < NumberIncrease.get(); i++) { - numberUsing += "using NUMBER_TYPE_%d = ".format(i) + numbertype + ";\n" + numberUsing += 'using NUMBER_TYPE_%d = '.format(i) + numbertype + ';\n'; } generateMiddleH(ns0, result, destDir, license); generateMiddleCpp(result, ns0, moduleName, destDir, license); generateImplH(ns0, numberUsing, result, structOfTs, destDir, license); - let implCpp = implCppTemplete.replaceAll("[implName]", ns0.name) - let bindingCpp = '' - let buildCpp = '' - let includeH = '' + let implCpp = implCppTemplete.replaceAll('[implName]', ns0.name); + let bindingCpp = ''; + let buildCpp = ''; + let includeH = ''; if (jsonCfg) { let includeHCppRes = includeHCppFunc(jsonCfg, includeH, bindingCpp, buildCpp); bindingCpp = includeHCppRes[0]; includeH = includeHCppRes[1]; buildCpp = includeHCppRes[2]; } - implCpp = implCpp.replaceAll("[include_configure_hCode]", includeH); - implCpp = implCpp.replaceAll("[implCpp_detail]", result.implCpp) - writeFile(re.pathJoin(destDir, "%s.cpp".format(ns0.name)), null != license ? (license + "\n" + implCpp) : implCpp) - genFileList.push("%s.cpp".format(ns0.name)); - - let partName = moduleName.replace('.', '_') - generateGYP(destDir, ns0.name, license, bindingCpp) // 生成ubuntu下测试的编译脚本 - generateGN(destDir, ns0.name, license, partName, buildCpp) // 生成BUILD.gn for ohos - generateBase(destDir, license) // tool_utility.h/cpp - genFileList.push("tool_utility.h"); - genFileList.push("tool_utility.cpp"); + implCpp = implCpp.replaceAll('[include_configure_hCode]', includeH); + implCpp = implCpp.replaceAll('[implCpp_detail]', result.implCpp); + writeFile(re.pathJoin(destDir, '%s.cpp'.format(ns0.name)), null != license ? (license + '\n' + implCpp) : implCpp); + genFileList.push('%s.cpp'.format(ns0.name)); + + let partName = moduleName.replace('.', '_'); + generateGYP(destDir, ns0.name, license, bindingCpp); // 生成ubuntu下测试的编译脚本 + generateGN(destDir, ns0.name, license, partName, buildCpp); // 生成BUILD.gn for ohos + generateBase(destDir, license); // tool_utility.h/cpp + genFileList.push('tool_utility.h'); + genFileList.push('tool_utility.cpp'); formatCode(destDir); } function generateImplH(ns0, numberUsing, result, structOfTs, destDir, license) { - let implH = replaceAll(implHTemplete, "[impl_name_upper]", ns0.name.toUpperCase()); - implH = implH.replaceAll("[numberUsing]", numberUsing); - implH = replaceAll(implH, "[implH_detail]", result.implH); + let implH = replaceAll(implHTemplete, '[impl_name_upper]', ns0.name.toUpperCase()); + implH = implH.replaceAll('[numberUsing]', numberUsing); + implH = replaceAll(implH, '[implH_detail]', result.implH); let imports = ''; for (let i = 0; i < structOfTs.imports.length; i++) { imports += structOfTs.imports[i]; } - implH = replaceAll(implH, "[importTs]", imports); - writeFile(re.pathJoin(destDir, "%s.h".format(ns0.name)), null != license ? (license + "\n" + implH) : implH); - genFileList.push("%s.h".format(ns0.name)); + implH = replaceAll(implH, '[importTs]', imports); + writeFile(re.pathJoin(destDir, '%s.h'.format(ns0.name)), null != license ? (license + '\n' + implH) : implH); + genFileList.push('%s.h'.format(ns0.name)); } function generateMiddleCpp(result, ns0, moduleName, destDir, license) { - let middleCpp = replaceAll(moduleCppTmplete, "[body_replace]", result.middleBody); - middleCpp = replaceAll(middleCpp, "[init_replace]", result.middleInit); - middleCpp = replaceAll(middleCpp, "[implName]", ns0.name); - middleCpp = replaceAll(middleCpp, "[modulename]", moduleName); + let middleCpp = replaceAll(moduleCppTmplete, '[body_replace]', result.middleBody); + middleCpp = replaceAll(middleCpp, '[init_replace]', result.middleInit); + middleCpp = replaceAll(middleCpp, '[implName]', ns0.name); + middleCpp = replaceAll(middleCpp, '[modulename]', moduleName); genFileList.splice(0, genFileList.length); - writeFile(re.pathJoin(destDir, "%s_middle.cpp".format(ns0.name)), - null != license ? (license + "\n" + middleCpp) : middleCpp); - genFileList.push("%s_middle.cpp".format(ns0.name)); + writeFile(re.pathJoin(destDir, '%s_middle.cpp'.format(ns0.name)), + null != license ? (license + '\n' + middleCpp) : middleCpp); + genFileList.push('%s_middle.cpp'.format(ns0.name)); } // 将业务代码的头文件导入,若重复则跳过 function includeHCppFunc(jsonCfg, includeH, bindingCpp, buildCpp) {; for (let i = 0; i < jsonCfg.length; i++) { - if (jsonCfg[i].includeName !== "") { + if (jsonCfg[i].includeName !== '') { let includeNamePath = jsonCfg[i].includeName; let tmp = '#include "%s"\n'.format(includeNamePath); if (includeH.indexOf(tmp) < 0) { includeH += tmp; } } - if (jsonCfg[i].cppName !== "") { + if (jsonCfg[i].cppName !== '') { let cppNamePath = jsonCfg[i].cppName; let tmpCpp = '\n "%s",'.format(cppNamePath); let tmpBuildCpp = '\n "%s",'.format(cppNamePath); @@ -339,15 +339,15 @@ function includeHCppFunc(jsonCfg, includeH, bindingCpp, buildCpp) {; } function generateMiddleH(ns0, result, destDir, license) { - let implName = ns0.name + "_middle"; - let middleH = replaceAll(moduleHTemplete, "[impl_name_upper]", implName.toUpperCase()); - middleH = replaceAll(middleH, "[implName]", ns0.name); - middleH = replaceAll(middleH, "[implH_detail]", result.middleH); - writeFile(re.pathJoin(destDir, "%s_middle.h".format(ns0.name)), - null != license ? (license + "\n" + middleH) : middleH); - genFileList.push("%s_middle.h".format(ns0.name)); + let implName = ns0.name + '_middle'; + let middleH = replaceAll(moduleHTemplete, '[impl_name_upper]', implName.toUpperCase()); + middleH = replaceAll(middleH, '[implName]', ns0.name); + middleH = replaceAll(middleH, '[implH_detail]', result.middleH); + writeFile(re.pathJoin(destDir, '%s_middle.h'.format(ns0.name)), + null != license ? (license + '\n' + middleH) : middleH); + genFileList.push('%s_middle.h'.format(ns0.name)); } module.exports = { generateAll -} +}; \ No newline at end of file -- Gitee From d21e4191ad1ac985e5cb1f0f62b557db3ea4c459 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:17:21 +0800 Subject: [PATCH 21/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/gener?= =?UTF-8?q?ate/class.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/generate/class.js | 152 +++++++++++----------- 1 file changed, 76 insertions(+), 76 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/generate/class.js b/src/cli/dts2cpp/src/gen/generate/class.js index 99003bdf..60921f34 100644 --- a/src/cli/dts2cpp/src/gen/generate/class.js +++ b/src/cli/dts2cpp/src/gen/generate/class.js @@ -12,14 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { generateFunctionDirect } = require("./function_direct"); -const { generateFunctionSync } = require("./function_sync"); -const { generateFunctionAsync } = require("./function_async"); -const { FuncType, InterfaceList, getArrayType } = require("../tools/common"); -const { jsToC } = require("./param_generate"); -const { cToJs } = require("./return_generate"); -const re = require("../tools/re"); -const { NapiLog } = require("../tools/NapiLog"); +const { generateFunctionDirect } = require('./function_direct'); +const { generateFunctionSync } = require('./function_sync'); +const { generateFunctionAsync } = require('./function_async'); +const { FuncType, InterfaceList, getArrayType } = require('../tools/common'); +const { jsToC } = require('./param_generate'); +const { cToJs } = require('./return_generate'); +const re = require('../tools/re'); +const { NapiLog } = require('../tools/NapiLog'); let middleBodyTmplete = ` class [className]_middle { @@ -38,21 +38,21 @@ public: delete p2; } [static_funcs] -};` +};`; function generateVariable(name, type, variable, className) { - if (type == "string") variable.hDefine += "\n std::string %s;".format(name) - else if (type.substring(0, 12) == "NUMBER_TYPE_") variable.hDefine += "\n %s %s;".format(type, name) - else if (InterfaceList.getValue(type)) variable.hDefine += "\n %s %s;".format(type, name) - else if (type.indexOf("Array<") == 0) { - let type2 = getArrayType(type) - if (type2 == "string") type2 = "std::string" - if (type2 == "boolean") type2 = "bool" - variable.hDefine += "\n std::vector<%s> %s;".format(type2, name) - } else if (type == "boolean") { - variable.hDefine += "\n bool %s;".format(name) - } else if (type.indexOf("[]") == 0) { - variable.hDefine += "\n std::vector<%s> %s;".format(type, name) + if (type == 'string') variable.hDefine += '\n std::string %s;'.format(name); + else if (type.substring(0, 12) == 'NUMBER_TYPE_') variable.hDefine += '\n %s %s;'.format(type, name); + else if (InterfaceList.getValue(type)) variable.hDefine += '\n %s %s;'.format(type, name); + else if (type.indexOf('Array<') == 0) { + let type2 = getArrayType(type); + if (type2 == 'string') type2 = 'std::string'; + if (type2 == 'boolean') type2 = 'bool'; + variable.hDefine += '\n std::vector<%s> %s;'.format(type2, name); + } else if (type == 'boolean') { + variable.hDefine += '\n bool %s;'.format(name); + } else if (type.indexOf('[]') == 0) { + variable.hDefine += '\n std::vector<%s> %s;'.format(type, name); } else NapiLog.logError(` @@ -65,7 +65,7 @@ function generateVariable(name, type, variable, className) { void *instPtr = pxt->UnWarpInstance(); %s *p = static_cast<%s *>(instPtr); napi_value result = nullptr; - `.format(name, className, className) + cToJs("p->" + name, type, "result") + ` + `.format(name, className, className) + cToJs('p->' + name, type, 'result') + ` delete pxt; return result; } @@ -74,113 +74,113 @@ function generateVariable(name, type, variable, className) { std::shared_ptr pxt = std::make_shared(env, info); void *instPtr = pxt->UnWarpInstance(); %s *p = static_cast<%s *>(instPtr); - `.format(name, className, className) + jsToC("p->" + name, "pxt->GetArgv(XNapiTool::ZERO)", type) + ` + `.format(name, className, className) + jsToC('p->' + name, 'pxt->GetArgv(XNapiTool::ZERO)', type) + ` return nullptr; } -` +`; } function generateClass(name, data, inNamespace, functiontType) { - let resultConnect = connectResult(data, inNamespace, name) - let middleFunc = resultConnect[0] - let implH = functiontType == "static" ? "\n" + "static " + - resultConnect[1].substring(1, resultConnect[1].length) : resultConnect[1] - let implCpp = resultConnect[2] - let middleInit = resultConnect[3] - let middleH = resultConnect[4] - let selfNs = "" + let resultConnect = connectResult(data, inNamespace, name); + let middleFunc = resultConnect[0]; + let implH = functiontType == 'static' ? '\n' + 'static ' + + resultConnect[1].substring(1, resultConnect[1].length) : resultConnect[1]; + let implCpp = resultConnect[2]; + let middleInit = resultConnect[3]; + let middleH = resultConnect[4]; + let selfNs = ''; if (inNamespace.length > 0) { - let nsl = inNamespace.split("::") - nsl.pop() + let nsl = inNamespace.split('::'); + nsl.pop(); if (nsl.length >= 2) { - selfNs = ", " + nsl[nsl.length - 1] + selfNs = ', ' + nsl[nsl.length - 1]; } } - let toolNamespace = getToolNamespace(inNamespace) + let toolNamespace = getToolNamespace(inNamespace); middleInit += `\n pxt->DefineClass("%s", %s%s%s_middle::constructor, valueList, funcList%s);\n}\n` - .format(name, inNamespace, toolNamespace, name, selfNs) + .format(name, inNamespace, toolNamespace, name, selfNs); let result = { implH: ` class %s { public:%s };`.format(name, implH), implCpp: implCpp, - middleBody: middleBodyTmplete.replaceAll("[className]", name).replaceAll("[static_funcs]", middleFunc), + middleBody: middleBodyTmplete.replaceAll('[className]', name).replaceAll('[static_funcs]', middleFunc), middleInit: middleInit, declarationH: ` class %s;\r`.format(name), middleH: middleH - } - return result + }; + return result; } function connectResult(data, inNamespace, name) { - let implH = "" - let implCpp = "" - let middleFunc = "" - let middleInit = "" - let middleH = "" + let implH = ''; + let implCpp = ''; + let middleFunc = ''; + let middleInit = ''; + let middleH = ''; let variable = { - hDefine: "", - middleValue: "", - } - let toolNamespace = getToolNamespace(inNamespace) - middleInit = `{\n std::map> valueList;` + hDefine: '', + middleValue: '', + }; + let toolNamespace = getToolNamespace(inNamespace); + middleInit = `{\n std::map> valueList;`; for (let i in data.value) { - let v = data.value[i] - generateVariable(v.name, v.type, variable, name) + let v = data.value[i]; + generateVariable(v.name, v.type, variable, name); middleInit += ` valueList["%s"]["getvalue"] = %s%s%s_middle::getvalue_%s; valueList["%s"]["setvalue"] = %s%s%s_middle::setvalue_%s;` - .format(v.name, inNamespace, toolNamespace, name, v.name, v.name, inNamespace, toolNamespace, name, v.name) + .format(v.name, inNamespace, toolNamespace, name, v.name, v.name, inNamespace, toolNamespace, name, v.name); } - implH += variable.hDefine - middleFunc += variable.middleValue - middleInit += `\n std::map funcList;` + implH += variable.hDefine; + middleFunc += variable.middleValue; + middleInit += `\n std::map funcList;`; for (let i in data.function) { - let func = data.function[i] + let func = data.function[i]; let tmp; switch (func.type) { case FuncType.DIRECT: - tmp = generateFunctionDirect(func, '', name) + tmp = generateFunctionDirect(func, '', name); break; case FuncType.SYNC: - tmp = generateFunctionSync(func, '', name) - break + tmp = generateFunctionSync(func, '', name); + break; case FuncType.ASYNC: case FuncType.PROMISE: - tmp = generateFunctionAsync(func, '', name) - break + tmp = generateFunctionAsync(func, '', name); + break; default: - return + return; } - middleFunc += tmp[0] - implH += tmp[1] - implCpp += tmp[2] - middleH += tmp[3] + middleFunc += tmp[0]; + implH += tmp[1]; + implCpp += tmp[2]; + middleH += tmp[3]; middleInit += `\n funcList["%s"] = %s%s%s_middle::%s_middle;` - .format(func.name, inNamespace, toolNamespace, name, func.name) + .format(func.name, inNamespace, toolNamespace, name, func.name); } - return [middleFunc, implH, implCpp, middleInit, middleH] + return [middleFunc, implH, implCpp, middleInit, middleH]; } function getToolNamespace(inNamespace) { - let index = inNamespace.lastIndexOf("::"); + let index = inNamespace.lastIndexOf('::'); let toolNamespace; if (index > 0) { - let bodyTmp = inNamespace.substring(0, index) - let index2 = bodyTmp.lastIndexOf('::') + let bodyTmp = inNamespace.substring(0, index); + let index2 = bodyTmp.lastIndexOf('::'); if (index2 > 0 && index2 < index) { - toolNamespace = inNamespace.substring(index2 + 2, index) + '_interface::' + toolNamespace = inNamespace.substring(index2 + 2, index) + '_interface::'; } else { - toolNamespace = bodyTmp + "_interface::"; + toolNamespace = bodyTmp + '_interface::'; } } else { - toolNamespace = inNamespace + "_interface::"; + toolNamespace = inNamespace + '_interface::'; } return toolNamespace; } module.exports = { generateClass -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From 6e709c3e56551c6355c62a9c3ec547772cfb7095 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:27:20 +0800 Subject: [PATCH 22/26] =?UTF-8?q?"modifile=20examples/napitutorials/entry/?= =?UTF-8?q?src/main/cpp/ncpp/ffmpegcase/render/plugin=5Frender.cpp=20?= =?UTF-8?q?=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE=E9=A2=98=20?= =?UTF-8?q?=E5=92=8Ccpp=E5=A4=B4=E6=96=87=E4=BB=B6=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- .../src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp b/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp index a0ec39aa..133e0f7a 100644 --- a/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp +++ b/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp @@ -24,12 +24,11 @@ #include "../manager/plugin_manager.h" #include "libavutil/pixdesc.h" #include "plugin_render.h" +#include "libavformat/avformat.h" +#include "libavcodec/avcodec.h" +#include "libavutil/timestamp.h" extern "C" { - #include "libavformat/avformat.h" - #include "libavcodec/avcodec.h" - #include "libavutil/timestamp.h" - #include "libavutil/pixdesc.h" // 自定义 avio_read_packet 函数 int custom_avio_read_packet(void *opaque, uint8_t *buf, int bufSize) -- Gitee From f26c85b84c16d6d42a7b171589d058edbc7db715 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:27:22 +0800 Subject: [PATCH 23/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/gener?= =?UTF-8?q?ate/enum.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98=20=E5=92=8Ccpp=E5=A4=B4=E6=96=87=E4=BB=B6=E9=97=AE?= =?UTF-8?q?=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- src/cli/dts2cpp/src/gen/generate/enum.js | 48 ++++++++++++------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/generate/enum.js b/src/cli/dts2cpp/src/gen/generate/enum.js index 8dad9861..3b29cdd2 100644 --- a/src/cli/dts2cpp/src/gen/generate/enum.js +++ b/src/cli/dts2cpp/src/gen/generate/enum.js @@ -12,51 +12,51 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); -const { EnumValueType, getLogErrInfo } = require("../tools/common"); -const { NapiLog } = require("../tools/NapiLog"); +const re = require('../tools/re'); +const { EnumValueType, getLogErrInfo } = require('../tools/common'); +const { NapiLog } = require('../tools/NapiLog'); function generateEnum(name, data, inNamespace, nameSpaceName, toolNamespace) { - let implH = "" - let implCpp = "" - let midInitEnum = "" - let midInitEnumDefine = "" + let implH = ''; + let implCpp = ''; + let midInitEnum = ''; + let midInitEnumDefine = ''; if (data.enumValueType == EnumValueType.ENUM_VALUE_TYPE_STRING) { - implH = `\nclass %s {\npublic:\n`.format(name, implH) + implH = `\nclass %s {\npublic:\n`.format(name, implH); } else if (data.enumValueType == EnumValueType.ENUM_VALUE_TYPE_NUMBER){ - implH = `\nenum class %s {\n`.format(name, implH) + implH = `\nenum class %s {\n`.format(name, implH); } else { NapiLog.logError(`The enum type[%s] is not support.`.format(data.enumValueType), getLogErrInfo()); - return {implH: "", implCpp: ""} + return {implH: '', implCpp: ''}; } for (let i in data.element) { - let v = data.element[i] - if(midInitEnumDefine == "") { - midInitEnumDefine += 'std::map enumMap%s;\n'.format(name) + let v = data.element[i]; + if(midInitEnumDefine == '') { + midInitEnumDefine += 'std::map enumMap%s;\n'.format(name); } if (data.enumValueType == EnumValueType.ENUM_VALUE_TYPE_STRING) { - implH += ` static const std::string %s;\n`.format(v.name) - implCpp += `\nconst std::string %s::%s = "%s";\n`.format(name, v.name, v.value) - midInitEnum += ' %s%s::%senumMap%s["%s"] = "%s";\n'.format(inNamespace, nameSpaceName, toolNamespace, name, v.name, v.value) + implH += ` static const std::string %s;\n`.format(v.name); + implCpp += `\nconst std::string %s::%s = "%s";\n`.format(name, v.name, v.value); + midInitEnum += ' %s%s::%senumMap%s["%s"] = "%s";\n'.format(inNamespace, nameSpaceName, toolNamespace, name, v.name, v.value); } else { if (v.value == '') { - v.value = 0 + v.value = 0; } - implH += ` %s = %s,\n`.format(v.name, v.value) - midInitEnum += ' %s%s::%senumMap%s["%s"] = %s;\n'.format(inNamespace, nameSpaceName, toolNamespace, name, v.name, v.value) + implH += ` %s = %s,\n`.format(v.name, v.value); + midInitEnum += ' %s%s::%senumMap%s["%s"] = %s;\n'.format(inNamespace, nameSpaceName, toolNamespace, name, v.name, v.value); } } - midInitEnum += ' pxt->CreateEnumObject("%s", %s%s::%senumMap%s);\n'.format(name, inNamespace, nameSpaceName, toolNamespace, name) - implH += `};\n` + midInitEnum += ' pxt->CreateEnumObject("%s", %s%s::%senumMap%s);\n'.format(name, inNamespace, nameSpaceName, toolNamespace, name); + implH += `};\n`; let result = { implH: implH, implCpp: implCpp, midInitEnum: midInitEnum, midInitEnumDefine: midInitEnumDefine - } - return result + }; + return result; } module.exports = { generateEnum -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From 955d38f6fe1efba282c34577a24c4b578e50e5d0 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 10:27:39 +0800 Subject: [PATCH 24/26] =?UTF-8?q?"modifile=20src/cli/dts2cpp/src/gen/gener?= =?UTF-8?q?ate/function=5Fasync.js=20=E4=BF=AE=E6=94=B9js=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E9=97=AE=E9=A2=98=20=E5=92=8Ccpp=E5=A4=B4=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E9=97=AE=E9=A2=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huruitao --- .../src/gen/generate/function_async.js | 160 +++++++++--------- 1 file changed, 80 insertions(+), 80 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/generate/function_async.js b/src/cli/dts2cpp/src/gen/generate/function_async.js index 4cbdfc18..05cb4a29 100644 --- a/src/cli/dts2cpp/src/gen/generate/function_async.js +++ b/src/cli/dts2cpp/src/gen/generate/function_async.js @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { replaceAll, getPrefix, getConstNum } = require("../tools/tool"); -const { paramGenerate } = require("./param_generate"); -const { returnGenerate } = require("./return_generate"); -const { jsonCfgList, InterfaceList }= require("../tools/common"); +const { replaceAll, getPrefix, getConstNum } = require('../tools/tool'); +const { paramGenerate } = require('./param_generate'); +const { returnGenerate } = require('./return_generate'); +const { jsonCfgList, InterfaceList }= require('../tools/common'); /** * 结果异步返回Async|Promise @@ -28,7 +28,7 @@ struct [funcName]_value_struct {[valueIn] [static_define]void [funcName]_execute(XNapiTool *pxt, DataPtr data); [static_define]void [funcName]_complete(XNapiTool *pxt, DataPtr data); [static_define]napi_value [funcName]_middle(napi_env env, napi_callback_info info); -` +`; let funcAsyncTemplete = ` void [middleClassName][funcName]_execute(XNapiTool *pxt, DataPtr data) @@ -69,7 +69,7 @@ napi_value [middleClassName][funcName]_middle(napi_env env, napi_callback_info i struct [funcName]_value_struct *vio = new [funcName]_value_struct(); [valueCheckout][optionalCallbackInit][start_async] return result; -}` +}`; let cppTemplate = ` bool %s%s(%s) @@ -77,7 +77,7 @@ bool %s%s(%s) %s[replace_valueOut] return true; } -` +`; let cppCbResultTemplate = ` [replace_outDefine] @@ -86,93 +86,93 @@ void %s%sSetCbValue(%s) %s return; } -` +`; function removeEndlineEnter(value) { for (var i = value.length; i > 0; i--) { - let len = value.length - if (value.substring(len - 1, len) == "\n" || value.substring(len - 1, len) == ' ') { - value = value.substring(0, len - 1) + let len = value.length; + if (value.substring(len - 1, len) == '\n' || value.substring(len - 1, len) == ' ') { + value = value.substring(0, len - 1); } else { - value = ' ' + value + "\n" - break + value = ' ' + value + '\n'; + break; } } - return value + return value; } function getOptionalCallbackInit(param) { if (!param.callback.optional) { - return "" + return ''; } - let cType = param.valueOut.substr(0, param.valueOut.indexOf("*")) - return "vio->out = new %s;".format(cType) + let cType = param.valueOut.substr(0, param.valueOut.indexOf('*')); + return 'vio->out = new %s;'.format(cType); } function replaceBasicInfo(middleFunc, middleH, className) { if (className == null) { - middleH = middleH.replaceAll("[static_define]", "") - middleFunc = middleFunc.replaceAll("[unwarp_instance]", "") - middleFunc = middleFunc.replaceAll("[checkout_async_instance]", "") - middleFunc = middleFunc.replaceAll("[middleClassName]", "") + middleH = middleH.replaceAll('[static_define]', ''); + middleFunc = middleFunc.replaceAll('[unwarp_instance]', ''); + middleFunc = middleFunc.replaceAll('[checkout_async_instance]', ''); + middleFunc = middleFunc.replaceAll('[middleClassName]', ''); } else { - middleH = middleH.replaceAll("[static_define]", "static ") - middleFunc = middleFunc.replaceAll("[unwarp_instance]", - `pxt->SetAsyncInstance(pxt->UnWarpInstance());`) - middleFunc = middleFunc.replaceAll("[checkout_async_instance]", - "%s *pInstance = (%s *)pxt->GetAsyncInstance();".format(className, className)) - middleFunc = middleFunc.replaceAll("[middleClassName]", className + "_middle" + "::") + middleH = middleH.replaceAll('[static_define]', 'static '); + middleFunc = middleFunc.replaceAll('[unwarp_instance]', + `pxt->SetAsyncInstance(pxt->UnWarpInstance());`); + middleFunc = middleFunc.replaceAll('[checkout_async_instance]', + '%s *pInstance = (%s *)pxt->GetAsyncInstance();'.format(className, className)); + middleFunc = middleFunc.replaceAll('[middleClassName]', className + '_middle' + '::'); } - return [middleFunc, middleH] + return [middleFunc, middleH]; } function generateFunctionAsync(func, data, className, implHCbVariable) { - let middleFunc = replaceAll(funcAsyncTemplete, "[funcName]", func.name) - let middleH = "" - if (func.name != "constructor") { - middleH = replaceAll(funcAsyncMiddleHTemplete, "[funcName]", func.name) + let middleFunc = replaceAll(funcAsyncTemplete, '[funcName]', func.name); + let middleH = ''; + if (func.name != 'constructor') { + middleH = replaceAll(funcAsyncMiddleHTemplete, '[funcName]', func.name); } - let basicInfoRes = replaceBasicInfo(middleFunc, middleH, className) - middleFunc = basicInfoRes[0] - middleH = basicInfoRes[1] + let basicInfoRes = replaceBasicInfo(middleFunc, middleH, className); + middleFunc = basicInfoRes[0]; + middleH = basicInfoRes[1]; // 定义输入,定义输出,解析,填充到函数内,输出参数打包,impl参数定义,可选参数内存释放 - let param = { valueIn: "", valueOut: "", valueCheckout: "", valueFill: "", - valuePackage: "", valueDefine: "", optionalParamDestory: "" } + let param = { valueIn: '', valueOut: '', valueCheckout: '', valueFill: '', + valuePackage: '', valueDefine: '', optionalParamDestory: '' }; for (let i in func.value) { - paramGenerate(i, func.value[i], param, data) + paramGenerate(i, func.value[i], param, data); } - returnGenerate(param.callback, param, data) + returnGenerate(param.callback, param, data); middleH = replaceValueOut(middleH, param); middleFunc = getMiddleFunc(param, middleFunc); - middleFunc = replaceAll(middleFunc, "[start_async]", ` + middleFunc = replaceAll(middleFunc, '[start_async]', ` napi_value result = pxt->StartAsync(%s_execute, reinterpret_cast(vio), %s_complete, pxt->GetArgc() == %s? pxt->GetArgv(%d) : nullptr);` .format(func.name, func.name, getConstNum(parseInt(param.callback.offset) + 1), - getConstNum(param.callback.offset))) // 注册异步调用 - let callFunc = "%s%s(%s);".format(className == null ? "" : "pInstance->", func.name, param.valueFill) - middleFunc = replaceAll(middleFunc, "[callFunc]", callFunc) // 执行 - middleFunc = replaceAll(middleFunc, "[valuePackage]", param.valuePackage) // 输出参数打包 - middleFunc = replaceAll(middleFunc, "[optionalParamDestory]", param.optionalParamDestory) // 可选参数内存释放 - - let prefixArr = getPrefix(data, func) - let implH = "" - let implCpp = "" + getConstNum(param.callback.offset))); // 注册异步调用 + let callFunc = '%s%s(%s);'.format(className == null ? '' : 'pInstance->', func.name, param.valueFill); + middleFunc = replaceAll(middleFunc, '[callFunc]', callFunc); // 执行 + middleFunc = replaceAll(middleFunc, '[valuePackage]', param.valuePackage); // 输出参数打包 + middleFunc = replaceAll(middleFunc, '[optionalParamDestory]', param.optionalParamDestory); // 可选参数内存释放 + + let prefixArr = getPrefix(data, func); + let implH = ''; + let implCpp = ''; if (!func.isParentMember) { // 只有类/接口自己的成员方法需要在.h.cpp中生成,父类/父接口不需要 - implH = "\n%s%s%sbool %s(%s)%s;".format( - prefixArr[0], prefixArr[1], prefixArr[2], func.name, param.valueDefine, prefixArr[3]) - let callStatement = jsonCfgList.getValue(className == null? "": className, func.name); - implCpp = cppTemplate.format(className == null ? "" : className + "::", func.name, param.valueDefine, - callStatement == null? "": callStatement) - - let outResult = generateCbInterfaceOutFunc(param, className, prefixArr, implHCbVariable, implCpp, implH) - implCpp = outResult[0] - implH = outResult[1] + implH = '\n%s%s%sbool %s(%s)%s;'.format( + prefixArr[0], prefixArr[1], prefixArr[2], func.name, param.valueDefine, prefixArr[3]); + let callStatement = jsonCfgList.getValue(className == null? '': className, func.name); + implCpp = cppTemplate.format(className == null ? '' : className + '::', func.name, param.valueDefine, + callStatement == null? '': callStatement); + + let outResult = generateCbInterfaceOutFunc(param, className, prefixArr, implHCbVariable, implCpp, implH); + implCpp = outResult[0]; + implH = outResult[1]; } - return [middleFunc, implH, implCpp, middleH] + return [middleFunc, implH, implCpp, middleH]; } function getMiddleFunc(param, middleFunc) { @@ -192,8 +192,8 @@ function getMiddleFunc(param, middleFunc) { } function generateCbInterfaceOutFunc(param, className, prefixArr, implHCbVariable, implCpp, implH) { - let cbInterfaceRes = ""; - let outInterfaceDefine = param.valueDefine.substring(param.valueDefine.lastIndexOf(",") + 1, + let cbInterfaceRes = ''; + let outInterfaceDefine = param.valueDefine.substring(param.valueDefine.lastIndexOf(',') + 1, param.valueDefine.length); outInterfaceDefine = replaceAll(outInterfaceDefine, ' ', ''); let index = outInterfaceDefine.indexOf('&'); @@ -203,51 +203,51 @@ function generateCbInterfaceOutFunc(param, className, prefixArr, implHCbVariable let useParams = ''; let interBody = InterfaceList.getValue(outInterfaceName); for (let i = 0; i < interBody.length; i++) { - let realType = interBody[i].type == "string" ? "std::string" : interBody[i].type; - realType = interBody[i].type == "boolean" ? "bool" : realType; - defineParams += "%s %s, ".format(realType, interBody[i].name); - useParams += "%s%sOutRes.%s = %s;\n".format(className == null ? "" : className + "::", + let realType = interBody[i].type == 'string' ? 'std::string' : interBody[i].type; + realType = interBody[i].type == 'boolean' ? 'bool' : realType; + defineParams += '%s %s, '.format(realType, interBody[i].name); + useParams += '%s%sOutRes.%s = %s;\n'.format(className == null ? '' : className + '::', outInterfaceName.toLocaleLowerCase(), interBody[i].name, interBody[i].name); } defineParams = defineParams.substring(0, defineParams.length - 2); - let cbOutDefine = "\n%s %s%sOutRes = {};".format(outInterfaceName, className == null ? "" : className + "::", - outInterfaceName.toLocaleLowerCase()) - cbInterfaceRes = cppCbResultTemplate.format(className == null ? "" : className + "::", outInterfaceName.toLocaleLowerCase(), + let cbOutDefine = '\n%s %s%sOutRes = {};'.format(outInterfaceName, className == null ? '' : className + '::', + outInterfaceName.toLocaleLowerCase()); + cbInterfaceRes = cppCbResultTemplate.format(className == null ? '' : className + '::', outInterfaceName.toLocaleLowerCase(), defineParams, useParams); if (className != null) { - cbInterfaceRes = replaceAll(cbInterfaceRes, '[replace_outDefine]', cbOutDefine) + cbInterfaceRes = replaceAll(cbInterfaceRes, '[replace_outDefine]', cbOutDefine); } else { - cbInterfaceRes = replaceAll(cbInterfaceRes, '[replace_outDefine]', '') + cbInterfaceRes = replaceAll(cbInterfaceRes, '[replace_outDefine]', ''); } // 多次使用interface(非匿名)作为Promise回调只需生成一次cbResult接口 - let outResDefine = "\n%s%s%sstatic %s %sOutRes;".format( + let outResDefine = '\n%s%s%sstatic %s %sOutRes;'.format( prefixArr[0], prefixArr[1], prefixArr[2], outInterfaceName, outInterfaceName.toLocaleLowerCase()); - let replaceOut = "\n out = %s%sOutRes;".format(className == null ? "" : className + "::", + let replaceOut = '\n out = %s%sOutRes;'.format(className == null ? '' : className + '::', outInterfaceName.toLocaleLowerCase()); - implCpp = replaceAll(implCpp, "[replace_valueOut]", replaceOut); + implCpp = replaceAll(implCpp, '[replace_valueOut]', replaceOut); if (implHCbVariable.indexOf(outResDefine) < 0) { implH += outResDefine; - implH += "\n%s%s%svoid %sSetCbValue(%s);".format( + implH += '\n%s%s%svoid %sSetCbValue(%s);'.format( prefixArr[0], prefixArr[1], prefixArr[2], outInterfaceName.toLocaleLowerCase(), defineParams); implCpp += cbInterfaceRes; } } else { - implCpp = replaceAll(implCpp, "[replace_valueOut]", ''); + implCpp = replaceAll(implCpp, '[replace_valueOut]', ''); } return [implCpp, implH]; } function replaceValueOut(middleH, param) { - middleH = replaceAll(middleH, "[valueIn]", param.valueIn); // # 输入参数定义 - if (param.valueOut == "") { - middleH = replaceAll(middleH, "[valueOut]", param.valueOut); // # 输出参数定义 + middleH = replaceAll(middleH, '[valueIn]', param.valueIn); // # 输入参数定义 + if (param.valueOut == '') { + middleH = replaceAll(middleH, '[valueOut]', param.valueOut); // # 输出参数定义 } else { - middleH = replaceAll(middleH, "[valueOut]", "\n " + param.valueOut); // # 输出参数定义 + middleH = replaceAll(middleH, '[valueOut]', '\n ' + param.valueOut); // # 输出参数定义 } return middleH; } module.exports = { generateFunctionAsync -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From 47dfac916960864d6683da181abc97dfb9b2f7b7 Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 15:11:38 +0800 Subject: [PATCH 25/26] codecheck Signed-off-by: huruitao --- autocommit.py | 77 +++++++++++++++++++ .../ncpp/ffmpegcase/render/plugin_render.cpp | 1 - src/cli/cmake2gn/src/src/analyze_cmake.js | 2 +- 3 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 autocommit.py mode change 100644 => 100755 src/cli/cmake2gn/src/src/analyze_cmake.js diff --git a/autocommit.py b/autocommit.py new file mode 100644 index 00000000..b45df2d3 --- /dev/null +++ b/autocommit.py @@ -0,0 +1,77 @@ +#!/usr/bin/python3 +import os +import sys +import json +import time +import datetime +import subprocess +import shutil +import random + +resultLog = [] +summaryReport = [] +countReport = [] +memdict = {} +deltaReport = {} + +def auCommit(modifile, cmsg): + cmdlist = ["git", "add", modifile] + top_info = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) + out, err = top_info.communicate() + outstr = str(out) + print("outstr:", outstr) + rint = random.randint(1, 100) + print("rint:", rint) + time.sleep(rint) + commitMsg = "\"modifile " + modifile + " " + cmsg + "\"" + cmdlist = ["git", "commit", "-sm", commitMsg] + top_info = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) + out, err = top_info.communicate() + outstr = str(out) + print("outstr:", outstr) + +def main(cmsg): + cmdlist = ["git", "status"] + top_info = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) + out, err = top_info.communicate() + outstr = str(out) + print("outstr:", outstr) + outlist = outstr.split("\\n") + modifiedFiles = [] + deletedFiles = [] + addFiles = [] + isUntracked = False + for item in outlist: + if "modified" in item: + itemlist = item.split(":") + filename = itemlist[1] + filename = filename.strip() + modifiedFiles.append(filename) + if "deleted" in item: + itemlist = item.split(":") + filename = itemlist[1] + filename = filename.strip() + deletedFiles.append(filename) + if isUntracked and ("\\t" in item) and "autocommit.py" not in item: + filename = item.strip() + filename = filename.replace("\\t", "") + addFiles.append(filename) + if "Untracked" in item: + isUntracked = True + + + print("modifiedFiles------:", modifiedFiles) + print("addFiles------:", addFiles) + print("deleted------:", deletedFiles) + + # 增加 modify文件 + for modifile in modifiedFiles: + auCommit(modifile, cmsg) + for modifile in addFiles: + auCommit(modifile, cmsg) + for modifile in deletedFiles: + auCommit(modifile, cmsg) + +if __name__ == '__main__': + cmsg = sys.argv[1] + main(cmsg) \ No newline at end of file diff --git a/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp b/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp index 133e0f7a..a9472c92 100644 --- a/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp +++ b/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp @@ -29,7 +29,6 @@ #include "libavutil/timestamp.h" extern "C" { - // 自定义 avio_read_packet 函数 int custom_avio_read_packet(void *opaque, uint8_t *buf, int bufSize) { diff --git a/src/cli/cmake2gn/src/src/analyze_cmake.js b/src/cli/cmake2gn/src/src/analyze_cmake.js old mode 100644 new mode 100755 index cf07f876..933b98c5 --- a/src/cli/cmake2gn/src/src/analyze_cmake.js +++ b/src/cli/cmake2gn/src/src/analyze_cmake.js @@ -84,4 +84,4 @@ class AnalyzeCMake { module.exports = { AnalyzeCMake -} \ No newline at end of file +}; \ No newline at end of file -- Gitee From a8367daf81f426081bf63759d5617d4b710824cd Mon Sep 17 00:00:00 2001 From: huruitao Date: Wed, 10 Jul 2024 15:13:11 +0800 Subject: [PATCH 26/26] codecheck Signed-off-by: huruitao --- autocommit.py | 77 --------------------------------------------------- 1 file changed, 77 deletions(-) delete mode 100644 autocommit.py diff --git a/autocommit.py b/autocommit.py deleted file mode 100644 index b45df2d3..00000000 --- a/autocommit.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python3 -import os -import sys -import json -import time -import datetime -import subprocess -import shutil -import random - -resultLog = [] -summaryReport = [] -countReport = [] -memdict = {} -deltaReport = {} - -def auCommit(modifile, cmsg): - cmdlist = ["git", "add", modifile] - top_info = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) - out, err = top_info.communicate() - outstr = str(out) - print("outstr:", outstr) - rint = random.randint(1, 100) - print("rint:", rint) - time.sleep(rint) - commitMsg = "\"modifile " + modifile + " " + cmsg + "\"" - cmdlist = ["git", "commit", "-sm", commitMsg] - top_info = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) - out, err = top_info.communicate() - outstr = str(out) - print("outstr:", outstr) - -def main(cmsg): - cmdlist = ["git", "status"] - top_info = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) - out, err = top_info.communicate() - outstr = str(out) - print("outstr:", outstr) - outlist = outstr.split("\\n") - modifiedFiles = [] - deletedFiles = [] - addFiles = [] - isUntracked = False - for item in outlist: - if "modified" in item: - itemlist = item.split(":") - filename = itemlist[1] - filename = filename.strip() - modifiedFiles.append(filename) - if "deleted" in item: - itemlist = item.split(":") - filename = itemlist[1] - filename = filename.strip() - deletedFiles.append(filename) - if isUntracked and ("\\t" in item) and "autocommit.py" not in item: - filename = item.strip() - filename = filename.replace("\\t", "") - addFiles.append(filename) - if "Untracked" in item: - isUntracked = True - - - print("modifiedFiles------:", modifiedFiles) - print("addFiles------:", addFiles) - print("deleted------:", deletedFiles) - - # 增加 modify文件 - for modifile in modifiedFiles: - auCommit(modifile, cmsg) - for modifile in addFiles: - auCommit(modifile, cmsg) - for modifile in deletedFiles: - auCommit(modifile, cmsg) - -if __name__ == '__main__': - cmsg = sys.argv[1] - main(cmsg) \ No newline at end of file -- Gitee