1/* 2 * Copyright (c) 2024-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 fs from 'fs'; 17import path from 'path'; 18import Logger, { LOG_MODULE_TYPE } from './logger'; 19 20const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'getAllFiles'); 21/** 22 * 从指定目录中提取指定后缀名的所有文件 23 * @param srcPath string 要提取文件的项目入口,相对或绝对路径都可 24 * @param exts string[] 要提取的文件扩展名数组,每个扩展名需以点开头 25 * @param filenameArr string[] 用来存放提取出的文件的原始路径的数组,可不传,默认为空数组 26 * @param visited: Set<string> 用来存放已经访问过的路径,避免递归栈溢出,可不传,默认为空数组 27 * @return string[] 提取出的文件的原始路径数组 28 */ 29export function getAllFiles( 30 srcPath: string, 31 exts: string[], 32 ignore: string[] = [], 33 filenameArr: string[] = [], 34 visited: Set<string> = new Set<string>() 35): string[] { 36 let ignoreFiles: Set<string> = new Set(ignore); 37 // 如果源目录不存在,直接结束程序 38 if (!fs.existsSync(srcPath)) { 39 logger.error(`Input directory ${srcPath} is not exist, please check!`); 40 return filenameArr; 41 } 42 43 // 获取src的绝对路径 44 const realSrc = fs.realpathSync(srcPath); 45 if (visited.has(realSrc)) { 46 return filenameArr; 47 } 48 visited.add(realSrc); 49 50 // 遍历src,判断文件类型 51 fs.readdirSync(realSrc).forEach(filename => { 52 if (ignoreFiles.has(filename)) { 53 return; 54 } 55 // 拼接文件的绝对路径 56 const realFile = path.resolve(realSrc, filename); 57 58 //TODO: 增加排除文件后缀和目录 59 60 // 如果是目录,递归提取 61 if (fs.statSync(realFile).isDirectory()) { 62 getAllFiles(realFile, exts, ignore, filenameArr, visited); 63 } else { 64 // 如果是文件,则判断其扩展名是否在给定的扩展名数组中 65 if (exts.includes(path.extname(filename))) { 66 filenameArr.push(realFile); 67 } 68 } 69 }); 70 return filenameArr; 71} 72