This repository has been archived by the owner on May 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.js
121 lines (90 loc) · 2.62 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
'use strict';
var fs = require('fs');
var path = require('path');
var log = require('./log');
var fse = require('fs-extra');
var utils = require('./utils');
/**
* The config file is a simple key=value list
*/
class Config {
constructor(configDir, defaultConfig) {
this.directory = path.join(utils.home, '.' + configDir);
this.file = path.join(this.directory, 'config');
this.defaultConfig = defaultConfig;
this.createFile();
}
// This will create the config file if needed
createFile() {
try {
fse.ensureDirSync(this.directory);
} catch(e) {
if ( e.code != 'EEXIST' ) throw e;
}
if (!utils.fileExists(this.file)) {
fs.writeFileSync(this.file, this.serialize(this.defaultConfig));
log.d('Created the default config file in ' + this.file);
}
}
loadConfigFromFile(raw) {
this.createFile();
var fileContent = fs.readFileSync(this.file, 'utf8');
if (fileContent === false) {
log.e('An error occured when creating the default config file');
process.exit();
}
if (raw) {
return fileContent;
}
return this.unserialize(fileContent);
}
saveConfigToFile(conf) {
fs.writeFileSync(this.file, this.serialize(conf));
}
get(key, defaultValue) {
var config = this.loadConfigFromFile();
if (typeof config[key] == 'undefined') {
return defaultValue;
}
return config[key];
}
set(key, value) {
var config = this.loadConfigFromFile();
config[key] = value;
this.saveConfigToFile(config);
}
all(raw) {
if (raw) {
return this.loadConfigFromFile(true);
}
return this.loadConfigFromFile();
}
has(key) {
var config = this.loadConfigFromFile();
return typeof config[key] != 'undefined';
}
serialize(conf) {
var tmp = [];
for (var key in conf) {
if (conf.hasOwnProperty(key)) {
tmp.push(key + '=' + conf[key]);
}
}
return tmp.join("\n");
}
unserialize(conf) {
var values = conf.split("\n");
var out = {};
// A config line looks like this:
// example.of.key=some value
for (var i = 0; i < values.length; i++) {
if (values[i].length == 0) {
continue;
}
values[i] = values[i].split('=');
out[values[i][0]] = values[i][1] || '';
}
return out;
}
}
module.exports = Config;