forked from steveukx/git-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigList.ts
More file actions
64 lines (47 loc) · 1.66 KB
/
ConfigList.ts
File metadata and controls
64 lines (47 loc) · 1.66 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { ConfigListSummary, ConfigValues } from '../../../typings';
import { last, splitOn } from '../utils';
export class ConfigList implements ConfigListSummary {
public files: string[] = [];
public values: { [fileName: string]: ConfigValues } = Object.create(null);
private _all: ConfigValues | undefined;
public get all(): ConfigValues {
if (!this._all) {
this._all = this.files.reduce((all: ConfigValues, file: string) => {
return Object.assign(all, this.values[file]);
}, {});
}
return this._all;
}
public addFile(file: string): ConfigValues {
if (!(file in this.values)) {
const latest = last(this.files);
this.values[file] = latest ? Object.create(this.values[latest]) : {}
this.files.push(file);
}
return this.values[file];
}
public addValue(file: string, key: string, value: string) {
const values = this.addFile(file);
if (!values.hasOwnProperty(key)) {
values[key] = value;
} else if (Array.isArray(values[key])) {
(values[key] as string[]).push(value);
} else {
values[key] = [values[key] as string, value];
}
this._all = undefined;
}
}
export function configListParser(text: string): ConfigList {
const config = new ConfigList();
const lines = text.split('\0');
for (let i = 0, max = lines.length - 1; i < max;) {
const file = configFilePath(lines[i++]);
const [key, value] = splitOn(lines[i++], '\n');
config.addValue(file, key, value);
}
return config;
}
function configFilePath(filePath: string): string {
return filePath.replace(/^(file):/, '');
}