1/* 2 * Copyright (c) 2025 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 */ 15 16import { ArkFile, SourceFilePrinter } from 'arkanalyzer'; 17import { FileReports, IssueReport } from '../../model/Defects'; 18import { Engine } from '../../model/Engine'; 19import { FunctionFix } from '../../model/Fix'; 20import path from 'path'; 21// @ts-ignore 22import { removeSync } from 'fs-extra'; 23import { FileUtils, WriteFileMode } from '../../utils/common/FileUtils'; 24import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; 25import { FixUtils } from '../../utils/common/FixUtils'; 26 27const FIX_OUTPUT_DIR = './fixedCode'; 28 29const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'HomeCheckFixEngine'); 30 31export class HomeCheckFixEngine implements Engine { 32 33 constructor() { 34 removeSync(FIX_OUTPUT_DIR); 35 } 36 37 applyFix(arkFile: ArkFile, issues: IssueReport[]): FileReports { 38 let fixPath = ''; 39 const remainIssues: IssueReport[] = []; 40 for (let issue of issues) { 41 let fix = issue.fix; 42 if (fix === undefined) { 43 remainIssues.push(issue); 44 continue; 45 } 46 if (!FixUtils.isFunctionFix(fix)) { 47 remainIssues.push(issue); 48 continue; 49 } 50 let functionFix = fix as FunctionFix; 51 if (!issue.defect.fixable) { 52 remainIssues.push(issue); 53 continue; 54 } 55 if (!functionFix.fix(arkFile, issue.defect.fixKey)) { 56 remainIssues.push(issue); 57 continue; 58 } 59 fixPath = path.join(FIX_OUTPUT_DIR, arkFile.getName() + '.fix'); 60 if (this.arkFileToFile(arkFile, fixPath)) { 61 functionFix.fixed = true; 62 break; 63 } 64 } 65 return { defects: remainIssues.map((issue => issue.defect)), output: '', filePath: fixPath }; 66 } 67 68 private arkFileToFile(arkFile: ArkFile, outputPath: string): boolean { 69 if (!arkFile) { 70 return false; 71 } 72 const printer = new SourceFilePrinter(arkFile); 73 try { 74 FileUtils.writeToFile(outputPath, printer.dump(), WriteFileMode.OVERWRITE); 75 return true; 76 } catch (e) { 77 logger.error(e); 78 return false; 79 } 80 } 81} 82