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 */
15
16import fs from 'fs';
17import path from 'path';
18import envConfig from '../config/env';
19import { LogUtil } from './logUtil';
20import { StringConstant } from '../utils/Constant';
21if (!process.env.DIR_NAME) {
22  Object.assign(process.env, envConfig);
23}
24export class FileUtils {
25  /**
26   * 通过动态环境变量配置项目根目录的地址
27   */
28  private static baseDirName: string = String(process.env.DIR_NAME);
29  /**
30   * 获取项目根目录的地址,相关配置可以查看src\config\env.ts中的DIR_NAME配置
31   */
32  static getBaseDirName(): string {
33    return this.baseDirName;
34  }
35  /**
36   * 读取文件,返回满足要求的所有文件路径
37   *
38   * @param {string} dirName 文件目录
39   * @param {(name: string) => boolean} [filter] 文件路径的过滤条件
40   * @return {Array<string>}
41   */
42  static readFilesInDir(dirName: string, filter?: (name: string) => boolean): Array<string> {
43    const files: Array<string> = [];
44    if (!fs.existsSync(dirName)) {
45      return files;
46    }
47    fs.readdirSync(dirName, { withFileTypes: true }).forEach((dir) => {
48      if (dir.name === StringConstant.NOT_SCAN_DIR) {
49        return;
50      }
51      const filePath: string = path.join(dirName, dir.name);
52      if (dir.isFile()) {
53        if (!filter) {
54          files.push(filePath);
55          return;
56        }
57        if (filter(dir.name)) {
58          files.push(filePath);
59        }
60        return;
61      }
62      files.push(...FileUtils.readFilesInDir(filePath, filter));
63    });
64    return files;
65  }
66
67  static writeStringToFile(str: string, filePath: string): void {
68    const parentDir: string = path.dirname(filePath);
69    if (!FileUtils.isExists(parentDir)) {
70      fs.mkdirSync(parentDir, { recursive: true });
71    }
72    fs.writeFileSync(filePath, str);
73  }
74
75  static isDirectory(path: string): boolean {
76    const stats: fs.Stats = fs.lstatSync(path);
77    return stats.isDirectory();
78  }
79
80  static isFile(path: string): boolean {
81    const stats: fs.Stats = fs.lstatSync(path);
82    return stats.isFile();
83  }
84
85  static isExists(pathName: string | undefined): boolean {
86    if (!pathName) {
87      return false;
88    }
89    try {
90      fs.accessSync(path.resolve(this.baseDirName, pathName), fs.constants.R_OK);
91      return true;
92    } catch (exception) {
93      const error = exception as Error;
94      LogUtil.e(`error filePath`, error.stack ? error.stack : error.message);
95      return false;
96    }
97  }
98}
99