From ae2cfdd0314f31e9721cdc2f54e7819368a4019f Mon Sep 17 00:00:00 2001 From: wangshi Date: Tue, 11 Feb 2025 16:15:56 +0800 Subject: [PATCH 1/2] refact log Signed-off-by: wangshi --- src/vscode_plugin/src/common/conf.ts | 32 +++++- src/vscode_plugin/src/common/file.ts | 44 +++++++- src/vscode_plugin/src/common/log.ts | 102 ++++++++++++++++++ src/vscode_plugin/src/common/tool.ts | 17 ++- src/vscode_plugin/src/common/widget.ts | 9 +- .../src/controller/crosscompilectrl.ts | 6 +- .../src/controller/dts2cppctrl.ts | 4 +- .../src/controller/h2dtscppctrl.ts | 4 +- src/vscode_plugin/src/controller/h2dtsctrl.ts | 4 +- src/vscode_plugin/src/controller/h2hdfctrl.ts | 4 +- src/vscode_plugin/src/controller/h2sactrl.ts | 4 +- .../src/controller/welcomectrl.ts | 4 +- src/vscode_plugin/src/extension.ts | 29 ++--- src/vscode_plugin/src/gen/gendts.ts | 5 +- src/vscode_plugin/src/gen/gendtscpp.ts | 6 +- src/vscode_plugin/src/gen/genhdf.ts | 6 +- src/vscode_plugin/src/gen/gensa.ts | 6 +- src/vscode_plugin/src/gen/gentest.ts | 6 +- .../src/model/crosscompilemod.ts | 8 +- src/vscode_plugin/src/model/dts2cppmod.ts | 12 +-- src/vscode_plugin/src/model/h2dtscppmod.ts | 10 +- src/vscode_plugin/src/model/h2dtsmod.ts | 8 +- src/vscode_plugin/src/model/h2hdfmod.ts | 10 +- src/vscode_plugin/src/model/h2samod.ts | 10 +- src/vscode_plugin/src/model/imodel.ts | 4 +- src/vscode_plugin/src/model/welcomemod.ts | 8 +- src/vscode_plugin/src/ohcrosscompile.ts | 7 +- src/vscode_plugin/src/parse/parsec.ts | 42 ++++---- src/vscode_plugin/src/parse/parsets.ts | 43 ++++---- src/vscode_plugin/src/test/runTest.ts | 3 +- .../src/test/suite/common/tool.test.ts | 4 +- src/vscode_plugin/src/test/suite/index.ts | 5 +- src/vscode_plugin/src/view/welcomeview.ts | 4 +- 33 files changed, 328 insertions(+), 142 deletions(-) create mode 100644 src/vscode_plugin/src/common/log.ts diff --git a/src/vscode_plugin/src/common/conf.ts b/src/vscode_plugin/src/common/conf.ts index cd111224..c38db8b4 100644 --- a/src/vscode_plugin/src/common/conf.ts +++ b/src/vscode_plugin/src/common/conf.ts @@ -22,7 +22,31 @@ export function getOutputPath(): string { } export function getReportConf(): string { - const config = vscode.workspace.getConfiguration('testReport'); - const outSetting = config.get("canOutput"); - return outSetting; - } + const config = vscode.workspace.getConfiguration('testReport'); + const outSetting = config.get("canOutput"); + return outSetting; +} + +export enum GEN_TYPE { + GEN_REPLACE = 1, + GEN_APPEND, + GEN_NEW +} + +export function getGenerateConf(): number { + const config = vscode.workspace.getConfiguration('genProject'); + const outSetting = config.get("policy"); + return outSetting; +} + +export function getLogPath(): string { + const config = vscode.workspace.getConfiguration('logger'); + const outSetting = config.get("filePath"); + return outSetting; +} + +export function getLogName(): string { + const config = vscode.workspace.getConfiguration('logger'); + const outSetting = config.get("fileName"); + return outSetting; +} \ No newline at end of file diff --git a/src/vscode_plugin/src/common/file.ts b/src/vscode_plugin/src/common/file.ts index 01d6ff78..0bb974e2 100644 --- a/src/vscode_plugin/src/common/file.ts +++ b/src/vscode_plugin/src/common/file.ts @@ -14,9 +14,45 @@ */ const vscode = require("vscode"); +import * as fs from 'fs'; +import { getGenerateConf, GEN_TYPE } from './conf'; -export function getOutputPath(): string { - const config = vscode.workspace.getConfiguration('napiExtension'); - const outSetting = config.get("outSetting"); - return outSetting; +export function saveFileSync(filePath: string, fileContent: string) { + let genType = getGenerateConf(); + if (!fs.existsSync(filePath)) { + // TODO: if file exist, replace, append or new file + switch (genType) { + case GEN_TYPE.GEN_APPEND: + break; + case GEN_TYPE.GEN_REPLACE: + break; + case GEN_TYPE.GEN_NEW: + break; + default: + break; + } + fs.writeFileSync(filePath, fileContent); + } else { + fs.writeFileSync(filePath, fileContent); + } } + +export function mkdirSync(dirPath: string) { + let genType = getGenerateConf(); + if (!fs.existsSync(dirPath)) { + // TODO: if file exist, replace, append or new file + switch (genType) { + case GEN_TYPE.GEN_APPEND: + break; + case GEN_TYPE.GEN_REPLACE: + break; + case GEN_TYPE.GEN_NEW: + break; + default: + break; + } + fs.mkdirSync(dirPath, { recursive: true }); + } else { + fs.mkdirSync(dirPath, { recursive: true }); + } +} \ No newline at end of file diff --git a/src/vscode_plugin/src/common/log.ts b/src/vscode_plugin/src/common/log.ts new file mode 100644 index 00000000..e171ea87 --- /dev/null +++ b/src/vscode_plugin/src/common/log.ts @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +const vscode = require("vscode"); +import * as fs from 'fs'; +import * as path from 'path'; +import { getLogName, getLogPath } from './conf'; + +const DEBUG_MSG = '[debug]'; +const INFO_MSG = '[info]'; +const WARN_MSG = '[warn]'; +const ERROR_MSG = '[error]'; + +export class Logger { + private logFilePath: string; + private maxFileSize: number = 1024 * 1024; // 1MB + private static instance: Logger; + + constructor() { + let logDirectory: string = getLogPath(); + let fileName: string = getLogName(); + this.logFilePath = path.join(logDirectory, fileName); + this.initLogFile(); + } + + static getInstance(): Logger { + if (!Logger.instance) { + Logger.instance = new Logger(); + } + return Logger.instance; + } + + private initLogFile(): void { + if (!fs.existsSync(this.logFilePath)) { + fs.writeFileSync(this.logFilePath, ''); + } + } + + public debug(message: string) { + console.log(message); + this.log(DEBUG_MSG + message); + } + + public info(message: string) { + Logger.getInstance().info(message); + this.log(INFO_MSG + message); + } + + public error(message: string) { + Logger.getInstance().error(message); + this.log(ERROR_MSG + message); + } + + public warn(message: string) { + Logger.getInstance().warn(message); + this.log(WARN_MSG + message); + } + + public log(message: string): void { + const timestamp = new Date().toISOString(); + const logMessage = `${timestamp} -${message}\n`; + this.appendLog(logMessage); + } + + private appendLog(message: string): void { + // Check if the current log file exceeds the max size + const stats = fs.statSync(this.logFilePath); + if (stats.size + Buffer.byteLength(message) > this.maxFileSize) { + this.rotateLogFile(); + } + + // Append the log message to the file + fs.appendFileSync(this.logFilePath, message); + } + + private rotateLogFile(): void { + // Get the current file name and extension + const { name, ext } = path.parse(this.logFilePath); + // Generate a new file name with a timestamp + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + const newFileName = `${name}-${timestamp}${ext}`; + const newFilePath = path.join(path.dirname(this.logFilePath), newFileName); + + // Rename the current log file + fs.renameSync(this.logFilePath, newFilePath); + + // Create a new log file + fs.writeFileSync(this.logFilePath, ''); + } +} \ No newline at end of file diff --git a/src/vscode_plugin/src/common/tool.ts b/src/vscode_plugin/src/common/tool.ts index 9cba22a4..4eb69abc 100644 --- a/src/vscode_plugin/src/common/tool.ts +++ b/src/vscode_plugin/src/common/tool.ts @@ -13,8 +13,23 @@ * limitations under the License. */ +export function getCurrentTimeString(): string { + const now = new Date(); + // 使用 padStart 方法确保日期和月份部分是两位数 + const yearLastTwoDigits = now.getFullYear() % 100; // 获取年份的最后两位 + const month = (now.getMonth() + 1).toString().padStart(2, '0'); + const day = now.getDate().toString().padStart(2, '0'); + const hours = now.getHours().toString().padStart(2, '0'); + const minutes = now.getMinutes().toString().padStart(2, '0'); + const seconds = now.getSeconds().toString().padStart(2, '0'); + + // 拼接成完整的日期时间字符串,年份只显示最后两位 + const currentTimeString = `${yearLastTwoDigits}${month}${day}${hours}${minutes}${seconds}`; + return currentTimeString; +} + export function replaceAll(s: string, sfrom: string, sto: any) { - // console.log('[replaceall] s:'+s+' sfrom:'+sfrom+' sto:'+sto); + // Logger.getInstance().debug('[replaceall] s:'+s+' sfrom:'+sfrom+' sto:'+sto); if (s && sfrom && sto) { while (s.indexOf(sfrom) >= 0) { s = s.replace(sfrom, sto); diff --git a/src/vscode_plugin/src/common/widget.ts b/src/vscode_plugin/src/common/widget.ts index 9937aa42..700476eb 100644 --- a/src/vscode_plugin/src/common/widget.ts +++ b/src/vscode_plugin/src/common/widget.ts @@ -22,6 +22,7 @@ import { EVENT_INFORMATION, EVENT_WARNING } from './eventtype'; +import { Logger } from './log'; import { Callback } from './define'; export function doAsyncQuickPick(valueList: string[], options?: vscode.QuickPickOptions, cb?: Callback) { @@ -71,19 +72,19 @@ export function doAsyncOpenDialog(options: vscode.OpenDialogOptions, cb: Callbac export function toastMsg(event: string, msg: string) { switch(event) { case EVENT_ERROR: - console.error(msg); + Logger.getInstance().error(msg); vscode.window.showErrorMessage(msg); break; case EVENT_INFORMATION: - console.info(msg); + Logger.getInstance().info(msg); vscode.window.showInformationMessage(msg); break; case EVENT_WARNING: - console.warn(msg); + Logger.getInstance().warn(msg); vscode.window.showWarningMessage(msg); break; default: - console.log(msg); + Logger.getInstance().debug(msg); vscode.window.showInformationMessage(msg); break; } diff --git a/src/vscode_plugin/src/controller/crosscompilectrl.ts b/src/vscode_plugin/src/controller/crosscompilectrl.ts index 5f87ce69..776b7fee 100644 --- a/src/vscode_plugin/src/controller/crosscompilectrl.ts +++ b/src/vscode_plugin/src/controller/crosscompilectrl.ts @@ -13,11 +13,11 @@ * limitations under the License. */ -import { Uri } from "vscode"; +import { InputBoxValidationSeverity, Uri } from "vscode"; import { CrossCompileMod } from "../model/crosscompilemod"; import { IModel } from "../model/imodel"; import { CrossCompileView } from "../view/crosscompileview"; - +import { Logger } from "../common/log"; import { IView } from "../view/iview"; import { IController } from "./icontroller"; import { EVENT_ERROR } from "../common/eventtype"; @@ -48,7 +48,7 @@ export class CrossCompileCtrl extends IController { this.model.doStart(); } catch(e) { let errmsg = "h2dts start error: " + JSON.stringify(e) - console.error(errmsg); + Logger.getInstance().error(errmsg); this.view.showMsg(EVENT_ERROR, errmsg); } } diff --git a/src/vscode_plugin/src/controller/dts2cppctrl.ts b/src/vscode_plugin/src/controller/dts2cppctrl.ts index 28850027..f1737726 100644 --- a/src/vscode_plugin/src/controller/dts2cppctrl.ts +++ b/src/vscode_plugin/src/controller/dts2cppctrl.ts @@ -17,7 +17,7 @@ import { Uri } from "vscode"; import { Dts2cppMod } from "../model/dts2cppmod"; import { IModel } from "../model/imodel"; import { Dts2cppView } from "../view/dts2cppview"; - +import { Logger } from "../common/log"; import { IView } from "../view/iview"; import { IController } from "./icontroller"; import { EVENT_ERROR } from "../common/eventtype"; @@ -48,7 +48,7 @@ export class Dts2cppCtrl extends IController { this.model.doStart(); } catch(e) { let errmsg = this.name + " start error: " + JSON.stringify(e) - console.error(errmsg); + Logger.getInstance().error(errmsg); this.view.showMsg(EVENT_ERROR, errmsg); } } diff --git a/src/vscode_plugin/src/controller/h2dtscppctrl.ts b/src/vscode_plugin/src/controller/h2dtscppctrl.ts index b05feeb2..68689a4f 100644 --- a/src/vscode_plugin/src/controller/h2dtscppctrl.ts +++ b/src/vscode_plugin/src/controller/h2dtscppctrl.ts @@ -15,7 +15,7 @@ import { Uri } from "vscode"; import { IModel } from "../model/imodel"; - +import { Logger } from "../common/log"; import { IView } from "../view/iview"; import { IController } from "./icontroller"; import { EVENT_ERROR } from "../common/eventtype"; @@ -48,7 +48,7 @@ export class H2dtscppCtrl extends IController { this.model.doStart(); } catch(e) { let errmsg = "h2dts start error: " + JSON.stringify(e) - console.error(errmsg); + Logger.getInstance().error(errmsg); this.view.showMsg(EVENT_ERROR, errmsg); } } diff --git a/src/vscode_plugin/src/controller/h2dtsctrl.ts b/src/vscode_plugin/src/controller/h2dtsctrl.ts index cf8ad3f1..cc4f6e92 100644 --- a/src/vscode_plugin/src/controller/h2dtsctrl.ts +++ b/src/vscode_plugin/src/controller/h2dtsctrl.ts @@ -17,7 +17,7 @@ import { Uri } from "vscode"; import { H2dtsMod } from "../model/h2dtsmod"; import { IModel } from "../model/imodel"; import { H2dtsView } from "../view/h2dtsview"; - +import { Logger } from "../common/log"; import { IView } from "../view/iview"; import { IController } from "./icontroller"; import { EVENT_ERROR } from "../common/eventtype"; @@ -48,7 +48,7 @@ export class H2dtsCtrl extends IController { this.model.doStart(); } catch(e) { let errmsg = "h2dts start error: " + JSON.stringify(e) - console.error(errmsg); + Logger.getInstance().error(errmsg); this.view.showMsg(EVENT_ERROR, errmsg); } } diff --git a/src/vscode_plugin/src/controller/h2hdfctrl.ts b/src/vscode_plugin/src/controller/h2hdfctrl.ts index cb218462..a03e4071 100644 --- a/src/vscode_plugin/src/controller/h2hdfctrl.ts +++ b/src/vscode_plugin/src/controller/h2hdfctrl.ts @@ -17,7 +17,7 @@ import { Uri } from "vscode"; import { H2hdfMod } from "../model/h2hdfmod"; import { IModel } from "../model/imodel"; import { H2hdfView } from "../view/h2hdfview"; - +import { Logger } from "../common/log"; import { IView } from "../view/iview"; import { IController } from "./icontroller"; import { EVENT_ERROR } from "../common/eventtype"; @@ -48,7 +48,7 @@ export class H2hdfCtrl extends IController { this.model.doStart(); } catch(e) { let errmsg = this.name + " start error: " + JSON.stringify(e) - console.error(errmsg); + Logger.getInstance().error(errmsg); this.view.showMsg(EVENT_ERROR, errmsg); } } diff --git a/src/vscode_plugin/src/controller/h2sactrl.ts b/src/vscode_plugin/src/controller/h2sactrl.ts index 3bca4468..6db29552 100644 --- a/src/vscode_plugin/src/controller/h2sactrl.ts +++ b/src/vscode_plugin/src/controller/h2sactrl.ts @@ -21,7 +21,7 @@ import { H2saView } from "../view/h2saview"; import { IView } from "../view/iview"; import { IController } from "./icontroller"; import { EVENT_ERROR } from "../common/eventtype"; - +import { Logger } from "../common/log"; export class H2saCtrl extends IController { name: string; view: IView; @@ -48,7 +48,7 @@ export class H2saCtrl extends IController { this.model.doStart(); } catch(e) { let errmsg = this.name + " start error: " + JSON.stringify(e) - console.error(errmsg); + Logger.getInstance().error(errmsg); this.view.showMsg(EVENT_ERROR, errmsg); } diff --git a/src/vscode_plugin/src/controller/welcomectrl.ts b/src/vscode_plugin/src/controller/welcomectrl.ts index 8d6a424b..627745a7 100644 --- a/src/vscode_plugin/src/controller/welcomectrl.ts +++ b/src/vscode_plugin/src/controller/welcomectrl.ts @@ -17,7 +17,7 @@ import { Uri } from "vscode"; import { WelcomeMod } from "../model/welcomemod"; import { IModel } from "../model/imodel"; import { WelcomeView } from "../view/welcomeview"; - +import { Logger } from "../common/log"; import { IView } from "../view/iview"; import { IController } from "./icontroller"; import { EVENT_ERROR } from "../common/eventtype"; @@ -48,7 +48,7 @@ export class WelcomeCtrl extends IController { this.model.doStart(); } catch(e) { let errmsg = this.name + " start error: " + JSON.stringify(e) - console.error(errmsg); + Logger.getInstance().error(errmsg); this.view.showMsg(EVENT_ERROR, errmsg); } } diff --git a/src/vscode_plugin/src/extension.ts b/src/vscode_plugin/src/extension.ts index 892be254..216f0b5b 100644 --- a/src/vscode_plugin/src/extension.ts +++ b/src/vscode_plugin/src/extension.ts @@ -34,6 +34,7 @@ import { H2hdfCtrl } from './controller/h2hdfctrl'; import { H2dtscppCtrl } from './controller/h2dtscppctrl'; import { Dts2cppCtrl } from './controller/dts2cppctrl'; import { WelcomeCtrl } from './controller/welcomectrl'; +import { Logger } from './common/log'; // ��ȡ���ػ��ַ��� const SELECTED_DIR = vscode.l10n.t('You selected a directory:'); @@ -88,9 +89,9 @@ const CMAKE_MAKE_LOST = vscode.l10n.t('Cannot detect CMakeLists.txt or Makefile! // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { - // Use the console to output diagnostic information (console.log) and errors (console.error) + // Use the console to output diagnostic information (Logger.getInstance().debug) and errors (Logger.getInstance().error) // This line of code will only be executed once when your extension is activated - console.log('Congratulations, your extension "helloworld-sample" is now active!'); + Logger.getInstance().debug('Congratulations, your extension "helloworld-sample" is now active!'); const ohcrosscompile = vscode.commands.registerCommand('extension.ohcrosscompile', async (uri) => { let compileTool: string; @@ -387,7 +388,7 @@ export function activate(context: vscode.ExtensionContext) { filePath = nativePath.concat("/" + file); //��ȡnativeѹ�������ļ�·�� } } - console.log(filePath); + Logger.getInstance().debug(filePath); const terminal = vscode.window.createTerminal({ name: OH_CROSS_COMPILE_TITLE }); terminal.show(); await extractZip(platform, terminal, filePath, nativePath); @@ -493,7 +494,7 @@ export function activate(context: vscode.ExtensionContext) { // }, async (progress) => { // // parse // let parseRes = await parseHeaderFile(uri.fsPath); - // console.log('parse header file res: ', parseRes); + // Logger.getInstance().debug('parse header file res: ', parseRes); // progress.report({ increment: 50, message: PARSE_COMPLETE }); // let rootInfo: GenInfo = { @@ -523,7 +524,7 @@ export function activate(context: vscode.ExtensionContext) { let dts2cppCtrl = new Dts2cppCtrl(uri); dts2cppCtrl.init(); // The code you place here will be executed every time your command is executed - // console.log('uri is : ' + uri.fsPath ); + // Logger.getInstance().debug('uri is : ' + uri.fsPath ); // if (uri && uri.fsPath) { // vscode.window.withProgress({ // location: vscode.ProgressLocation.Notification, @@ -531,19 +532,19 @@ export function activate(context: vscode.ExtensionContext) { // cancellable: false // }, async (progress) => { // const filename = path.basename(uri.fsPath); - // console.log('get filename ' ); + // Logger.getInstance().debug('get filename ' ); // if (filename.endsWith('.d.ts')) { // // Display a message box to the user // // analyze // let res = parseTsFile(uri.fsPath); - // console.info('res: ' + JSON.stringify(res)); + // Logger.getInstance().info('res: ' + JSON.stringify(res)); // progress.report({ increment: 50, message: PARSE_COMPLETE }); // // generator // let out = path.dirname(uri.fsPath); // genCppFile(res, uri.fsPath, out); // progress.report({ increment: 100, message: GEN_COMPLETE + out }); // } else { - // console.log('not dts uri is : ' + uri.fsPath ); + // Logger.getInstance().debug('not dts uri is : ' + uri.fsPath ); // // Display a message box to the user // vscode.window.showInformationMessage(`${uri.fsPath} is not a .d.ts file!`); // } @@ -618,8 +619,8 @@ export function activate(context: vscode.ExtensionContext) { // }, async (progress) => { // // analyze // let funDescList = await parseHeaderFile(hdfInputPath); -// console.log('parse header file res: ', funDescList); -// console.log('parse header file jsonstr: ', JSON.stringify(funDescList)); +// Logger.getInstance().debug('parse header file res: ', funDescList); +// Logger.getInstance().debug('parse header file jsonstr: ', JSON.stringify(funDescList)); // progress.report({ increment: 50, message: PARSE_COMPLETE }); // // generator // let out = path.dirname(hdfInputPath); @@ -648,8 +649,8 @@ export function activate(context: vscode.ExtensionContext) { // }, async (progress) => { // // analyze // let funDescList = await parseHeaderFile(hPath); -// console.log('parse header file res: ', funDescList); -// console.log('parse header file jsonstr: ', JSON.stringify(funDescList)); +// Logger.getInstance().debug('parse header file res: ', funDescList); +// Logger.getInstance().debug('parse header file jsonstr: ', JSON.stringify(funDescList)); // progress.report({ increment: 50, message: PARSE_COMPLETE }); @@ -682,8 +683,8 @@ export function activate(context: vscode.ExtensionContext) { // // analyze // let funDescList = await parseHeaderFile(hFilePath); // let fileName = path.basename(hFilePath, '.h'); -// console.log('parse header file res: ', funDescList); -// console.log('parse header file jsonstr: ', JSON.stringify(funDescList)); +// Logger.getInstance().debug('parse header file res: ', funDescList); +// Logger.getInstance().debug('parse header file jsonstr: ', JSON.stringify(funDescList)); // progress.report({ increment: 50, message: PARSE_COMPLETE }); diff --git a/src/vscode_plugin/src/gen/gendts.ts b/src/vscode_plugin/src/gen/gendts.ts index 4c8893be..c00e1cc5 100644 --- a/src/vscode_plugin/src/gen/gendts.ts +++ b/src/vscode_plugin/src/gen/gendts.ts @@ -16,6 +16,7 @@ import fs = require('fs'); import { DtscppRootInfo, FuncObj, InterfaceBody, ParamObj, FuncInfo, GenInfo, InterfaceList, TypeList } from './datatype'; import { dts2cpp_key } from '../template/dtscpp/dts2cpp_key'; import path = require('path'); +import { Logger } from '../common/log'; import { generateRandomInteger, removeComments, removeTab, replaceAll } from '../common/tool'; import util = require('util'); @@ -369,7 +370,7 @@ export function genDtsInterface(path: string, typeList: TypeList[], interfaceLis if (basicTypeMatch) { for (let index = 0; index < basicTypeMatch.length; index++) { // 输出匹配的基本类型定义 - console.log('Basic type typedef match:', basicTypeMatch[0]); + Logger.getInstance().debug('Basic type typedef match:' + basicTypeMatch[0]); let matchs = basicTypeMatch[index].split(' '); let rawType = getJsTypeFromC(matchs[1].trim()); let defineType = matchs[2].split(';') @@ -553,6 +554,6 @@ export function genDtsFile(rootInfo: GenInfo) { let dirPath = path.dirname(rootInfo.rawFilePath); let outPath = path.join(dirPath, dtsFileName); fs.writeFileSync(outPath, fileContent); - console.info('generate success!') + Logger.getInstance().info('generate success!') return outPath; } \ No newline at end of file diff --git a/src/vscode_plugin/src/gen/gendtscpp.ts b/src/vscode_plugin/src/gen/gendtscpp.ts index 49926b95..9ce31595 100644 --- a/src/vscode_plugin/src/gen/gendtscpp.ts +++ b/src/vscode_plugin/src/gen/gendtscpp.ts @@ -22,7 +22,7 @@ import { cppout, dtscppout } from "../template/dtscpp/dtscppdir"; import { analyzeRootFunction, genDtsInterface, genTsFunction } from "./gendts"; import { generateDirectFunction } from "./gencpp"; import { generateFuncTestCase } from "./gentest"; - +import { Logger } from "../common/log"; import { tsTransferType } from "../template/functypemap_template"; interface GenResult { @@ -137,7 +137,7 @@ function generateFuncCode(rootInfo: DtscppRootInfo) { export function genDtsCppFile(rootInfo: DtscppRootInfo, out: string) { let res: GenResult = generateFuncCode(rootInfo); genDir(dtscppout, res, rootInfo, out); - console.info('generate success!') + Logger.getInstance().info('generate success!') } // dts2cpp @@ -149,7 +149,7 @@ export function genCppFile(parseObj: ParseObj, tsFilePath: string, out: string) }; let genResult: GenResult = generateFunctions(parseObj, tsFilePath); genDir(cppout, genResult, rootInfo, out); - console.info('generate success!') + Logger.getInstance().info('generate success!') } function generateFunctions(parseObj: ParseObj, tsFilePath: string) { diff --git a/src/vscode_plugin/src/gen/genhdf.ts b/src/vscode_plugin/src/gen/genhdf.ts index 84f69bf5..061adc54 100644 --- a/src/vscode_plugin/src/gen/genhdf.ts +++ b/src/vscode_plugin/src/gen/genhdf.ts @@ -21,7 +21,7 @@ import { genIdlFile } from './tools/genidlfile'; import { genServiceHFile } from './tools/genservicehfile'; import { genServiceCppFile } from './tools/genservicecppfile'; import { genHdfCommonFile } from './tools/gencommonfile'; - +import { Logger } from '../common/log'; const fileHandlers: { [key: string]: Function } = { 'I[marcoName]Interface.idl': genIdlFile, '[driverName]_interface_service.h': genServiceHFile, @@ -64,12 +64,12 @@ function genDir(dirItem: DirTemp, rootInfo: HdfRootInfo, out: string) { } export function genHdfFile(rootInfo: HdfRootInfo, out: string) { - console.info("rootInfo: " + JSON.stringify(rootInfo)) + Logger.getInstance().info("rootInfo: " + JSON.stringify(rootInfo)) let dirContentTemplete = hdf_version_map.get(rootInfo.versionTag); if (dirContentTemplete !== undefined) { genDir(dirContentTemplete, rootInfo, out); } - console.info('generate success!') + Logger.getInstance().info('generate success!') } \ No newline at end of file diff --git a/src/vscode_plugin/src/gen/gensa.ts b/src/vscode_plugin/src/gen/gensa.ts index ba2a5e09..196e54a2 100644 --- a/src/vscode_plugin/src/gen/gensa.ts +++ b/src/vscode_plugin/src/gen/gensa.ts @@ -27,7 +27,7 @@ import { genStubHFile } from './tools/genstubhfile'; import { genStubCppFile } from './tools/genstubcppfile'; import { genClientCppFile } from './tools/genclientcppfile'; import { genSaCommonFile } from './tools/gencommonfile'; - +import { Logger } from '../common/log'; const fileHandlers: { [key: string]: Function } = { '[serviceName]_service_proxy.h': genProxyHFile, '[serviceName]_service_proxy.cpp': genProxyCppFile, @@ -74,12 +74,12 @@ function genDir(dirItem: DirTemp, rootInfo: ServiceRootInfo, out: string) { } export function genServiceFile(rootInfo: ServiceRootInfo, out: string) { - console.info("rootInfo: " + JSON.stringify(rootInfo)) + Logger.getInstance().info("rootInfo: " + JSON.stringify(rootInfo)) let dirContentTemplete = sa_version_map.get(rootInfo.versionTag); if (dirContentTemplete !== undefined) { genDir(dirContentTemplete, rootInfo, out); } - console.info('generate success!') + Logger.getInstance().info('generate success!') } diff --git a/src/vscode_plugin/src/gen/gentest.ts b/src/vscode_plugin/src/gen/gentest.ts index 03dcebe7..dff29fdc 100644 --- a/src/vscode_plugin/src/gen/gentest.ts +++ b/src/vscode_plugin/src/gen/gentest.ts @@ -18,6 +18,8 @@ import { replaceAll } from "../common/tool"; import { FuncInfo, InterfaceList, ParamObj, TypeList } from "./datatype"; import { getInterfaceBody, getJsTypeFromC, getTypeBody, isBoolType, isNumberType, isStringType } from './gendts'; import { testAbilityFuncTemplate } from "../template/func_template"; +import { Logger } from '../common/log'; + const INTVALUE = 5; const FLOATVALUE = 2.5; @@ -29,12 +31,12 @@ export function generateFuncTestCase(funcInfo: FuncInfo, rawFileName: string, t let callFunc = ''; let hilogContent = ''; // 调用函数 - console.info("test funcInfo:" + JSON.stringify(funcInfo)); + Logger.getInstance().info("test funcInfo:" + JSON.stringify(funcInfo)); if (getJsType(funcInfo.retType) !== 'void') { callFunc = util.format('let result: %s = testNapi.%s(%s)\n ', getJsType(funcInfo.retType), funcInfo.genName, funcParamUse); // 加 hilog 打印 hilogContent = util.format('hilog.info(0x0000, "testTag", "Test NAPI %s: ", JSON.stringify(result));\n ', funcInfo.genName); - hilogContent += util.format('console.info("testTag", "Test NAPI %s: ", JSON.stringify(result));\n ', funcInfo.genName); + hilogContent += util.format('Logger.getInstance().info("testTag", "Test NAPI %s: ", JSON.stringify(result));\n ', funcInfo.genName); } else { callFunc = util.format('testNapi.%s(%s)\n ', funcInfo.genName, funcParamUse); } diff --git a/src/vscode_plugin/src/model/crosscompilemod.ts b/src/vscode_plugin/src/model/crosscompilemod.ts index 17f2714f..a9f9612a 100644 --- a/src/vscode_plugin/src/model/crosscompilemod.ts +++ b/src/vscode_plugin/src/model/crosscompilemod.ts @@ -19,7 +19,7 @@ import { parseHeaderFile } from '../parse/parsec'; import { GenInfo } from '../gen/datatype'; import { genDtsFile } from '../gen/gendts'; import { GEN_COMPLETE, PARSE_COMPLETE } from '../common/constants'; - +import { Logger } from '../common/log'; import { EVENT_ERROR, EVENT_INFORMATION, @@ -51,7 +51,7 @@ export class CrossCompileMod extends IModel { if (this.uri) { // parse let parseRes = await parseHeaderFile(this.uri.fsPath); - console.log('parse header file res: ', parseRes); + Logger.getInstance().debug('parse header file res: ' + parseRes); this.emmitEventForKey(EVENT_PROGRESS, 50, PARSE_COMPLETE); let rootInfo: GenInfo = { @@ -63,11 +63,11 @@ export class CrossCompileMod extends IModel { let outPath = genDtsFile(rootInfo); this.emmitEventForKey(EVENT_PROGRESS, 100, PARSE_COMPLETE); } else { - console.error('parse header file error with undefine uri.'); + Logger.getInstance().error('parse header file error with undefine uri.'); } } catch (e) { let errmsg = 'parse header file error: ' + JSON.stringify(e); - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } diff --git a/src/vscode_plugin/src/model/dts2cppmod.ts b/src/vscode_plugin/src/model/dts2cppmod.ts index f8f58bd2..c2ba0df1 100644 --- a/src/vscode_plugin/src/model/dts2cppmod.ts +++ b/src/vscode_plugin/src/model/dts2cppmod.ts @@ -28,7 +28,7 @@ import { } from '../common/eventtype'; import { parseTsFile } from '../parse/parsets'; import { genCppFile } from '../gen/gendtscpp'; - +import { Logger } from '../common/log'; export class Dts2cppMod extends IModel { name: string; private static instance: Dts2cppMod; @@ -52,12 +52,12 @@ export class Dts2cppMod extends IModel { try { if (this.uri) { const filename = path.basename(this.uri.fsPath); - console.log('get filename ' ); + Logger.getInstance().debug('get filename ' ); if (filename.endsWith('.d.ts')) { // Display a message box to the user // analyze let res = parseTsFile(this.uri.fsPath); - console.info('res: ' + JSON.stringify(res)); + Logger.getInstance().info('res: ' + JSON.stringify(res)); // progress.report({ increment: 50, message: PARSE_COMPLETE }); this.emmitEventForKey(EVENT_PROGRESS, 50, PARSE_COMPLETE); // generator @@ -76,19 +76,19 @@ export class Dts2cppMod extends IModel { } } else { let errmsg = 'not dts uri is : ' + this.uri.fsPath; - console.error(errmsg); + Logger.getInstance().error(errmsg); // Display a message box to the user //vscode.window.showInformationMessage(`${this.uri.fsPath} is not a .d.ts file!`); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } else { let errmsg = 'parse header file error with undefine uri'; - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } catch (e) { let errmsg = 'parse header file error: ' + JSON.stringify(e); - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } diff --git a/src/vscode_plugin/src/model/h2dtscppmod.ts b/src/vscode_plugin/src/model/h2dtscppmod.ts index 431827c7..4cc0cc35 100644 --- a/src/vscode_plugin/src/model/h2dtscppmod.ts +++ b/src/vscode_plugin/src/model/h2dtscppmod.ts @@ -19,7 +19,7 @@ import { parseHeaderFile } from '../parse/parsec'; import { DtscppRootInfo, GenInfo } from '../gen/datatype'; import { genDtsFile } from '../gen/gendts'; import { GEN_COMPLETE, OPEN_IN_EXPLORER, PARSE_COMPLETE } from '../common/constants'; - +import { Logger } from '../common/log'; import { EVENT_ERROR, EVENT_INFORMATION, @@ -53,8 +53,8 @@ export class H2dtscppMod extends IModel { // analyze let funDescList = await parseHeaderFile(this.uri.fsPath); let fileName = path.basename(this.uri.fsPath, '.h'); - console.log('parse header file res: ', funDescList); - console.log('parse header file jsonstr: ', JSON.stringify(funDescList)); + Logger.getInstance().debug('parse header file res: ' + funDescList); + Logger.getInstance().debug('parse header file jsonstr: ' + JSON.stringify(funDescList)); // progress.report({ increment: 50, message: PARSE_COMPLETE }); this.emmitEventForKey(EVENT_PROGRESS, 50, PARSE_COMPLETE); @@ -81,12 +81,12 @@ export class H2dtscppMod extends IModel { } } else { let errmsg = 'parse header file error with undefine uri'; - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } catch (e) { let errmsg = 'parse header file error: ' + JSON.stringify(e); - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } diff --git a/src/vscode_plugin/src/model/h2dtsmod.ts b/src/vscode_plugin/src/model/h2dtsmod.ts index dbc1a1d6..851541bd 100644 --- a/src/vscode_plugin/src/model/h2dtsmod.ts +++ b/src/vscode_plugin/src/model/h2dtsmod.ts @@ -19,7 +19,7 @@ import { parseHeaderFile } from '../parse/parsec'; import { GenInfo } from '../gen/datatype'; import { genDtsFile } from '../gen/gendts'; import { GEN_COMPLETE, PARSE_COMPLETE } from '../common/constants'; - +import { Logger } from '../common/log'; import { EVENT_ERROR, EVENT_INFORMATION, @@ -51,7 +51,7 @@ export class H2dtsMod extends IModel { if (this.uri) { // parse let parseRes = await parseHeaderFile(this.uri.fsPath); - console.log('parse header file res: ', parseRes); + Logger.getInstance().debug('parse header file res: ' + parseRes); this.emmitEventForKey(EVENT_PROGRESS, 50, PARSE_COMPLETE); let rootInfo: GenInfo = { @@ -63,11 +63,11 @@ export class H2dtsMod extends IModel { let outPath = genDtsFile(rootInfo); this.emmitEventForKey(EVENT_PROGRESS, 100, PARSE_COMPLETE); } else { - console.error('parse header file error with undefine uri.'); + Logger.getInstance().error('parse header file error with undefine uri.'); } } catch (e) { let errmsg = 'parse header file error: ' + JSON.stringify(e); - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } diff --git a/src/vscode_plugin/src/model/h2hdfmod.ts b/src/vscode_plugin/src/model/h2hdfmod.ts index 4fb7e5de..f178a80b 100644 --- a/src/vscode_plugin/src/model/h2hdfmod.ts +++ b/src/vscode_plugin/src/model/h2hdfmod.ts @@ -19,7 +19,7 @@ import { parseHeaderFile } from '../parse/parsec'; import { GenInfo } from '../gen/datatype'; import { genDtsFile } from '../gen/gendts'; import { GEN_COMPLETE, OPEN_IN_EXPLORER, PARSE_COMPLETE } from '../common/constants'; - +import { Logger } from '../common/log'; import { EVENT_ERROR, EVENT_INFORMATION, @@ -62,8 +62,8 @@ export class H2hdfMod extends IModel { async generateHdf(hdfInputPath: string, versionTag: string) { // analyze let funDescList = await parseHeaderFile(hdfInputPath); - console.log('parse header file res: ', funDescList); - console.log('parse header file jsonstr: ', JSON.stringify(funDescList)); + Logger.getInstance().debug('parse header file res: ' + funDescList); + Logger.getInstance().debug('parse header file jsonstr: ' + JSON.stringify(funDescList)); this.emmitEventForKey(EVENT_PROGRESS, 50, PARSE_COMPLETE); // generator let out = path.dirname(hdfInputPath); @@ -91,12 +91,12 @@ export class H2hdfMod extends IModel { this.generateHdf(this.uri.fsPath, this.versionTag); } else { let errmsg = 'parse header file error with undefine uri.'; - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } catch (e) { let errmsg = 'parse header file error: ' + JSON.stringify(e); - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } diff --git a/src/vscode_plugin/src/model/h2samod.ts b/src/vscode_plugin/src/model/h2samod.ts index 6ebb3318..19d2a26c 100644 --- a/src/vscode_plugin/src/model/h2samod.ts +++ b/src/vscode_plugin/src/model/h2samod.ts @@ -20,7 +20,7 @@ import { GenInfo } from '../gen/datatype'; import { genDtsFile } from '../gen/gendts'; import { GEN_COMPLETE, OPEN_IN_EXPLORER, PARSE_COMPLETE } from '../common/constants'; import { genServiceFile } from '../gen/gensa'; - +import { Logger } from '../common/log'; import { EVENT_ERROR, EVENT_INFORMATION, @@ -61,8 +61,8 @@ export class H2saMod extends IModel { async generateSa(hPath: string, versionTag: string, serviceId: string) { // analyze let funDescList = await parseHeaderFile(hPath); - console.log('parse header file res: ', funDescList); - console.log('parse header file jsonstr: ', JSON.stringify(funDescList)); + Logger.getInstance().debug('parse header file res: ' + funDescList); + Logger.getInstance().debug('parse header file jsonstr: ' + JSON.stringify(funDescList)); this.emmitEventForKey(EVENT_PROGRESS, 50, PARSE_COMPLETE); @@ -92,11 +92,11 @@ export class H2saMod extends IModel { if (this.uri) { this.generateSa(this.uri.fsPath, this.versionTag, this.serviceId); } else { - console.error('parse header file error with undefine uri.'); + Logger.getInstance().error('parse header file error with undefine uri.'); } } catch (e) { let errmsg = 'parse header file error: ' + JSON.stringify(e); - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } diff --git a/src/vscode_plugin/src/model/imodel.ts b/src/vscode_plugin/src/model/imodel.ts index 88005a32..ad3daf5c 100644 --- a/src/vscode_plugin/src/model/imodel.ts +++ b/src/vscode_plugin/src/model/imodel.ts @@ -14,7 +14,7 @@ */ import * as vscode from 'vscode'; import { Callback } from "../common/define" - +import { Logger } from "../common/log"; export abstract class IModel { abstract name: string; uri: vscode.Uri | undefined = undefined; @@ -43,7 +43,7 @@ export abstract class IModel { if (callback) { callback(...args); } else { - console.error(`No callback found with key "${event}".`); + Logger.getInstance().error(`No callback found with key "${event}".`); } } } \ No newline at end of file diff --git a/src/vscode_plugin/src/model/welcomemod.ts b/src/vscode_plugin/src/model/welcomemod.ts index 7abf5335..15bf57be 100644 --- a/src/vscode_plugin/src/model/welcomemod.ts +++ b/src/vscode_plugin/src/model/welcomemod.ts @@ -19,7 +19,7 @@ import { parseHeaderFile } from '../parse/parsec'; import { GenInfo } from '../gen/datatype'; import { genDtsFile } from '../gen/gendts'; import { GEN_COMPLETE, HDF_FRAMEWORK, NAPI_FRAMEWORK, PARSE_COMPLETE, SA_FRAMEWORK } from '../common/constants'; - +import { Logger } from "../common/log"; import { EVENT_ERROR, EVENT_INFORMATION, @@ -100,15 +100,15 @@ export class WelcomeMod extends IModel { // generateHdf(this.uri.fsPath, this.versionTag); break; default: - console.error('unknown gen type: ', this.genType); + Logger.getInstance().error('unknown gen type: ' + this.genType); break; } } else { - console.error('parse header file error with undefine uri.'); + Logger.getInstance().error('parse header file error with undefine uri.'); } } catch (e) { let errmsg = 'parse header file error: ' + JSON.stringify(e); - console.error(errmsg); + Logger.getInstance().error(errmsg); this.emmitEventForKey(EVENT_ERROR, -1, errmsg); } } diff --git a/src/vscode_plugin/src/ohcrosscompile.ts b/src/vscode_plugin/src/ohcrosscompile.ts index bb4abcb9..1b0d3199 100644 --- a/src/vscode_plugin/src/ohcrosscompile.ts +++ b/src/vscode_plugin/src/ohcrosscompile.ts @@ -18,6 +18,7 @@ import * as fs from 'fs'; import * as https from 'https'; import * as zlib from 'zlib'; import * as tar from 'tar'; +import { Logger } from './common/log'; const WINDOWS_START = vscode.l10n.t('Starting compilation on Windows.'); const TERMINAL_TITLE = vscode.l10n.t('OpenHarmony Cross Compile'); @@ -49,7 +50,7 @@ export function downloadSdk(url: string, destination: string, progress: vscode.P https.get(url, (response) => { if (response.statusCode === 200) { const totalSize = parseInt(String(response.headers['content-length'])); - console.log(`totalSize: ${totalSize}`); + Logger.getInstance().debug(`totalSize: ${totalSize}`); let downloadedSize = 0; response.on('data', (chunk) => { // 设置response的data事件,当每接收一个数据块时,计算下载进度并报告 @@ -240,7 +241,7 @@ function crossCompile_win32(terminal: vscode.Terminal | undefined, thirdPartyPat } } terminal.sendText(finalCommand); - console.log(finalCommand); + Logger.getInstance().debug(finalCommand); terminal.processId.then( () => { resolve(); @@ -367,7 +368,7 @@ function crossCompile_linux(terminal: vscode.Terminal | undefined, thirdPartyPat } } terminal.sendText(finalCommand); - console.log(finalCommand); + Logger.getInstance().debug(finalCommand); terminal.processId.then( () => { resolve(); diff --git a/src/vscode_plugin/src/parse/parsec.ts b/src/vscode_plugin/src/parse/parsec.ts index 733894a7..e79ea201 100644 --- a/src/vscode_plugin/src/parse/parsec.ts +++ b/src/vscode_plugin/src/parse/parsec.ts @@ -17,7 +17,7 @@ import * as vscode from 'vscode'; import * as path from 'path'; import * as ts from 'typescript'; import { ParamObj, FuncObj, StructObj, ClassObj, EnumObj, UnionObj, ParseObj } from '../gen/datatype' - +import { Logger } from '../common/log'; import fs = require('fs'); export function parseEnum(data: string) { @@ -39,7 +39,7 @@ export function parseEnum(data: string) { } enums.push(enumItem); } - console.info(` return enums: ${JSON.stringify(enums)}`); + Logger.getInstance().info(` return enums: ${JSON.stringify(enums)}`); return enums; } @@ -75,7 +75,7 @@ export function parseUnion(data: string) { const variable = match[2]; // 解析数组长度 const arrayLength = match[4] ? parseInt(match[4], 10) : -1; - // console.log(`Type: ${type}, Variable:${variable}, Size:${arrayLength}`); + // Logger.getInstance().debug(`Type: ${type}, Variable:${variable}, Size:${arrayLength}`); let paramItem: ParamObj = { "type": type, "name": variable, @@ -87,7 +87,7 @@ export function parseUnion(data: string) { unions.push(unionItem); } - console.info(` return unions: ${JSON.stringify(unions)}`); + Logger.getInstance().info(` return unions: ${JSON.stringify(unions)}`); return unions; } @@ -134,17 +134,17 @@ export function parseStruct(data: string) { structs.push(structItem); } - // console.info(` return structs: ${JSON.stringify(structs)}`); + // Logger.getInstance().info(` return structs: ${JSON.stringify(structs)}`); return structs; } // /^(const\s+)?([\w\s*]+)\s+(\w+)(?:\[(\d+)\])?$/ export function parseParameters(members: string[]): ParamObj[] { // const memberRegex = /^(const\s+)?([\w\s*]+)\s+(\w+)(?:\[(\d+)\])?$/; const memberRegex = /^(const\s+)?([\w\s*]+)\s+(\w+)(?:\[(\d*)\])?$/; - // console.info(` parseParameters members: ${JSON.stringify(members)}`); + // Logger.getInstance().info(` parseParameters members: ${JSON.stringify(members)}`); return members.map(member => { const match = member.trim().match(memberRegex); - // console.info(` parseParameters match: ${JSON.stringify(match)}`); + // Logger.getInstance().info(` parseParameters match: ${JSON.stringify(match)}`); if (match) { const type = match[2]; const name = match[3]; @@ -159,10 +159,10 @@ export function parseParameters(members: string[]): ParamObj[] { export function parseMembers(members: string[]): ParamObj[] { const memberRegex = /(?:public:|private:)?\s*(\w+(?:\s+\w+)?)\s+(\w+)(?:\[(\d+)\])?/; - // console.info(` parseMembers members: ${JSON.stringify(members)}`); + // Logger.getInstance().info(` parseMembers members: ${JSON.stringify(members)}`); return members.map(member => { const match = member.trim().match(memberRegex); - // console.info(` parseMembers match: ${JSON.stringify(match)}`); + // Logger.getInstance().info(` parseMembers match: ${JSON.stringify(match)}`); if (match) { const type = match[1]; const name = match[2]; @@ -224,10 +224,10 @@ export function parseClass(data: string) { }); const variableList = parseMembers(variables); - // console.log(`parseMembers: ${JSON.stringify(variableList)}`) + // Logger.getInstance().debug(`parseMembers: ${JSON.stringify(variableList)}`) const functionList: FuncObj[] = parseMethods(methods); - // console.log(`parsedFunctions: ${JSON.stringify(functionList)}`); + // Logger.getInstance().debug(`parsedFunctions: ${JSON.stringify(functionList)}`); const classItem: ClassObj = { "name": className, @@ -237,7 +237,7 @@ export function parseClass(data: string) { } classes.push(classItem); } - // console.info(` return classes: ${JSON.stringify(classes)}`); + // Logger.getInstance().info(` return classes: ${JSON.stringify(classes)}`); return classes; } @@ -248,7 +248,7 @@ export function parseFunctionOld(data: string) { let functions = data.match(functionRegex1) || []; if (functions.length <= 0) { - console.info("use functionRegex2"); + Logger.getInstance().info("use functionRegex2"); functions = data.match(functionRegex2) || []; } const functionDetails: FuncObj[] = functions.map(func => { @@ -259,7 +259,7 @@ export function parseFunctionOld(data: string) { } let parts = func.trim().match(/([a-zA-Z_]\w+)\s+\(*([*a-zA-Z_]\w+)\)*\s*\(([^)]*)\)/); if (!parts) { - console.info("use regex2"); + Logger.getInstance().info("use regex2"); parts = func.trim().match(/(\w+\s*\(.*?\)\s+)(\w+)\s*\((.*?)\);\s*/); } if (parts) { @@ -268,7 +268,7 @@ export function parseFunctionOld(data: string) { let functionName = parts[index + 1].trim(); let paramList = parts[index + 2].split(','); if (parts[index].trim() === 'typedef') { - console.info("typedef -------------", parts); + Logger.getInstance().info("typedef -------------" + parts); returnType = parts[index + 1].trim(); functionName = parts[index + 2].trim(); paramList = parts[index + 3].split(','); @@ -287,7 +287,7 @@ export function parseFunctionOld(data: string) { arraySize: 0, }) } - // console.info(`ret: ${returnType} func: ${functionName} params:(${paramResList.map(ditem => { + // Logger.getInstance().info(`ret: ${returnType} func: ${functionName} params:(${paramResList.map(ditem => { // return ' type: ' + ditem.type + ', ' + 'name: ' + ditem.name; // })})`) let funcRes: FuncObj = { @@ -308,7 +308,7 @@ export function parseFunctionOld(data: string) { }) .filter(detail => detail !== null); - console.log(`parse oldfunc : ${JSON.stringify(functionDetails)}`) + Logger.getInstance().debug(`parse oldfunc : ${JSON.stringify(functionDetails)}`) return functionDetails; // if (functionDetails.length > 0) { // const funcs = [...functionDetails.filter((funcItem) : funcItem is FuncObj => funcItem !== null)]; @@ -319,7 +319,7 @@ export function parseFunctionOld(data: string) { // return ' type: ' + ditem.type + ', ' + 'name: ' + ditem.name; // })})` // ).join('\n'); - // console.info(` return parseMethods: ${JSON.stringify(funcs)}`); + // Logger.getInstance().info(` return parseMethods: ${JSON.stringify(funcs)}`); // return funcs; // } else { // vscode.window.showInformationMessage('No functions found.'); @@ -332,7 +332,7 @@ export function parseFunction(data: string): FuncObj[] { const functions: FuncObj[] = [] let match; while ((match = funcRegex.exec(data)) !== null) { - // console.log(`func match: ${JSON.stringify(match)}`) + // Logger.getInstance().debug(`func match: ${JSON.stringify(match)}`) // match[3].trim(); const returnType = match[1] ? match[1].trim() : match[6].trim(); // match[4].trim(); @@ -349,7 +349,7 @@ export function parseFunction(data: string): FuncObj[] { functions.push(funcItem); } - // console.info(` return functions: ${JSON.stringify(functions)}`); + // Logger.getInstance().info(` return functions: ${JSON.stringify(functions)}`); return functions; } @@ -383,7 +383,7 @@ export function parseHeaderFile(filePath: string): Promise { classes: classList, funcs: funcList } - // console.info(` return parse result: ${JSON.stringify(parseRes)}`); + // Logger.getInstance().info(` return parse result: ${JSON.stringify(parseRes)}`); resolve(parseRes); }); }); diff --git a/src/vscode_plugin/src/parse/parsets.ts b/src/vscode_plugin/src/parse/parsets.ts index 3cc24d83..3cb3c223 100644 --- a/src/vscode_plugin/src/parse/parsets.ts +++ b/src/vscode_plugin/src/parse/parsets.ts @@ -19,6 +19,7 @@ import * as ts from 'typescript'; import { json } from 'stream/consumers'; import internal = require('stream'); import { ParamObj, FuncObj, ClassObj, EnumObj, TypeObj, ParseObj } from '../gen/datatype' +import { Logger } from '../common/log'; const fs = require('fs'); @@ -55,19 +56,19 @@ let gchecker: ts.TypeChecker; export function getTypeAliasSubtypes(typeAlias: ts.TypeAliasDeclaration, list: ParamObj[]) { // 检查类型是否为类型节点 const typeNode = typeAlias.type; - // console.log('getTypeAliasSubtypes'); + // Logger.getInstance().debug('getTypeAliasSubtypes'); try { if (ts.isUnionTypeNode(typeNode)) { // 如果是联合类型(Union Type),遍历它的子类型 - console.log('isUnionTypeNode'); + Logger.getInstance().debug('isUnionTypeNode'); return typeNode.types.map(type => JSON.stringify(type.getText())); } else if (ts.isIntersectionTypeNode(typeNode)) { // 如果是交叉类型(Intersection Type),遍历它的子类型 - console.log('isIntersectionTypeNode'); + Logger.getInstance().debug('isIntersectionTypeNode'); return typeNode.types.map(type => JSON.stringify(type.decorators)); } else if (ts.isTypeLiteralNode(typeNode)) { // 如果是类型字面量(Type Literal),遍历它的属性 - console.log('isTypeLiteralNode'); + Logger.getInstance().debug('isTypeLiteralNode'); return typeNode.members.map(member => { let nameStr = JSON.stringify(member.name); let nameObj = JSON.parse(nameStr); @@ -85,7 +86,7 @@ export function getTypeAliasSubtypes(typeAlias: ts.TypeAliasDeclaration, list: P // 处理其他类型 return [JSON.stringify(typeNode)]; } catch (error) { - console.error('Error processing node:', error); + Logger.getInstance().error('Error processing node:' + error); } return []; } @@ -137,7 +138,7 @@ export function parseTsFile(filePath: string): ParseObj { } function visitor(node: ts.Node) { if (ts.isClassDeclaration(node) && node.name) { - console.log(`Class: ${node.name.text}, ${node.members}`); + Logger.getInstance().debug(`Class: ${node.name.text}, ${node.members}`); let classItem: ClassObj = { name: node.name.text, alias: '', @@ -146,16 +147,16 @@ export function parseTsFile(filePath: string): ParseObj { }; try { node.members.forEach(member => { - // console.log(`Member: ${JSON.stringify(member)}`) + // Logger.getInstance().debug(`Member: ${JSON.stringify(member)}`) if (ts.isMethodDeclaration(member) && member.name) { const methodstr = member.name ? JSON.stringify(member.name) : 'noname'; const methodObject = JSON.parse(methodstr); const methodName = methodObject.escapedText; - console.log(`memberName: ${methodName} `); + Logger.getInstance().debug(`memberName: ${methodName} `); let returnStr = 'void'; if (member.type) { let returnObjStr = JSON.stringify(member.type); - // console.log(`returnObjStr: ${returnObjStr} `); + // Logger.getInstance().debug(`returnObjStr: ${returnObjStr} `); let returnObj = JSON.parse(returnObjStr); returnStr = getParamType(member.type); if (returnObj.typeName) { @@ -189,7 +190,7 @@ export function parseTsFile(filePath: string): ParseObj { if (param.type) { let paramTypeObjStr = JSON.stringify(param.type); - // console.log(`paramTypeObjStr: ${paramTypeObjStr} }`); + // Logger.getInstance().debug(`paramTypeObjStr: ${paramTypeObjStr} }`); paramTypeStr = getParamType(param.type); if (JSON.parse(paramTypeObjStr).typeName) { paramTypeStr = JSON.parse(paramTypeObjStr).typeName.escapedText; @@ -202,7 +203,7 @@ export function parseTsFile(filePath: string): ParseObj { }) return `${paramStr}: ${paramTypeStr}` }).join(', '); - console.log(` Method: ${methodName}, Return Type: ${returnStr}, Parameters: ${params}`); + Logger.getInstance().debug(` Method: ${methodName}, Return Type: ${returnStr}, Parameters: ${params}`); classItem.functionList.push({ name: methodName, returns: returnStr, @@ -224,40 +225,40 @@ export function parseTsFile(filePath: string): ParseObj { parseRes.classes.push(classItem); }); } catch (error) { - console.error('Error processing node:', error); + Logger.getInstance().error('Error processing node:' + error); } } else if (ts.isEnumDeclaration(node) && node.name) { try { - console.log(`Enum: ${node.name.text}`); + Logger.getInstance().debug(`Enum: ${node.name.text}`); let enumItem: EnumObj = { name: node.name.text, alias: '', members: [], }; - // console.log(`Enum: ${node.name.text}, ${node.members.length}`); + // Logger.getInstance().debug(`Enum: ${node.name.text}, ${node.members.length}`); node.members.forEach(member => { const memJsonStr = JSON.stringify(member.name); const memJsonObj = JSON.parse(memJsonStr); - // console.log(`Member: ${memJsonObj.escapedText}`) + // Logger.getInstance().debug(`Member: ${memJsonObj.escapedText}`) enumItem.members.push(memJsonObj.escapedText); }) parseRes.enums.push(enumItem); } catch (error) { - console.error('Error processing node:', error); + Logger.getInstance().error('Error processing node:' + error); } } else if (ts.isTypeAliasDeclaration(node) && node.name) { - console.log(`Type: ${node.name.text}`); + Logger.getInstance().debug(`Type: ${node.name.text}`); let typeItem: TypeObj = { name: node.name.text, alias: getParamType(node.type), members: [], }; - // console.log(`Type: ${node.name.text}, ${node.typeParameters} ${typeof(node.type)}`); + // Logger.getInstance().debug(`Type: ${node.name.text}, ${node.typeParameters} ${typeof(node.type)}`); const subtypes = getTypeAliasSubtypes(node, typeItem.members); parseRes.types!.push(typeItem); - console.log(`subtypes : ${subtypes}`); + Logger.getInstance().debug(`subtypes : ${subtypes}`); } else if (ts.isFunctionDeclaration(node) && node.name) { - console.log(`Type: ${node.name.text}`); + Logger.getInstance().debug(`Type: ${node.name.text}`); const parameters = node.parameters; let parames: ParamObj[] = []; parameters.forEach(param => { @@ -270,7 +271,7 @@ export function parseTsFile(filePath: string): ParseObj { const paramType = param.type; let paramText = getParamType(paramType); - console.log(` ${paramName}: ${paramText}`); + Logger.getInstance().debug(` ${paramName}: ${paramText}`); let parameter: ParamObj = { name: paramName, type: paramText, diff --git a/src/vscode_plugin/src/test/runTest.ts b/src/vscode_plugin/src/test/runTest.ts index 9a3d600e..674fab34 100644 --- a/src/vscode_plugin/src/test/runTest.ts +++ b/src/vscode_plugin/src/test/runTest.ts @@ -16,6 +16,7 @@ import * as path from 'path'; import { runTests } from '@vscode/test-electron'; +import { Logger } from '../common/log'; async function main() { try { @@ -30,7 +31,7 @@ async function main() { // Download VS Code, unzip it and run the integration test await runTests({ extensionDevelopmentPath, extensionTestsPath }); } catch (err) { - console.error('Failed to run tests'); + Logger.getInstance().error('Failed to run tests'); process.exit(1); } } diff --git a/src/vscode_plugin/src/test/suite/common/tool.test.ts b/src/vscode_plugin/src/test/suite/common/tool.test.ts index b44b43b4..2b3ab543 100644 --- a/src/vscode_plugin/src/test/suite/common/tool.test.ts +++ b/src/vscode_plugin/src/test/suite/common/tool.test.ts @@ -28,7 +28,7 @@ suite('Common_Tool_Test_Suite', () => { test('replaceall_test_1', () => { let resultStr = tools.replaceAll('hello_world', 'or', 'er'); assert.strictEqual(resultStr, 'hello_werld'); - + resultStr = tools.replaceAll('hello_world', 'l', 'r'); assert.strictEqual(resultStr, 'herro_worrd'); }); @@ -48,7 +48,7 @@ suite('Common_Tool_Test_Suite', () => { let resultStr = '' // 会死循环 // resultStr = tools.replaceAll('hello_world', '', 'er'); - // console.log("test replaceall_test_3 " + resultStr); + // Logger.getInstance().debug("test replaceall_test_3 " + resultStr); // assert.strictEqual(resultStr, 'hello_world'); resultStr = tools.replaceAll('hello_world', 'ahello_world', 'er'); diff --git a/src/vscode_plugin/src/test/suite/index.ts b/src/vscode_plugin/src/test/suite/index.ts index 383e3d97..2a02101e 100644 --- a/src/vscode_plugin/src/test/suite/index.ts +++ b/src/vscode_plugin/src/test/suite/index.ts @@ -16,6 +16,7 @@ import * as path from 'path'; import * as Mocha from 'mocha'; import * as glob from 'glob'; +import { Logger } from '../../common/log'; import { getOutputPath, getReportConf } from '../../common/conf'; export function run(): Promise { @@ -24,7 +25,7 @@ export function run(): Promise { ui: 'tdd' }); mocha.useColors(true); - + let reportTestResult = getReportConf(); if (reportTestResult) { let outpath = getOutputPath(); @@ -53,7 +54,7 @@ export function run(): Promise { } }); } catch (err) { - console.error(err); + Logger.getInstance().error(JSON.stringify(err)); e(err); } }); diff --git a/src/vscode_plugin/src/view/welcomeview.ts b/src/vscode_plugin/src/view/welcomeview.ts index 36bc95b6..d7849e93 100644 --- a/src/vscode_plugin/src/view/welcomeview.ts +++ b/src/vscode_plugin/src/view/welcomeview.ts @@ -25,7 +25,7 @@ import { import { IController } from '../controller/icontroller'; import { doAsyncQuickPick, toastMsg } from '../common/widget'; import { CONFIRM_SELECT, HDF_FRAMEWORK, INPUT_INCONSISTENT, INPUT_NO_EMPTY, INPUT_NUMBER, INPUT_SERVICEID, NAPI_FRAMEWORK, SA_FRAMEWORK, SELECT_FRAMWORK, SELECT_VERSION } from '../common/constants'; - +import { Logger } from '../common/log'; export class WelcomeView extends IView { name: string; model: IModel; @@ -81,7 +81,7 @@ export class WelcomeView extends IView { vscode.window.showOpenDialog(options).then(fileUri => { if (fileUri && fileUri[0]) { const filePath = fileUri[0].fsPath; - console.log('Selected path:', filePath); + Logger.getInstance().debug('Selected path:' + filePath); vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'Generating ...', -- Gitee From e58d9fff4c5ea44e692713c3e4dafd5b575a32e7 Mon Sep 17 00:00:00 2001 From: wangshi Date: Tue, 11 Feb 2025 16:16:34 +0800 Subject: [PATCH 2/2] add log conf Signed-off-by: wangshi --- src/vscode_plugin/package.json | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/vscode_plugin/package.json b/src/vscode_plugin/package.json index 8f760379..67b51939 100644 --- a/src/vscode_plugin/package.json +++ b/src/vscode_plugin/package.json @@ -38,6 +38,22 @@ "default": false, "description": "description of output flag" } + , + "genProject.policy": { + "type": "number", + "default": 1, + "description": "generate policy: 1,replace;2,append;3,new" + }, + "logger.filePath": { + "type": "string", + "default": "./", + "description": "logger file path" + }, + "logger.fileName": { + "type": "string", + "default": "dmesg.log", + "description": "logger file name" + } } }, "commands": [ -- Gitee