-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathconfig.js
82 lines (72 loc) · 2.37 KB
/
config.js
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
import path from 'node:path';
import os from 'node:os';
import { readJson, writeJson } from './file.js';
import { existsSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
export const GLOBAL_CONFIG = Symbol('globalConfig');
export const PROJECT_CONFIG = Symbol('projectConfig');
export const LOCAL_CONFIG = Symbol('localConfig');
export function getNcurcPath() {
if (process.env.XDG_CONFIG_HOME !== 'undefined' &&
process.env.XDG_CONFIG_HOME !== undefined) {
return path.join(process.env.XDG_CONFIG_HOME, 'ncurc');
} else {
return path.join(os.homedir(), '.ncurc');
}
}
export function getMergedConfig(dir, home) {
const globalConfig = getConfig(GLOBAL_CONFIG, home);
const projectConfig = getConfig(PROJECT_CONFIG, dir);
const localConfig = getConfig(LOCAL_CONFIG, dir);
return Object.assign(globalConfig, projectConfig, localConfig);
};
export function getConfig(configType, dir) {
const configPath = getConfigPath(configType, dir);
const encryptedConfigPath = configPath + '.gpg';
if (existsSync(encryptedConfigPath)) {
const { status, stdout } =
spawnSync('gpg', ['--decrypt', encryptedConfigPath]);
if (status === 0) {
return JSON.parse(stdout.toString('utf-8'));
}
}
try {
return readJson(configPath);
} catch (cause) {
throw new Error('Unable to parse config file ' + configPath, { cause });
}
};
export function getConfigPath(configType, dir) {
switch (configType) {
case GLOBAL_CONFIG:
return getNcurcPath();
case PROJECT_CONFIG: {
const projectRcPath = path.join(dir || process.cwd(), '.ncurc');
return projectRcPath;
}
case LOCAL_CONFIG: {
const ncuDir = getNcuDir(dir);
const configPath = path.join(ncuDir, 'config');
return configPath;
}
default:
throw Error('Invalid configType');
}
};
export function writeConfig(configType, obj, dir) {
writeJson(getConfigPath(configType, dir), obj);
};
export function updateConfig(configType, obj, dir) {
const config = getConfig(configType, dir);
const configPath = getConfigPath(configType, dir);
writeJson(configPath, Object.assign(config, obj));
};
export function getHomeDir(home) {
if (process.env.XDG_CONFIG_HOME) {
return process.env.XDG_CONFIG_HOME;
}
return home || os.homedir();
};
export function getNcuDir(dir) {
return path.join(dir || process.cwd(), '.ncu');
};