-
Notifications
You must be signed in to change notification settings - Fork 24
/
config.js
76 lines (70 loc) · 1.99 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
const fs = require('fs')
const template = require('./template.json')
const _ = require('lodash')
const Q = require('q')
const Logger = new (require('./logger'))()
const args = require('args')
const flags = args.parse(process.argv)
class Config {
constructor () {
// Declares
this.filename = flags.settings
// Bindings
this.init = this.init.bind(this)
this.readSettings = this.readSettings.bind(this)
this.mergeWriteSettings = this.mergeWriteSettings.bind(this)
}
init () {
Logger.verbose('Getting settings...')
const deferred = Q.defer()
Q.fcall(this.readSettings)
.then(this.mergeWriteSettings)
.then((settings) => {
Logger.verbose('Has resolve settings')
deferred.resolve(settings)
})
.catch(error => {
Logger.error('Error happen during setting pulling:', error)
process.exit()
})
return deferred.promise
}
readSettings () {
const deferred = Q.defer()
Logger.verbose('Reading file...')
fs.readFile(this.filename, 'utf8', (error, data) => {
if (error) {
if (_.get(error, 'code', '?') === 'ENOENT') {
Logger.verbose("Didn't found file, injecting template...")
deferred.resolve(template)
} else {
Logger.verbose('Error happen', error)
deferred.reject(error)
}
} else {
Logger.verbose('Found file...')
try {
const settings = JSON.parse(data)
deferred.resolve(settings)
} catch (error) {
deferred.reject(error)
}
}
})
return deferred.promise
}
mergeWriteSettings (userSettings) {
const deferred = Q.defer()
const settings = _.assign({}, template, userSettings)
const json = JSON.stringify(settings, null, 2)
fs.writeFile(this.filename, json, 'utf8', (error) => {
if (error) {
deferred.reject(error)
} else {
deferred.resolve(settings)
}
})
return deferred.promise
}
}
module.exports = Config