-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathconfigValue.ts
63 lines (51 loc) · 1.54 KB
/
configValue.ts
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
import * as vscode from 'vscode';
const sectionName = 'extension-test-runner';
const walkObject = <T>(value: T, replacer: (value: unknown) => any): T => {
if (value instanceof Array) {
return value.map(replacer) as T;
}
if (value && typeof value === 'object') {
const newValue = {} as Record<string, unknown>;
for (const [k, v] of Object.entries(value)) {
newValue[replacer(k)] = walkObject(v, replacer);
}
return newValue as T;
}
return replacer(value);
};
export class ConfigValue<T> {
private readonly changeEmitter = new vscode.EventEmitter<T>();
private readonly changeListener: vscode.Disposable;
private _value!: T;
public readonly onDidChange = this.changeEmitter.event;
public get value() {
return this._value;
}
public get key() {
return `${sectionName}.${this.sectionKey}`;
}
constructor(
private readonly sectionKey: string,
defaultValue: T,
scope?: vscode.ConfigurationScope,
) {
this.changeListener = vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration(this.key)) {
this.setValue(
vscode.workspace.getConfiguration(sectionName, scope).get(sectionKey) ?? defaultValue,
);
}
});
this.setValue(
vscode.workspace.getConfiguration(sectionName, scope).get(sectionKey) ?? defaultValue,
);
}
public dispose() {
this.changeListener.dispose();
this.changeEmitter.dispose();
}
private setValue(value: T) {
this._value = value;
this.changeEmitter.fire(this._value);
}
}