diff --git a/linter/src/Autofixer.ts b/linter/lib/Autofixer.ts similarity index 100% rename from linter/src/Autofixer.ts rename to linter/lib/Autofixer.ts diff --git a/linter/src/CommandLineOptions.ts b/linter/lib/CommandLineOptions.ts similarity index 100% rename from linter/src/CommandLineOptions.ts rename to linter/lib/CommandLineOptions.ts diff --git a/linter/lib/Compiler.ts b/linter/lib/Compiler.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8c2aa55375bfb254e2bbf19c6b80dcb9c07ab93 --- /dev/null +++ b/linter/lib/Compiler.ts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023-2023 Huawei Device 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. + */ + +import type { LintOptions } from './LintOptions'; +import type * as ts from 'typescript'; + +export abstract class Compiler { + static init(instance: Compiler): void { + this.instance_ = instance; + } + + static compile(options: LintOptions, extraOptions?: any): ts.Program { + return this.getInstance().doCompile(options, extraOptions); + } + + protected abstract doCompile(options: LintOptions, extraOptions?: any): ts.Program; + + private static getInstance(): Compiler { + if (!this.instance_) { + throw new Error('Not initialized'); + } + return this.instance_; + } + + private static instance_?: Compiler; +} diff --git a/linter/src/CookBookMsg.ts b/linter/lib/CookBookMsg.ts similarity index 100% rename from linter/src/CookBookMsg.ts rename to linter/lib/CookBookMsg.ts diff --git a/linter/src/FaultAttrs.ts b/linter/lib/FaultAttrs.ts similarity index 100% rename from linter/src/FaultAttrs.ts rename to linter/lib/FaultAttrs.ts diff --git a/linter/src/FaultDesc.ts b/linter/lib/FaultDesc.ts similarity index 100% rename from linter/src/FaultDesc.ts rename to linter/lib/FaultDesc.ts diff --git a/linter/src/IncrementalLintInfo.ts b/linter/lib/IncrementalLintInfo.ts similarity index 100% rename from linter/src/IncrementalLintInfo.ts rename to linter/lib/IncrementalLintInfo.ts diff --git a/linter/src/IsFileFromModuleCallback.ts b/linter/lib/IsFileFromModuleCallback.ts similarity index 100% rename from linter/src/IsFileFromModuleCallback.ts rename to linter/lib/IsFileFromModuleCallback.ts diff --git a/linter/src/LintOptions.ts b/linter/lib/LintOptions.ts similarity index 100% rename from linter/src/LintOptions.ts rename to linter/lib/LintOptions.ts diff --git a/linter/src/LintRunResult.ts b/linter/lib/LintRunResult.ts similarity index 100% rename from linter/src/LintRunResult.ts rename to linter/lib/LintRunResult.ts diff --git a/linter/src/LinterRunner.ts b/linter/lib/LinterRunner.ts similarity index 98% rename from linter/src/LinterRunner.ts rename to linter/lib/LinterRunner.ts index 2737bdb76d92da0b14e56535b96bebc43ff43f0d..48254ef0f4db5a8bd6e9851288a29f46cd3dee26 100644 --- a/linter/src/LinterRunner.ts +++ b/linter/lib/LinterRunner.ts @@ -21,7 +21,7 @@ import { faultDesc } from './FaultDesc'; import { faultsAttrs } from './FaultAttrs'; import type { LintRunResult } from './LintRunResult'; import * as path from 'node:path'; -import { compile } from './CompilerWrapper'; +import { Compiler } from './Compiler'; import type { LintOptions } from './LintOptions'; import type { CommandLineOptions } from './CommandLineOptions'; import { AutofixInfoSet } from './Autofixer'; @@ -137,7 +137,7 @@ export function createLinter(options: LintOptions): TSCCompiledProgram { if (options.tscDiagnosticsLinter) { return options.tscDiagnosticsLinter; } - const tsProgram = options.tsProgram ?? compile(options, getStrictOptions()); + const tsProgram = options.tsProgram ?? Compiler.compile(options, getStrictOptions()); if (options.realtimeLint) { return new TSCCompiledProgramSimple(tsProgram); } diff --git a/linter/lib/Logger.ts b/linter/lib/Logger.ts new file mode 100644 index 0000000000000000000000000000000000000000..73002788af44ecb3c62ea6d7d27f40b82bdfa857 --- /dev/null +++ b/linter/lib/Logger.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023-2023 Huawei Device 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. + */ + +export abstract class Logger { + static init(instance: Logger): void { + this.instance_ = instance; + } + + static trace(message: string): void { + this.getInstance().doTrace(message); + } + + static debug(message: string): void { + this.getInstance().doDebug(message); + } + + static info(message: string): void { + this.getInstance().doInfo(message); + } + + static warn(message: string): void { + this.getInstance().doWarn(message); + } + + static error(message: string): void { + this.getInstance().doError(message); + } + + protected abstract doTrace(message: string): void; + protected abstract doDebug(message: string): void; + protected abstract doInfo(message: string): void; + protected abstract doWarn(message: string): void; + protected abstract doError(message: string): void; + + private static getInstance(): Logger { + if (!this.instance_) { + throw new Error('Not initialized'); + } + return this.instance_; + } + + private static instance_?: Logger; +} diff --git a/linter/src/ProblemInfo.ts b/linter/lib/ProblemInfo.ts similarity index 100% rename from linter/src/ProblemInfo.ts rename to linter/lib/ProblemInfo.ts diff --git a/linter/src/ProblemSeverity.ts b/linter/lib/ProblemSeverity.ts similarity index 100% rename from linter/src/ProblemSeverity.ts rename to linter/lib/ProblemSeverity.ts diff --git a/linter/src/Problems.ts b/linter/lib/Problems.ts similarity index 100% rename from linter/src/Problems.ts rename to linter/lib/Problems.ts diff --git a/linter/src/TypeScriptLinter.ts b/linter/lib/TypeScriptLinter.ts similarity index 99% rename from linter/src/TypeScriptLinter.ts rename to linter/lib/TypeScriptLinter.ts index d2e12bef085c8a62f7f6177efdfb958de5806af6..97c357ecb72cb6397dd631746acba00471a552a5 100644 --- a/linter/src/TypeScriptLinter.ts +++ b/linter/lib/TypeScriptLinter.ts @@ -25,7 +25,7 @@ import type { Autofix, AutofixInfoSet } from './Autofixer'; import * as Autofixer from './Autofixer'; import type { ProblemInfo } from './ProblemInfo'; import { ProblemSeverity } from './ProblemSeverity'; -import Logger from '../utils/logger'; +import { Logger } from './Logger'; import { ARKUI_DECORATORS } from './utils/consts/ArkUIDecorators'; import { LIMITED_STD_GLOBAL_FUNC } from './utils/consts/LimitedStdGlobalFunc'; import { LIMITED_STD_OBJECT_API } from './utils/consts/LimitedStdObjectAPI'; @@ -58,8 +58,6 @@ import { } from './utils/functions/LibraryTypeCallDiagnosticChecker'; import { forEachNodeInSubtree } from './utils/functions/ForEachNodeInSubtree'; -const logger = Logger.getLogger(); - export function consoleLog(...args: unknown[]): void { if (TypeScriptLinter.ideMode) { return; @@ -68,7 +66,7 @@ export function consoleLog(...args: unknown[]): void { for (let k = 0; k < args.length; k++) { outLine += `${args[k]} `; } - logger.info(outLine); + Logger.info(outLine); } export class TypeScriptLinter { @@ -202,7 +200,7 @@ export class TypeScriptLinter { } else { const faultDescr = faultDesc[faultId]; const faultType = LinterConfig.tsSyntaxKindNames[node.kind]; - logger.info( + Logger.info( `Warning: ${this.sourceFile!.fileName} (${line}, ${character}): ${faultDescr ? faultDescr : faultType}` ); } @@ -1456,7 +1454,7 @@ export class TypeScriptLinter { private handleElementAccessExpression(node: ts.Node): void { const tsElementAccessExpr = node as ts.ElementAccessExpression; - let tsElemAccessBaseExprType = TsUtils.getNonNullableType( + const tsElemAccessBaseExprType = TsUtils.getNonNullableType( this.tsUtils.getTypeOrTypeConstraintAtLocation(tsElementAccessExpr.expression) ); const tsElemAccessBaseExprTypeNode = this.tsTypeChecker.typeToTypeNode( diff --git a/linter/src/TypeScriptLinterConfig.ts b/linter/lib/TypeScriptLinterConfig.ts similarity index 100% rename from linter/src/TypeScriptLinterConfig.ts rename to linter/lib/TypeScriptLinterConfig.ts diff --git a/linter/src/autofixes/AutofixInfo.ts b/linter/lib/autofixes/AutofixInfo.ts similarity index 100% rename from linter/src/autofixes/AutofixInfo.ts rename to linter/lib/autofixes/AutofixInfo.ts diff --git a/linter/src/autofixes/AutofixTitles.ts b/linter/lib/autofixes/AutofixTitles.ts similarity index 100% rename from linter/src/autofixes/AutofixTitles.ts rename to linter/lib/autofixes/AutofixTitles.ts diff --git a/linter/src/autofixes/ReportAutofixCallback.ts b/linter/lib/autofixes/ReportAutofixCallback.ts similarity index 100% rename from linter/src/autofixes/ReportAutofixCallback.ts rename to linter/lib/autofixes/ReportAutofixCallback.ts diff --git a/linter/src/ts-diagnostics/GetTscDiagnostics.ts b/linter/lib/ts-diagnostics/GetTscDiagnostics.ts similarity index 100% rename from linter/src/ts-diagnostics/GetTscDiagnostics.ts rename to linter/lib/ts-diagnostics/GetTscDiagnostics.ts diff --git a/linter/src/ts-diagnostics/TSCCompiledProgram.ts b/linter/lib/ts-diagnostics/TSCCompiledProgram.ts similarity index 97% rename from linter/src/ts-diagnostics/TSCCompiledProgram.ts rename to linter/lib/ts-diagnostics/TSCCompiledProgram.ts index 6e203aa388c58633ac2b0c8072ead7745976ffa1..77d288831fee8f86abe482fe3b65de754c023d70 100644 --- a/linter/src/ts-diagnostics/TSCCompiledProgram.ts +++ b/linter/lib/ts-diagnostics/TSCCompiledProgram.ts @@ -18,7 +18,7 @@ import type { ProblemInfo } from '../ProblemInfo'; import { ProblemSeverity } from '../ProblemSeverity'; import type { LintOptions } from '../LintOptions'; import { TypeScriptDiagnosticsExtractor } from './TypeScriptDiagnosticsExtractor'; -import { compile } from '../CompilerWrapper'; +import { Compiler } from '../Compiler'; import { FaultID } from '../Problems'; import { faultsAttrs } from '../FaultAttrs'; @@ -94,7 +94,7 @@ function getTwoCompiledVersions( const wasStrict = inverseStrictOptions(compilerOptions); const inversedOptions = getStrictOptions(!wasStrict); - const withInversedOptions = compile(options, inversedOptions); + const withInversedOptions = Compiler.compile(options, inversedOptions); return { strict: wasStrict ? program : withInversedOptions, diff --git a/linter/src/ts-diagnostics/TransformTscDiagnostics.ts b/linter/lib/ts-diagnostics/TransformTscDiagnostics.ts similarity index 100% rename from linter/src/ts-diagnostics/TransformTscDiagnostics.ts rename to linter/lib/ts-diagnostics/TransformTscDiagnostics.ts diff --git a/linter/src/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts b/linter/lib/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts similarity index 100% rename from linter/src/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts rename to linter/lib/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts diff --git a/linter/src/utils/TsUtils.ts b/linter/lib/utils/TsUtils.ts similarity index 99% rename from linter/src/utils/TsUtils.ts rename to linter/lib/utils/TsUtils.ts index d9de50374eb678c95de29a5702efb3ca080ad876..e3cd75be8fbcdcce1d4790197bf0c41c8e3a9e17 100644 --- a/linter/src/utils/TsUtils.ts +++ b/linter/lib/utils/TsUtils.ts @@ -858,7 +858,7 @@ export class TsUtils { return true; } - public static getNonNullableType(t: ts.Type): ts.Type { + static getNonNullableType(t: ts.Type): ts.Type { if (TsUtils.isNullableUnionType(t)) { return t.getNonNullableType(); } diff --git a/linter/src/utils/consts/AllowedStdSymbolAPI.ts b/linter/lib/utils/consts/AllowedStdSymbolAPI.ts similarity index 100% rename from linter/src/utils/consts/AllowedStdSymbolAPI.ts rename to linter/lib/utils/consts/AllowedStdSymbolAPI.ts diff --git a/linter/src/utils/consts/ArkUIDecorators.ts b/linter/lib/utils/consts/ArkUIDecorators.ts similarity index 100% rename from linter/src/utils/consts/ArkUIDecorators.ts rename to linter/lib/utils/consts/ArkUIDecorators.ts diff --git a/linter/src/utils/consts/ArktsIgnorePaths.ts b/linter/lib/utils/consts/ArktsIgnorePaths.ts similarity index 100% rename from linter/src/utils/consts/ArktsIgnorePaths.ts rename to linter/lib/utils/consts/ArktsIgnorePaths.ts diff --git a/linter/src/utils/consts/ESObject.ts b/linter/lib/utils/consts/ESObject.ts similarity index 100% rename from linter/src/utils/consts/ESObject.ts rename to linter/lib/utils/consts/ESObject.ts diff --git a/linter/src/utils/consts/FunctionHasNoReturnErrorCode.ts b/linter/lib/utils/consts/FunctionHasNoReturnErrorCode.ts similarity index 100% rename from linter/src/utils/consts/FunctionHasNoReturnErrorCode.ts rename to linter/lib/utils/consts/FunctionHasNoReturnErrorCode.ts diff --git a/linter/src/utils/consts/LimitedStandardUtilityTypes.ts b/linter/lib/utils/consts/LimitedStandardUtilityTypes.ts similarity index 100% rename from linter/src/utils/consts/LimitedStandardUtilityTypes.ts rename to linter/lib/utils/consts/LimitedStandardUtilityTypes.ts diff --git a/linter/src/utils/consts/LimitedStdGlobalFunc.ts b/linter/lib/utils/consts/LimitedStdGlobalFunc.ts similarity index 100% rename from linter/src/utils/consts/LimitedStdGlobalFunc.ts rename to linter/lib/utils/consts/LimitedStdGlobalFunc.ts diff --git a/linter/src/utils/consts/LimitedStdObjectAPI.ts b/linter/lib/utils/consts/LimitedStdObjectAPI.ts similarity index 100% rename from linter/src/utils/consts/LimitedStdObjectAPI.ts rename to linter/lib/utils/consts/LimitedStdObjectAPI.ts diff --git a/linter/src/utils/consts/LimitedStdProxyHandlerAPI.ts b/linter/lib/utils/consts/LimitedStdProxyHandlerAPI.ts similarity index 100% rename from linter/src/utils/consts/LimitedStdProxyHandlerAPI.ts rename to linter/lib/utils/consts/LimitedStdProxyHandlerAPI.ts diff --git a/linter/src/utils/consts/LimitedStdReflectAPI.ts b/linter/lib/utils/consts/LimitedStdReflectAPI.ts similarity index 100% rename from linter/src/utils/consts/LimitedStdReflectAPI.ts rename to linter/lib/utils/consts/LimitedStdReflectAPI.ts diff --git a/linter/src/utils/consts/NonInitializablePropertyDecorators.ts b/linter/lib/utils/consts/NonInitializablePropertyDecorators.ts similarity index 100% rename from linter/src/utils/consts/NonInitializablePropertyDecorators.ts rename to linter/lib/utils/consts/NonInitializablePropertyDecorators.ts diff --git a/linter/src/utils/consts/NonReturnFunctionDecorators.ts b/linter/lib/utils/consts/NonReturnFunctionDecorators.ts similarity index 100% rename from linter/src/utils/consts/NonReturnFunctionDecorators.ts rename to linter/lib/utils/consts/NonReturnFunctionDecorators.ts diff --git a/linter/src/utils/consts/PropertyHasNoInitializerErrorCode.ts b/linter/lib/utils/consts/PropertyHasNoInitializerErrorCode.ts similarity index 100% rename from linter/src/utils/consts/PropertyHasNoInitializerErrorCode.ts rename to linter/lib/utils/consts/PropertyHasNoInitializerErrorCode.ts diff --git a/linter/src/utils/consts/StandardLibraries.ts b/linter/lib/utils/consts/StandardLibraries.ts similarity index 100% rename from linter/src/utils/consts/StandardLibraries.ts rename to linter/lib/utils/consts/StandardLibraries.ts diff --git a/linter/src/utils/consts/TypedArrays.ts b/linter/lib/utils/consts/TypedArrays.ts similarity index 100% rename from linter/src/utils/consts/TypedArrays.ts rename to linter/lib/utils/consts/TypedArrays.ts diff --git a/linter/src/utils/functions/ContainsThis.ts b/linter/lib/utils/functions/ContainsThis.ts similarity index 100% rename from linter/src/utils/functions/ContainsThis.ts rename to linter/lib/utils/functions/ContainsThis.ts diff --git a/linter/src/utils/functions/DiagnosticChecker.ts b/linter/lib/utils/functions/DiagnosticChecker.ts similarity index 100% rename from linter/src/utils/functions/DiagnosticChecker.ts rename to linter/lib/utils/functions/DiagnosticChecker.ts diff --git a/linter/src/utils/functions/ForEachNodeInSubtree.ts b/linter/lib/utils/functions/ForEachNodeInSubtree.ts similarity index 100% rename from linter/src/utils/functions/ForEachNodeInSubtree.ts rename to linter/lib/utils/functions/ForEachNodeInSubtree.ts diff --git a/linter/src/utils/functions/GetScriptKind.ts b/linter/lib/utils/functions/GetScriptKind.ts similarity index 100% rename from linter/src/utils/functions/GetScriptKind.ts rename to linter/lib/utils/functions/GetScriptKind.ts diff --git a/linter/src/utils/functions/HasPredecessor.ts b/linter/lib/utils/functions/HasPredecessor.ts similarity index 100% rename from linter/src/utils/functions/HasPredecessor.ts rename to linter/lib/utils/functions/HasPredecessor.ts diff --git a/linter/src/utils/functions/IsStdLibrary.ts b/linter/lib/utils/functions/IsStdLibrary.ts similarity index 100% rename from linter/src/utils/functions/IsStdLibrary.ts rename to linter/lib/utils/functions/IsStdLibrary.ts diff --git a/linter/src/utils/functions/IsStruct.ts b/linter/lib/utils/functions/IsStruct.ts similarity index 100% rename from linter/src/utils/functions/IsStruct.ts rename to linter/lib/utils/functions/IsStruct.ts diff --git a/linter/src/utils/functions/LibraryTypeCallDiagnosticChecker.ts b/linter/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts similarity index 100% rename from linter/src/utils/functions/LibraryTypeCallDiagnosticChecker.ts rename to linter/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts diff --git a/linter/src/utils/functions/LinterInfo.ts b/linter/lib/utils/functions/LinterInfo.ts similarity index 100% rename from linter/src/utils/functions/LinterInfo.ts rename to linter/lib/utils/functions/LinterInfo.ts diff --git a/linter/src/utils/functions/LogTscDiagnostic.ts b/linter/lib/utils/functions/LogTscDiagnostic.ts similarity index 88% rename from linter/src/utils/functions/LogTscDiagnostic.ts rename to linter/lib/utils/functions/LogTscDiagnostic.ts index a12d9c4e25b7402359d5e5172ecfbd76ad1707b2..23a8ab166775c05bc05854c0e4c906a67d1f4dfe 100644 --- a/linter/src/utils/functions/LogTscDiagnostic.ts +++ b/linter/lib/utils/functions/LogTscDiagnostic.ts @@ -15,10 +15,7 @@ import * as ts from 'typescript'; -export function logTscDiagnostic( - diagnostics: readonly ts.Diagnostic[], - log: (message: unknown, ...args: unknown[]) => void -): void { +export function logTscDiagnostic(diagnostics: readonly ts.Diagnostic[], log: (message: string) => void): void { diagnostics.forEach((diagnostic) => { let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); diff --git a/linter/src/utils/functions/MergeArrayMaps.ts b/linter/lib/utils/functions/MergeArrayMaps.ts similarity index 100% rename from linter/src/utils/functions/MergeArrayMaps.ts rename to linter/lib/utils/functions/MergeArrayMaps.ts diff --git a/linter/src/utils/functions/PathHelper.ts b/linter/lib/utils/functions/PathHelper.ts similarity index 100% rename from linter/src/utils/functions/PathHelper.ts rename to linter/lib/utils/functions/PathHelper.ts diff --git a/linter/src/utils/functions/identiferUseInValueContext.ts b/linter/lib/utils/functions/identiferUseInValueContext.ts similarity index 100% rename from linter/src/utils/functions/identiferUseInValueContext.ts rename to linter/lib/utils/functions/identiferUseInValueContext.ts diff --git a/linter/src/utils/functions/isAssignmentOperator.ts b/linter/lib/utils/functions/isAssignmentOperator.ts similarity index 100% rename from linter/src/utils/functions/isAssignmentOperator.ts rename to linter/lib/utils/functions/isAssignmentOperator.ts diff --git a/linter/src/utils/functions/isIntrinsicObjectType.ts b/linter/lib/utils/functions/isIntrinsicObjectType.ts similarity index 100% rename from linter/src/utils/functions/isIntrinsicObjectType.ts rename to linter/lib/utils/functions/isIntrinsicObjectType.ts diff --git a/linter/package.json b/linter/package.json index 6acb1be182704fd857327df08ae75f2ec2ba6c96..5ac5d3dfceaeaf2b1c62fcb56ff5fe528660bab9 100644 --- a/linter/package.json +++ b/linter/package.json @@ -21,9 +21,9 @@ "test_main": "npm run compile && rimraf test/results && node build/src/TestRunner.js test", "test_rules": "npm run compile && rimraf test_rules/results && node build/src/TestRunner.js test_rules", "update-tests": "node scripts/update-test-results.mjs test test_rules", - "eslint-check": "npx eslint --ext .ts src", + "eslint-check": "npx eslint --ext .ts src lib", "eslint-fix": "npm run eslint-check -- --fix", - "prettier-fix": "prettier src --write", + "prettier-fix": "prettier src lib --write", "fix": "npm run prettier-fix && npm run eslint-fix" }, "dependencies": { diff --git a/linter/src/CommandLineParser.ts b/linter/src/CommandLineParser.ts index 77c4116c1cf031fd19dde412938aa6085047bff6..aa06dccac30ac2fac354166a34a6bf903a6302ca 100644 --- a/linter/src/CommandLineParser.ts +++ b/linter/src/CommandLineParser.ts @@ -13,11 +13,11 @@ * limitations under the License. */ -import Logger from '../utils/logger'; -import { logTscDiagnostic } from './utils/functions/LogTscDiagnostic'; -import { decodeAutofixInfo } from './utils/functions/LinterInfo'; -import type { CommandLineOptions } from './CommandLineOptions'; -import { AUTOFIX_ALL } from './Autofixer'; +import { Logger } from '../lib/Logger'; +import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic'; +import { decodeAutofixInfo } from '../lib/utils/functions/LinterInfo'; +import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import { AUTOFIX_ALL } from '../lib/Autofixer'; import { Command, Option } from 'commander'; import * as ts from 'typescript'; import * as fs from 'node:fs'; @@ -28,8 +28,6 @@ const TSX_EXT = '.tsx'; const ETS_EXT = '.ets'; const JSON_EXT = '.json'; -const logger = Logger.getLogger(); - let inputFiles: string[]; let responseFile = ''; function addSrcFile(value: string): void { @@ -132,7 +130,7 @@ export function parseCommandLine(commandLineArgs: string[]): CommandLineOptions cmdArgs.push(...commandLineArgs); program.parse(cmdArgs); } catch (error) { - logger.error('Failed to read response file: ', error); + Logger.error('Failed to read response file: ' + error); process.exit(-1); } } @@ -146,7 +144,7 @@ function doProjectFolderArg(prjFolders: string[], opts: CommandLineOptions): voi try { opts.inputFiles.push(...getFiles(prjFolderPath)); } catch (error) { - logger.error('Failed to read folder: ', error); + Logger.error('Failed to read folder: ' + error); process.exit(-1); } } @@ -174,12 +172,12 @@ function doProjectArg(cfgPath: string, opts: CommandLineOptions): void { if (diagnostics.length > 0) { // Log all diagnostic messages and exit program. - logger.error('Failed to read config file.'); - logTscDiagnostic(diagnostics, logger.info); + Logger.error('Failed to read config file.'); + logTscDiagnostic(diagnostics, Logger.info); process.exit(-1); } } catch (error) { - logger.error('Failed to read config file: ', error); + Logger.error('Failed to read config file: ' + error); process.exit(-1); } } diff --git a/linter/src/CompilerWrapper.ts b/linter/src/CompilerImpl.ts similarity index 36% rename from linter/src/CompilerWrapper.ts rename to linter/src/CompilerImpl.ts index 7bbd532742a724383237803506f4fafcc6852398..2a8c85126901aa06a675bacba8b9b2c69dbea488 100644 --- a/linter/src/CompilerWrapper.ts +++ b/linter/src/CompilerImpl.ts @@ -13,28 +13,33 @@ * limitations under the License. */ +import { Compiler as CompilerInterface } from '../lib/Compiler'; import * as ts from 'typescript'; -import { logTscDiagnostic } from './utils/functions/LogTscDiagnostic'; -import { consoleLog } from './TypeScriptLinter'; +import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic'; +import { consoleLog } from '../lib/TypeScriptLinter'; import { formTscOptions } from './ts-compiler/FormTscOptions'; -import type { LintOptions } from './LintOptions'; +import type { LintOptions } from '../lib/LintOptions'; -export function compile(options: LintOptions, extraOptions?: unknown): ts.Program { - const createProgramOptions = formTscOptions(options.cmdOptions, extraOptions); - const program = ts.createProgram(createProgramOptions); - // Log Tsc errors if needed - if (options.cmdOptions.logTscErrors) { - const diagnostics = ts.getPreEmitDiagnostics(program); - logTscDiagnostic(diagnostics, consoleLog); - diagnostics.forEach((diagnostic) => { - if (diagnostic.file && diagnostic.start) { - const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); - const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); - consoleLog(`${diagnostic.file.fileName} (${line + 1}, ${character + 1}): ${message}`); - } else { - consoleLog(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); - } - }); +export class CompilerImpl extends CompilerInterface { + doCompile(options: LintOptions, extraOptions?: unknown): ts.Program { + void this; + + const createProgramOptions = formTscOptions(options.cmdOptions, extraOptions); + const program = ts.createProgram(createProgramOptions); + // Log Tsc errors if needed + if (options.cmdOptions.logTscErrors) { + const diagnostics = ts.getPreEmitDiagnostics(program); + logTscDiagnostic(diagnostics, consoleLog); + diagnostics.forEach((diagnostic) => { + if (diagnostic.file && diagnostic.start) { + const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + consoleLog(`${diagnostic.file.fileName} (${line + 1}, ${character + 1}): ${message}`); + } else { + consoleLog(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + } + }); + } + return program; } - return program; } diff --git a/linter/src/LinterCLI.ts b/linter/src/LinterCLI.ts index ae6ad55a266df1aa0ef9c52986e16b53ef8e981d..4dc1cc791f9adc085f6c672ab9ea47e0a4f66f2d 100644 --- a/linter/src/LinterCLI.ts +++ b/linter/src/LinterCLI.ts @@ -13,22 +13,20 @@ * limitations under the License. */ -import { TypeScriptLinter } from './TypeScriptLinter'; +import { TypeScriptLinter } from '../lib/TypeScriptLinter'; import { parseCommandLine } from './CommandLineParser'; -import Logger from '../utils/logger'; +import { Logger } from '../lib/Logger'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as readline from 'node:readline'; import * as path from 'node:path'; -import type { CommandLineOptions } from './CommandLineOptions'; -import { lint } from './LinterRunner'; - -const logger = Logger.getLogger(); +import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import { lint } from '../lib/LinterRunner'; export function run(): void { const commandLineArgs = process.argv.slice(2); if (commandLineArgs.length === 0) { - logger.info('Command line error: no arguments'); + Logger.info('Command line error: no arguments'); process.exit(-1); } @@ -90,9 +88,9 @@ function runIDEMode(cmdOptions: CommandLineOptions): void { autofix: x.autofix }; }); - logger.info(`{"linter messages":${JSON.stringify(jsonMessage)}}`); + Logger.info(`{"linter messages":${JSON.stringify(jsonMessage)}}`); } else { - logger.error('Unexpected error: could not lint file'); + Logger.error('Unexpected error: could not lint file'); } fs.unlinkSync(tmpFileName); }); diff --git a/linter/src/LoggerImpl.ts b/linter/src/LoggerImpl.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ea1759293563b78c20709d438a2420d840c6cd8 --- /dev/null +++ b/linter/src/LoggerImpl.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023-2023 Huawei Device 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. + */ + +import { Logger as LoggerInterface } from '../lib/Logger'; +import Logger from '../utils/logger'; + +export class LoggerImpl extends LoggerInterface { + doTrace(message: string): void { + void this; + Logger.getLogger().trace(message); + } + + doDebug(message: string): void { + void this; + Logger.getLogger().debug(message); + } + + doInfo(message: string): void { + void this; + Logger.getLogger().info(message); + } + + doWarn(message: string): void { + void this; + Logger.getLogger().warn(message); + } + + doError(message: string): void { + void this; + Logger.getLogger().error(message); + } +} diff --git a/linter/src/TestRunner.ts b/linter/src/TestRunner.ts index d2fbb0ca81652b733fa612e8f9edfabf9f44ea9f..563194ee1241f71e9d331e40275dd0ea88416fdf 100644 --- a/linter/src/TestRunner.ts +++ b/linter/src/TestRunner.ts @@ -13,21 +13,26 @@ * limitations under the License. */ -import { TypeScriptLinter } from './TypeScriptLinter'; -import { lint } from './LinterRunner'; +import { Logger } from '../lib/Logger'; +import { LoggerImpl } from './LoggerImpl'; +Logger.init(new LoggerImpl()); + +import { Compiler } from '../lib/Compiler'; +import { CompilerImpl } from './CompilerImpl'; +Compiler.init(new CompilerImpl()); + +import { TypeScriptLinter } from '../lib/TypeScriptLinter'; +import { lint } from '../lib/LinterRunner'; import { parseCommandLine } from './CommandLineParser'; -import type { Autofix } from './Autofixer'; -import Logger from '../utils/logger'; +import type { Autofix } from '../lib/Autofixer'; import * as fs from 'node:fs'; import * as path from 'node:path'; import * as ts from 'typescript'; -import type { CommandLineOptions } from './CommandLineOptions'; +import type { CommandLineOptions } from '../lib/CommandLineOptions'; const TEST_DIR = 'test'; const TAB = ' '; -const logger = Logger.getLogger(); - interface TestNodeInfo { line: number; column: number; @@ -76,7 +81,7 @@ function runTests(testDirs: string[]): number { x.trimEnd().endsWith(ts.Extension.Tsx) ); }); - logger.info(`\nProcessing "${testDir}" directory:\n`); + Logger.info(`\nProcessing "${testDir}" directory:\n`); // Run each test in Strict, Autofix, and Relax mode: for (const testFile of testFiles) { if (runTest(testDir, testFile, Mode.STRICT)) { @@ -99,8 +104,8 @@ function runTests(testDirs: string[]): number { } } } - logger.info(`\nSUMMARY: ${passed + failed} total, ${passed} passed or skipped, ${failed} failed.`); - logger.info(failed > 0 ? '\nTEST FAILED' : '\nTEST SUCCESSFUL'); + Logger.info(`\nSUMMARY: ${passed + failed} total, ${passed} passed or skipped, ${failed} failed.`); + Logger.info(failed > 0 ? '\nTEST FAILED' : '\nTEST SUCCESSFUL'); process.exit(hasComparisonFailures ? -1 : 0); } @@ -143,16 +148,16 @@ function compareExpectedAndActual(testDir: string, testFile: string, mode: Mode, if (!expectedResult?.nodes || expectedResult.nodes.length !== resultNodes.length) { const expectedResultCount = expectedResult?.nodes ? expectedResult.nodes.length : 0; diff = `Expected count: ${expectedResultCount} vs actual count: ${resultNodes.length}`; - logger.info(`${TAB}${diff}`); + Logger.info(`${TAB}${diff}`); } else { diff = expectedAndActualMatch(expectedResult.nodes, resultNodes); } if (diff) { - logger.info(`${TAB}Test failed. Expected and actual results differ.`); + Logger.info(`${TAB}Test failed. Expected and actual results differ.`); } } catch (error) { - logger.info(`${TAB}Test failed. `, error); + Logger.info(`${TAB}Test failed. ` + error); } return diff; @@ -160,10 +165,10 @@ function compareExpectedAndActual(testDir: string, testFile: string, mode: Mode, function runTest(testDir: string, testFile: string, mode: Mode): boolean { if (mode === Mode.AUTOFIX && fs.existsSync(path.join(testDir, testFile + AUTOFIX_SKIP_EXT))) { - logger.info(`Skipping test ${testFile} (${Mode[mode]} mode)`); + Logger.info(`Skipping test ${testFile} (${Mode[mode]} mode)`); return false; } - logger.info(`Running test ${testFile} (${Mode[mode]} mode)`); + Logger.info(`Running test ${testFile} (${Mode[mode]} mode)`); TypeScriptLinter.initGlobals(); @@ -271,7 +276,7 @@ ${expectedNode} Actual: ${actualNode}`; - logger.info(diff); + Logger.info(diff); return diff; } diff --git a/linter/src/main.ts b/linter/src/main.ts index e1b7ecf91e950ff3051b59f7d413fc88c13d01af..6ffe1703d6590be939dfb8d22f4937d24b48bfdc 100644 --- a/linter/src/main.ts +++ b/linter/src/main.ts @@ -13,6 +13,14 @@ * limitations under the License. */ +import { Logger } from '../lib/Logger'; +import { LoggerImpl } from './LoggerImpl'; +Logger.init(new LoggerImpl()); + +import { Compiler } from '../lib/Compiler'; +import { CompilerImpl } from './CompilerImpl'; +Compiler.init(new CompilerImpl()); + import { run } from './LinterCLI'; run(); diff --git a/linter/src/ts-compiler/FormTscOptions.ts b/linter/src/ts-compiler/FormTscOptions.ts index 19fce66c1bcb174842931a2f1575dd083529e976..de293100bf6fa3a4a4832d34b9f161a24e55af11 100644 --- a/linter/src/ts-compiler/FormTscOptions.ts +++ b/linter/src/ts-compiler/FormTscOptions.ts @@ -14,7 +14,7 @@ */ import * as ts from 'typescript'; -import type { CommandLineOptions } from '../CommandLineOptions'; +import type { CommandLineOptions } from '../../lib/CommandLineOptions'; export function formTscOptions(cmdOptions: CommandLineOptions, extraOptions?: unknown): ts.CreateProgramOptions { if (cmdOptions.parsedConfigFile) { diff --git a/linter/tsconfig.json b/linter/tsconfig.json index 38bce99f852138baa0ded32cf404e45eeb327e4b..5e1d00ae015576cb61181716a3726ab419935bc2 100644 --- a/linter/tsconfig.json +++ b/linter/tsconfig.json @@ -12,5 +12,5 @@ "strict": true }, - "include": ["src/**/*", "utils/*"] -} \ No newline at end of file + "include": ["src/**/*", "lib/**/*", "utils/*"] +}