aboutsummaryrefslogtreecommitdiff
path: root/webAO/iniParse.ts
blob: ca84c3530a30ec7baca7f90ad202825c4c34c636 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
interface ParsedIni {
  [section: string]: { [key: string]: string };
}

const regexPatterns = {
  section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
  param: /^\s*([\w.\-_]+)\s*=\s*(.*?)\s*$/,
  comment: /^\s*;.*$/,
};

const valueHandler = (matchKey: string, matchValue: string): string => {
  return matchKey === "showname" ? matchValue : matchValue.toLowerCase();
};

const lineFilter = (value: string): boolean => {
  const isEmpty: boolean = value.length === 0;
  const isComment: boolean = regexPatterns.comment.test(value);

  if (isComment || isEmpty) {
    return false;
  }
  return true;
};

const iniParse = (data: string): ParsedIni => {
  const parsedIni: ParsedIni = {};
  const lines: string[] = data.split(/\r\n|\r|\n/);
  const filteredLines: string[] = lines.filter(lineFilter);

  let currentSection: string | undefined;

  filteredLines.forEach((line) => {
    const isParameter: boolean = regexPatterns.param.test(line);
    const isSection: boolean = regexPatterns.section.test(line);
    if (isParameter && currentSection) {
      const match: RegExpMatchArray | null = line.match(regexPatterns.param);

      if (match) {
        const matchKey: string = match[1].toLowerCase();
        const matchValue: string = match[2];
        parsedIni[currentSection][matchKey] = valueHandler(matchKey, matchValue);
      }
    } else if (isSection) {
      const match: RegExpMatchArray | null = line.match(regexPatterns.section);

      if (match) {
        const matchKey: string = match[1].toLowerCase();
        parsedIni[matchKey] = {};
        currentSection = matchKey;
      }
    }
  });

  return parsedIni;
};

export default iniParse;