1export type PropertiesItem =
2  | {
3      type: 'comment';
4      value: string;
5    }
6  | {
7      type: 'empty';
8    }
9  | {
10      type: 'property';
11      key: string;
12      value: string;
13    };
14
15export function parsePropertiesFile(contents: string): PropertiesItem[] {
16  const propertiesList: PropertiesItem[] = [];
17  const lines = contents.split('\n');
18  for (let i = 0; i < lines.length; i++) {
19    const line = lines[i].trim();
20    if (!line) {
21      propertiesList.push({ type: 'empty' });
22    } else if (line.startsWith('#')) {
23      propertiesList.push({ type: 'comment', value: line.substring(1).trimStart() });
24    } else {
25      const eok = line.indexOf('=');
26      const key = line.slice(0, eok);
27      const value = line.slice(eok + 1, line.length);
28      propertiesList.push({ type: 'property', key, value });
29    }
30  }
31
32  return propertiesList;
33}
34
35export function propertiesListToString(props: PropertiesItem[]): string {
36  let output = '';
37  for (let i = 0; i < props.length; i++) {
38    const prop = props[i];
39    if (prop.type === 'empty') {
40      output += '';
41    } else if (prop.type === 'comment') {
42      output += '# ' + prop.value;
43    } else if (prop.type === 'property') {
44      output += `${prop.key}=${prop.value}`;
45    } else {
46      // @ts-ignore: assertion
47      throw new Error(`Invalid properties type "${prop.type}"`);
48    }
49    if (i < props.length - 1) {
50      output += '\n';
51    }
52  }
53  return output;
54}
55