-
Notifications
You must be signed in to change notification settings - Fork 0
/
township-config.js
120 lines (100 loc) · 2.36 KB
/
township-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
var fs = require('fs')
var path = require('path')
var homedir = require('os-homedir')
var isNumber = require('is-number')
var isString = require('is-string')
module.exports = Config
function Config (opts) {
if (!(this instanceof Config)) return new Config(opts)
opts = opts || {}
this.filename = opts.filename || '.townshiprc'
this.filepath = opts.filepath || path.join(homedir(), this.filename)
return this
}
Config.prototype.init = function () {
var self = this
if (self.read()) {
return
} else {
self.write({
currentLogin: null,
logins: []
})
}
}
Config.prototype.read = function () {
var self = this
var file
try {
file = fs.readFileSync(self.filepath, 'utf8')
} catch (err) {
// file not found
}
if (!file || file instanceof Error) return false
return JSON.parse(file)
}
Config.prototype.write = function (data) {
var self = this
var file = JSON.stringify(data, true, 2)
fs.writeFileSync(self.filepath, file)
}
Config.prototype.get = function (key) {
var self = this
var data = self.read()
if (!key) return data
var keys = self._parseKeys(key)
var current = keys[0]
if (keys.length === 1) return data[current]
}
Config.prototype.set = function (key, val) {
var self = this
var data = self.read()
var keys = self._parseKeys(key)
var current = keys[0]
if (keys.length === 1) {
data[current] = val
self.write(data)
}
}
Config.prototype.getLogin = function (server) {
var self = this
var logins = self.get('logins') || []
if (!server) {
return self.get('currentLogin')
}
var login = logins.find(function (item) {
if (item === null) return
return item.server === server
})
if (!login) return false
login.server = server
return login
}
Config.prototype.setLogin = function (opts) {
var self = this
var logins = self.get('logins') || []
var found = false
logins = logins.map(function (login) {
if (login === null) return
if (login.server === opts.server) {
found = true
return opts
}
})
if (!found) {
logins.push(opts)
}
self.set('logins', logins)
self.set('currentLogin', opts)
return opts
}
Config.prototype._parseKeys = function (key) {
if (isString(key)) {
var keys = key.split('.').map(function (key) {
if (isNumber(key)) return parseInt(key)
return key
})
return keys
}
return key
}