aboutsummaryrefslogtreecommitdiff
path: root/deps/node/deps/npm/node_modules/config-chain/index.js
blob: 0ef3a91f7358071db9398b8a44f4cb9a18ebe058 (plain)
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
var ProtoList = require('proto-list')
  , path = require('path')
  , fs = require('fs')
  , ini = require('ini')
  , EE = require('events').EventEmitter
  , url = require('url')
  , http = require('http')

var exports = module.exports = function () {
  var args = [].slice.call(arguments)
    , conf = new ConfigChain()

  while(args.length) {
    var a = args.shift()
    if(a) conf.push
          ( 'string' === typeof a
            ? json(a)
            : a )
  }

  return conf
}

//recursively find a file...

var find = exports.find = function () {
  var rel = path.join.apply(null, [].slice.call(arguments))

  function find(start, rel) {
    var file = path.join(start, rel)
    try {
      fs.statSync(file)
      return file
    } catch (err) {
      if(path.dirname(start) !== start) // root
        return find(path.dirname(start), rel)
    }
  }
  return find(__dirname, rel)
}

var parse = exports.parse = function (content, file, type) {
  content = '' + content
  // if we don't know what it is, try json and fall back to ini
  // if we know what it is, then it must be that.
  if (!type) {
    try { return JSON.parse(content) }
    catch (er) { return ini.parse(content) }
  } else if (type === 'json') {
    if (this.emit) {
      try { return JSON.parse(content) }
      catch (er) { this.emit('error', er) }
    } else {
      return JSON.parse(content)
    }
  } else {
    return ini.parse(content)
  }
}

var json = exports.json = function () {
  var args = [].slice.call(arguments).filter(function (arg) { return arg != null })
  var file = path.join.apply(null, args)
  var content
  try {
    content = fs.readFileSync(file,'utf-8')
  } catch (err) {
    return
  }
  return parse(content, file, 'json')
}

var env = exports.env = function (prefix, env) {
  env = env || process.env
  var obj = {}
  var l = prefix.length
  for(var k in env) {
    if(k.indexOf(prefix) === 0)
      obj[k.substring(l)] = env[k]
  }

  return obj
}

exports.ConfigChain = ConfigChain
function ConfigChain () {
  EE.apply(this)
  ProtoList.apply(this, arguments)
  this._awaiting = 0
  this._saving = 0
  this.sources = {}
}

// multi-inheritance-ish
var extras = {
  constructor: { value: ConfigChain }
}
Object.keys(EE.prototype).forEach(function (k) {
  extras[k] = Object.getOwnPropertyDescriptor(EE.prototype, k)
})
ConfigChain.prototype = Object.create(ProtoList.prototype, extras)

ConfigChain.prototype.del = function (key, where) {
  // if not specified where, then delete from the whole chain, scorched
  // earth style
  if (where) {
    var target = this.sources[where]
    target = target && target.data
    if (!target) {
      return this.emit('error', new Error('not found '+where))
    }
    delete target[key]
  } else {
    for (var i = 0, l = this.list.length; i < l; i ++) {
      delete this.list[i][key]
    }
  }
  return this
}

ConfigChain.prototype.set = function (key, value, where) {
  var target

  if (where) {
    target = this.sources[where]
    target = target && target.data
    if (!target) {
      return this.emit('error', new Error('not found '+where))
    }
  } else {
    target = this.list[0]
    if (!target) {
      return this.emit('error', new Error('cannot set, no confs!'))
    }
  }
  target[key] = value
  return this
}

ConfigChain.prototype.get = function (key, where) {
  if (where) {
    where = this.sources[where]
    if (where) where = where.data
    if (where && Object.hasOwnProperty.call(where, key)) return where[key]
    return undefined
  }
  return this.list[0][key]
}

ConfigChain.prototype.save = function (where, type, cb) {
  if (typeof type === 'function') cb = type, type = null
  var target = this.sources[where]
  if (!target || !(target.path || target.source) || !target.data) {
    // TODO: maybe save() to a url target could be a PUT or something?
    // would be easy to swap out with a reddis type thing, too
    return this.emit('error', new Error('bad save target: '+where))
  }

  if (target.source) {
    var pref = target.prefix || ''
    Object.keys(target.data).forEach(function (k) {
      target.source[pref + k] = target.data[k]
    })
    return this
  }

  var type = type || target.type
  var data = target.data
  if (target.type === 'json') {
    data = JSON.stringify(data)
  } else {
    data = ini.stringify(data)
  }

  this._saving ++
  fs.writeFile(target.path, data, 'utf8', function (er) {
    this._saving --
    if (er) {
      if (cb) return cb(er)
      else return this.emit('error', er)
    }
    if (this._saving === 0) {
      if (cb) cb()
      this.emit('save')
    }
  }.bind(this))
  return this
}

ConfigChain.prototype.addFile = function (file, type, name) {
  name = name || file
  var marker = {__source__:name}
  this.sources[name] = { path: file, type: type }
  this.push(marker)
  this._await()
  fs.readFile(file, 'utf8', function (er, data) {
    if (er) this.emit('error', er)
    this.addString(data, file, type, marker)
  }.bind(this))
  return this
}

ConfigChain.prototype.addEnv = function (prefix, env, name) {
  name = name || 'env'
  var data = exports.env(prefix, env)
  this.sources[name] = { data: data, source: env, prefix: prefix }
  return this.add(data, name)
}

ConfigChain.prototype.addUrl = function (req, type, name) {
  this._await()
  var href = url.format(req)
  name = name || href
  var marker = {__source__:name}
  this.sources[name] = { href: href, type: type }
  this.push(marker)
  http.request(req, function (res) {
    var c = []
    var ct = res.headers['content-type']
    if (!type) {
      type = ct.indexOf('json') !== -1 ? 'json'
           : ct.indexOf('ini') !== -1 ? 'ini'
           : href.match(/\.json$/) ? 'json'
           : href.match(/\.ini$/) ? 'ini'
           : null
      marker.type = type
    }

    res.on('data', c.push.bind(c))
    .on('end', function () {
      this.addString(Buffer.concat(c), href, type, marker)
    }.bind(this))
    .on('error', this.emit.bind(this, 'error'))

  }.bind(this))
  .on('error', this.emit.bind(this, 'error'))
  .end()

  return this
}

ConfigChain.prototype.addString = function (data, file, type, marker) {
  data = this.parse(data, file, type)
  this.add(data, marker)
  return this
}

ConfigChain.prototype.add = function (data, marker) {
  if (marker && typeof marker === 'object') {
    var i = this.list.indexOf(marker)
    if (i === -1) {
      return this.emit('error', new Error('bad marker'))
    }
    this.splice(i, 1, data)
    marker = marker.__source__
    this.sources[marker] = this.sources[marker] || {}
    this.sources[marker].data = data
    // we were waiting for this.  maybe emit 'load'
    this._resolve()
  } else {
    if (typeof marker === 'string') {
      this.sources[marker] = this.sources[marker] || {}
      this.sources[marker].data = data
    }
    // trigger the load event if nothing was already going to do so.
    this._await()
    this.push(data)
    process.nextTick(this._resolve.bind(this))
  }
  return this
}

ConfigChain.prototype.parse = exports.parse

ConfigChain.prototype._await = function () {
  this._awaiting++
}

ConfigChain.prototype._resolve = function () {
  this._awaiting--
  if (this._awaiting === 0) this.emit('load', this)
}