• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023-2024 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 * as fs from 'node:fs';
16import * as path from 'node:path';
17
18export function getConfiguredRuleTags(
19  arkTSRulesMap: Map<number, string>,
20  configuredRulesMap: Map<string, string[]>
21): Set<number> {
22  const mergedRulesMap: string[] = Array.from(configuredRulesMap.values()).flat();
23  const configuredRuleTags = new Set<number>();
24  const mergedRulesSet = new Set(mergedRulesMap);
25  arkTSRulesMap.forEach((key, value) => {
26    if (mergedRulesSet.has(key)) {
27      configuredRuleTags.add(value);
28    }
29  });
30  return configuredRuleTags;
31}
32
33export function getRulesFromConfig(configRulePath: string): Map<string, string[]> {
34  try {
35    const normalizedPath = path.normalize(configRulePath);
36    const data = fs.readFileSync(normalizedPath, 'utf-8');
37    const jsonData = JSON.parse(data);
38    const dataMap = new Map<string, any>();
39    for (const [key, value] of Object.entries(jsonData)) {
40      dataMap.set(key, value);
41    }
42    return convertToStringArrayMap(dataMap);
43  } catch (error) {
44    if (error instanceof SyntaxError) {
45      throw new Error(`JSON parsing failed: ${error.message}`);
46    }
47    return new Map<string, string[]>();
48  }
49}
50
51function convertToStringArrayMap(inputMap: Map<string, any>): Map<string, string[]> {
52  const resultMap: Map<string, string[]> = new Map();
53  for (const [key, value] of inputMap) {
54    if (isStringArray(value)) {
55      resultMap.set(key, value);
56    }
57  }
58  return resultMap;
59}
60
61function isStringArray(value: any): value is string[] {
62  return (
63    Array.isArray(value) &&
64    value.every((item) => {
65      return typeof item === 'string';
66    })
67  );
68}
69