summaryrefslogtreecommitdiff
path: root/packages/telemetry/src/config.ts
blob: d03f9102b182e56f371809c21a25299122a1d2fc (plain) (blame)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import dget from 'dlv';
import { dset } from 'dset';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import process from 'node:process';

export interface ConfigOptions {
	name: string;
}

// Adapted from https://github.com/sindresorhus/env-paths
function getConfigDir(name: string) {
	const homedir = os.homedir();
	const macos = () => path.join(homedir, 'Library', 'Preferences', name);
	const win = () => {
		const { APPDATA = path.join(homedir, 'AppData', 'Roaming') } = process.env;
		return path.join(APPDATA, name, 'Config');
	};
	const linux = () => {
		const { XDG_CONFIG_HOME = path.join(homedir, '.config') } = process.env;
		return path.join(XDG_CONFIG_HOME, name);
	};
	switch (process.platform) {
		case 'darwin':
			return macos();
		case 'win32':
			return win();
		default:
			return linux();
	}
}

export class GlobalConfig {
	private dir: string;
	private file: string;

	constructor(private project: ConfigOptions) {
		this.dir = getConfigDir(this.project.name);
		this.file = path.join(this.dir, 'config.json');
	}

	private _store?: Record<string, any>;
	private get store(): Record<string, any> {
		if (this._store) return this._store;
		this.ensureDir();
		if (fs.existsSync(this.file)) {
			this._store = JSON.parse(fs.readFileSync(this.file).toString());
		} else {
			const store = {};
			this._store = store;
			this.write();
		}
		return this._store!;
	}
	private set store(value: Record<string, any>) {
		this._store = value;
		this.write();
	}
	private ensureDir() {
		fs.mkdirSync(this.dir, { recursive: true });
	}
	write() {
		fs.writeFileSync(this.file, JSON.stringify(this.store, null, '\t'));
	}
	clear(): void {
		this.store = {};
		fs.rmSync(this.file, { recursive: true });
	}
	delete(key: string): boolean {
		dset(this.store, key, undefined);
		this.write();
		return true;
	}
	get(key: string): any {
		return dget(this.store, key);
	}
	has(key: string): boolean {
		return typeof this.get(key) !== 'undefined';
	}
	set(key: string, value: any): void {
		dset(this.store, key, value);
		this.write();
	}
}