1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15import path, { ParsedPath } from 'path'; 16import fs, { Stats } from 'fs'; 17import { Workbook, Worksheet } from 'exceljs'; 18import ts, { LineAndCharacter } from 'typescript'; 19import { ApiResultSimpleInfo, ApiResultInfo, ApiResultMessage, ApiCheckInfo, ErrorBaseInfo } from '../typedef/checker/result_type'; 20import { ApiInfo, BasicApiInfo, ClassInfo, ParentClass } from '../typedef/parser/ApiInfoDefination'; 21import { FileUtils } from './FileUtils'; 22import { ApiCheckVersion } from '../coreImpl/checker/config/api_check_version.json'; 23import { PunctuationMark } from './Constant'; 24import { Comment } from '../typedef/parser/Comment'; 25import { currentFilePath } from '../coreImpl/checker/src/api_check_plugin'; 26import { toNumber } from 'lodash'; 27 28 29export class PosOfNode { 30 /** 31 * 获取行列信息 32 * @param { ts.Node } node 33 * @param { ts.Diagnostic } diagnostic 34 */ 35 static getPosOfNode(node: ts.Node, diagnostic: ts.Diagnostic): string { 36 const posOfNode: LineAndCharacter = ts.getLineAndCharacterOfPosition( 37 node.getSourceFile(), 38 diagnostic.start as number 39 ); 40 const location: string = 41 (diagnostic.file?.fileName as string) + `(line: ${posOfNode.line + 1}, col: ${posOfNode.character + 1})`; 42 return location; 43 } 44} 45 46export class CompolerOptions { 47 /** 48 * tsconfig配置项设置 49 */ 50 static getCompolerOptions(): ts.CompilerOptions { 51 const compilerOptions: ts.CompilerOptions = ts.readConfigFile( 52 path.resolve(FileUtils.getBaseDirName(), './tsconfig.json'), 53 ts.sys.readFile 54 ).config.compilerOptions; 55 Object.assign(compilerOptions, { 56 target: 'es2020', 57 jsx: 'preserve', 58 incremental: undefined, 59 declaration: undefined, 60 declarationMap: undefined, 61 emitDeclarationOnly: undefined, 62 outFile: undefined, 63 composite: undefined, 64 tsBuildInfoFile: undefined, 65 noEmit: undefined, 66 isolatedModules: true, 67 paths: undefined, 68 rootDirs: undefined, 69 types: undefined, 70 out: undefined, 71 noLib: undefined, 72 noResolve: true, 73 noEmitOnError: undefined, 74 declarationDir: undefined, 75 suppressOutputPathCheck: true, 76 allowNonTsExtensions: true, 77 }); 78 return compilerOptions; 79 } 80} 81 82export class GenerateFile { 83 /** 84 * 将错误信息输出为txt文件 85 * @param { ApiResultSimpleInfo[] } resultData 86 * @param { string } outputPath 87 * @param { string } option 88 */ 89 static writeFile(resultData: ApiResultMessage[], outputPath: string, option: object): void { 90 const STANDARD_INDENT: number = 2; 91 fs.writeFile( 92 path.resolve(outputPath), 93 JSON.stringify(resultData, null, STANDARD_INDENT), 94 option, 95 (err) => { 96 if (err) { 97 console.error(`ERROR FOR CREATE FILE:${err}`); 98 } else { 99 console.log('API CHECK FINISH!'); 100 } 101 } 102 ); 103 } 104 105 /** 106 * 将错误信息输出为excel文件 107 * @param { ApiResultInfo[] } apiCheckArr 108 */ 109 static async writeExcelFile(apiCheckArr: ApiResultMessage[]): Promise<void> { 110 const workbook: Workbook = new Workbook(); 111 const sheet: Worksheet = workbook.addWorksheet('Js Api', { views: [{ xSplit: 1 }] }); 112 sheet.getRow(1).values = [ 113 'order', 114 'analyzerName', 115 'buggyFilePath', 116 'codeContextStaerLine', 117 'defectLevel', 118 'defectType', 119 'description', 120 'language', 121 'mainBuggyCode', 122 'apiName', 123 'apiType', 124 'hierarchicalRelations', 125 'parentModuleName' 126 ]; 127 for (let i = 1; i <= apiCheckArr.length; i++) { 128 const apiData: ApiResultMessage = apiCheckArr[i - 1]; 129 sheet.getRow(i + 1).values = [ 130 i, 131 apiData.analyzerName, 132 apiData.getFilePath(), 133 apiData.getLocation(), 134 apiData.getLevel(), 135 apiData.getType(), 136 apiData.getMessage(), 137 apiData.language, 138 apiData.getMainBuggyCode(), 139 apiData.getExtendInfo().getApiName(), 140 apiData.getExtendInfo().getApiType(), 141 apiData.getExtendInfo().getHierarchicalRelations(), 142 apiData.getExtendInfo().getParentModuleName() 143 ]; 144 } 145 workbook.xlsx.writeBuffer().then((buffer) => { 146 fs.writeFile(path.resolve(FileUtils.getBaseDirName(), './Js_Api.xlsx'), buffer, function (err) { 147 if (err) { 148 console.error(err); 149 return; 150 } 151 }); 152 }); 153 } 154} 155 156export class ObtainFullPath { 157 /** 158 * 获取仓库中api文件夹下的所有d.ts和d.ets路径 159 * @param { string } dir -api路径 160 * @param { string[] } utFiles -存放具体路径的数组 161 */ 162 static getFullFiles(dir: string, utFiles: string[]): void { 163 try { 164 const files: string[] = fs.readdirSync(dir); 165 files.forEach((element) => { 166 const filePath: string = path.join(dir, element); 167 const status: Stats = fs.statSync(filePath); 168 if (status.isDirectory()) { 169 ObtainFullPath.getFullFiles(filePath, utFiles); 170 } else if (/\.d\.ts/.test(filePath) || /\.d\.ets/.test(filePath) || /\.ts/.test(filePath)) { 171 utFiles.push(filePath); 172 } 173 }); 174 } catch (e) { 175 console.error('ETS ERROR: ' + e); 176 } 177 } 178} 179 180export class CommonFunctions { 181 static getSinceVersion(sinceValue: string): string { 182 return sinceValue.indexOf(PunctuationMark.LEFT_PARENTHESES) !== -1 ? 183 sinceValue.substring(sinceValue.indexOf(PunctuationMark.LEFT_PARENTHESES) + 1, 184 sinceValue.indexOf(PunctuationMark.RIGHT_PARENTHESES)) : sinceValue; 185 } 186 /** 187 * 判断标签是否为官方标签 188 */ 189 static isOfficialTag(tagName: string): boolean { 190 return tagsArrayOfOrder.indexOf(tagName) === -1; 191 } 192 193 /** 194 * Replaces the set placeholder with the target 195 * @param { string } errorInfo 196 * @param { string[] } params 197 * @returns { string } 198 */ 199 static createErrorInfo(errorInfo: string, params: string[]): string { 200 params.forEach((param) => { 201 errorInfo = errorInfo.replace('$$', param); 202 }); 203 return errorInfo; 204 } 205 206 /** 207 * Obtain the current version to be checked 208 * @returns { number } 209 */ 210 static getCheckApiVersion(): string { 211 let checkApiVersion: string = '-1'; 212 try { 213 checkApiVersion = JSON.stringify(ApiCheckVersion); 214 } catch (error) { 215 throw `Failed to read package.json or parse JSON content: ${error}`; 216 } 217 if (!checkApiVersion) { 218 throw 'Please configure the correct API version to be verified'; 219 } 220 return checkApiVersion; 221 } 222 223 static judgeSpecialCase(type: ts.SyntaxKind): string[] { 224 let specialCaseType: string[] = []; 225 if (type === ts.SyntaxKind.TypeLiteral) { 226 specialCaseType = ['object']; 227 } else if (type === ts.SyntaxKind.FunctionType) { 228 specialCaseType = ['function']; 229 } 230 return specialCaseType; 231 } 232 static getExtendsApiValue(singleApi: ApiInfo): string { 233 let extendsApiValue: string = ''; 234 const extendsApiArr: ParentClass[] = (singleApi as ClassInfo).getParentClasses(); 235 if (extendsApiArr.length === 0) { 236 return extendsApiValue; 237 } 238 extendsApiArr.forEach(extendsApi => { 239 if (extendsApi.getExtendClass().length !== 0) { 240 extendsApiValue = extendsApi.getExtendClass(); 241 } 242 }); 243 return extendsApiValue; 244 } 245 246 static getImplementsApiValue(singleApi: ApiInfo): string { 247 let implementsApiValue: string = ''; 248 const implementsApiArr: ParentClass[] = (singleApi as ClassInfo).getParentClasses(); 249 if (implementsApiArr.length === 0) { 250 return implementsApiValue; 251 } 252 implementsApiArr.forEach(implementsApi => { 253 if (implementsApi.getImplementClass().length !== 0) { 254 implementsApiValue = implementsApi.getImplementClass(); 255 } 256 }); 257 return implementsApiValue; 258 } 259 260 261 static getErrorInfo(singleApi: BasicApiInfo | undefined, apiJsdoc: Comment.JsDocInfo | undefined, filePath: string, 262 errorBaseInfo: ErrorBaseInfo): ApiCheckInfo { 263 let apiInfo: ApiCheckInfo = new ApiCheckInfo(); 264 if (singleApi === undefined) { 265 return apiInfo; 266 } 267 const sinceVersion: number = apiJsdoc === undefined ? -1 : toNumber(apiJsdoc.since); 268 apiInfo 269 .setErrorID(errorBaseInfo.errorID) 270 .setErrorLevel(errorBaseInfo.errorLevel) 271 .setFilePath(filePath) 272 .setApiPostion(singleApi.getPos()) 273 .setErrorType(errorBaseInfo.errorType) 274 .setLogType(errorBaseInfo.logType) 275 .setSinceNumber(sinceVersion) 276 .setApiName(singleApi.getApiName()) 277 .setApiType(singleApi.getApiType()) 278 .setApiText(singleApi.getDefinedText()) 279 .setErrorInfo(errorBaseInfo.errorInfo) 280 .setHierarchicalRelations(singleApi.getHierarchicalRelations().join('|')) 281 .setParentModuleName(singleApi.getParentApi()?.getApiName()); 282 283 return apiInfo; 284 } 285 286 static getMdFiles(url: string): string[] { 287 const mdFiles: string[] = []; 288 const content: string = fs.readFileSync(url, 'utf-8'); 289 const filePathArr: string[] = content.split(/[(\r\n)\r\n]+/); 290 filePathArr.forEach((filePath: string) => { 291 const pathElements: Set<string> = new Set(); 292 CommonFunctions.splitPath(filePath, pathElements); 293 if (!pathElements.has('build-tools')) { 294 mdFiles.push(filePath); 295 } 296 }); 297 return mdFiles; 298 } 299 300 static splitPath(filePath: string, pathElements: Set<string>): void { 301 let spliteResult: ParsedPath = path.parse(filePath); 302 if (spliteResult.base !== '') { 303 pathElements.add(spliteResult.base); 304 CommonFunctions.splitPath(spliteResult.dir, pathElements); 305 } 306 } 307 308 static isAscending(arr: number[]): boolean { 309 for (let i = 1; i < arr.length; i++) { 310 if (arr[i] < arr[i - 1]) { 311 return false; 312 } 313 } 314 return true; 315 } 316} 317 318/** 319 * The order between labels 320 */ 321export const tagsArrayOfOrder: string[] = [ 322 'namespace', 'struct', 'typedef', 'interface', 'extends', 'implements', 'permission', 'enum', 'constant', 'type', 323 'param', 'default', 'returns', 'readonly', 'throws', 'static', 'fires', 'syscap', 'systemapi', 'famodelonly', 324 'FAModelOnly', 'stagemodelonly', 'StageModelOnly', 'crossplatform', 'form', 'atomicservice', 'since', 'deprecated', 325 'useinstead', 'test', 'example' 326]; 327 328/** 329 * Official label 330 */ 331export const officialTagArr: string[] = [ 332 'abstract', 'access', 'alias', 'async', 'augments', 'author', 'borrows', 'class', 'classdesc', 'constructs', 333 'copyright', 'event', 'exports', 'external', 'file', 'function', 'generator', 'global', 'hideconstructor', 'ignore', 334 'inheritdoc', 'inner', 'instance', 'lends', 'license', 'listens', 'member', 'memberof', 'mixes', 335 'mixin', 'modifies', 'module', 'package', 'private', 'property', 'protected', 'public', 'requires', 'see', 'summary', 336 'this', 'todo', 'tutorial', 'variation', 'version', 'yields', 'also', 'description', 'kind', 'name', 'undocumented' 337]; 338 339/** 340 * Inherit tag 341 */ 342export const inheritTagArr: string[] = ['test', 'famodelonly', 'FAModelOnly', 'stagemodelonly', 'StageModelOnly', 343 'deprecated', 'systemapi']; 344 345export const followTagArr: string[] = ['atomicservice', 'form']; 346 347/** 348 * Optional tag 349 */ 350export const optionalTags: string[] = [ 351 'static', 'fires', 'systemapi', 'famodelonly', 'FAModelOnly', 'stagemodelonly', 352 'StageModelOnly', 'crossplatform', 'deprecated', 'test', 'form', 'example', 'atomicservice' 353]; 354/** 355 * conditional optional tag 356 */ 357export const conditionalOptionalTags: string[] = ['default', 'permission', 'throws']; 358 359/** 360 * All api types that can use the permission tag. 361 */ 362export const permissionOptionalTags: ts.SyntaxKind[] = [ 363 ts.SyntaxKind.FunctionDeclaration, 364 ts.SyntaxKind.MethodSignature, 365 ts.SyntaxKind.MethodDeclaration, 366 ts.SyntaxKind.CallSignature, 367 ts.SyntaxKind.Constructor, 368 ts.SyntaxKind.PropertyDeclaration, 369 ts.SyntaxKind.PropertySignature, 370 ts.SyntaxKind.VariableStatement, 371]; 372 373/** 374 * Each api type corresponds to a set of available tags. 375 */ 376export const apiLegalityCheckTypeMap: Map<ts.SyntaxKind, string[]> = new Map([ 377 [ts.SyntaxKind.CallSignature, ['param', 'returns', 'permission', 'throws', 'syscap', 'since']], 378 [ts.SyntaxKind.ClassDeclaration, ['extends', 'implements', 'syscap', 'since']], 379 [ts.SyntaxKind.Constructor, ['param', 'syscap', 'permission', 'throws', 'syscap', 'since']], 380 [ts.SyntaxKind.EnumDeclaration, ['enum', 'syscap', 'since']], 381 [ts.SyntaxKind.FunctionDeclaration, ['param', 'returns', 'permission', 'throws', 'syscap', 'since']], 382 [ts.SyntaxKind.InterfaceDeclaration, ['typedef', 'extends', 'syscap', 'since']], 383 [ts.SyntaxKind.MethodDeclaration, ['param', 'returns', 'permission', 'throws', 'syscap', 'since']], 384 [ts.SyntaxKind.MethodSignature, ['param', 'returns', 'permission', 'throws', 'syscap', 'since']], 385 [ts.SyntaxKind.ModuleDeclaration, ['namespace', 'syscap', 'since']], 386 [ts.SyntaxKind.PropertyDeclaration, ['type', 'default', 'permission', 'throws', 'readonly', 'syscap', 'since']], 387 [ts.SyntaxKind.PropertySignature, ['type', 'default', 'permission', 'throws', 'readonly', 'syscap', 'since']], 388 [ts.SyntaxKind.VariableStatement, ['constant', 'default', 'permission', 'throws', 'syscap', 'since']], 389 [ts.SyntaxKind.TypeAliasDeclaration, ['syscap', 'since', 'typedef', 'param', 'returns', 'throws']], 390 [ts.SyntaxKind.EnumMember, ['syscap', 'since']], 391 [ts.SyntaxKind.NamespaceExportDeclaration, ['syscap', 'since']], 392 [ts.SyntaxKind.TypeLiteral, ['syscap', 'since']], 393 [ts.SyntaxKind.LabeledStatement, ['syscap', 'since']], 394 [ts.SyntaxKind.StructDeclaration, ['struct', 'syscap', 'since']], 395]); 396 397/** 398 * An array of online error messages 399 */ 400export const compositiveResult: ApiResultSimpleInfo[] = []; 401 402/** 403 * An array of local error messages 404 */ 405export const compositiveLocalResult: ApiResultInfo[] = []; 406 407export const apiCheckResult: ApiResultMessage[] = []; 408 409export const punctuationMarkSet: Set<string> = new Set(['\\{', '\\}', '\\(', '\\)', '\\[', '\\]', '\\@', '\\.', '\\:', 410 '\\,', '\\;', '\\(', '\\)', '\\"', '\\/', '\\_', '\\-', '\\=', '\\?', '\\<', '\\>', '\\,', '\\!', '\\#', '\:', '\,', 411 '\\:', '\\|', '\\%', '\\&', '\\¡', '\\¢', '\\+', '\\`', '\\\\', '\\\'']); 412