forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.ts
More file actions
49 lines (40 loc) · 1.48 KB
/
Copy pathparse.ts
File metadata and controls
49 lines (40 loc) · 1.48 KB
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
import {parseArray} from '../../utils/text';
interface SiteProps {
url: string[];
}
interface SitesFixesParserOptions {
commands: string[];
getCommandPropName: (command: string) => string;
parseCommandValue: (command: string, value: string) => any;
}
export function parseSitesFixesConfig<T extends SiteProps>(text: string, options: SitesFixesParserOptions) {
const sites: T[] = [];
const blocks = text.replace(/\r/g, '').split(/^\s*={2,}\s*$/gm);
blocks.forEach((block) => {
const lines = block.split('\n');
const commandIndices: number[] = [];
lines.forEach((ln, i) => {
if (ln.match(/^\s*[A-Z]+(\s[A-Z]+)*\s*$/)) {
commandIndices.push(i);
}
});
if (commandIndices.length === 0) {
return;
}
const siteFix = {
url: parseArray(lines.slice(0, commandIndices[0]).join('\n')) as string[],
} as T;
commandIndices.forEach((commandIndex, i) => {
const command = lines[commandIndex].trim();
const valueText = lines.slice(commandIndex + 1, i === commandIndices.length - 1 ? lines.length : commandIndices[i + 1]).join('\n');
const prop = options.getCommandPropName(command);
if (!prop) {
return;
}
const value = options.parseCommandValue(command, valueText);
siteFix[prop] = value;
});
sites.push(siteFix);
});
return sites;
}