1 | 'use strict'
|
2 |
|
3 | rc = require 'rc'
|
4 | async = require 'async'
|
5 | fs = require 'fs-extra'
|
6 | dotProp = require 'dot-prop'
|
7 | jsonFuture = require 'json-future'
|
8 | parser = require 'parse-config-file'
|
9 | parserAsync = async.asyncify parser
|
10 | serializer = require('yaml-parser').safeDump
|
11 |
|
12 | module.exports =
|
13 |
|
14 | createJSON: (opts, cb)->
|
15 | jsonFuture.saveAsync opts.file, opts.data, (err) -> cb err
|
16 |
|
17 | |
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | updateJSON: (opts, cb) ->
|
24 | jsonFuture.loadAsync opts.filename, (err, file) ->
|
25 | return cb err if err
|
26 |
|
27 | firstChar = opts.value.charAt(0)
|
28 | lastChar = opts.value.charAt(opts.value.length - 1)
|
29 | isArray = (firstChar is '[') and (lastChar is ']')
|
30 | isDotProp = opts.property.split('.').length > 1
|
31 |
|
32 | if isArray
|
33 | items = opts.value.substring(1, opts.value.length - 1)
|
34 | items = items.split(',')
|
35 | items = items.map (item) -> item.trim()
|
36 | file[opts.property] = items
|
37 | else if isDotProp
|
38 | dotProp.set(file, opts.property, opts.value)
|
39 | else
|
40 | file[opts.property] = opts.value if file[opts.property]? or opts.force
|
41 |
|
42 | jsonFuture.saveAsync(opts.filename, file, cb)
|
43 |
|
44 | initConfig: (opts) ->
|
45 | rc opts.appname, opts.default, null, parser
|
46 |
|
47 | loadConfig: (opts, cb) ->
|
48 | tasks = [
|
49 | (next) -> fs.readFile opts.path, encoding:'utf8', next
|
50 | parserAsync
|
51 | ]
|
52 |
|
53 | async.waterfall tasks, cb
|
54 |
|
55 | saveConfig: (opts, cb) ->
|
56 | data = serializer opts.data
|
57 | fs.writeFile opts.path, data, encoding: 'utf8', (err) -> cb(err)
|
58 |
|
59 | isBoolean: (n) ->
|
60 | typeof n is 'boolean'
|
61 |
|
62 | isArray: Array.isArray
|
63 |
|
64 | isEmpty: (arr) ->
|
65 | arr.length is 0
|
66 |
|
67 | includes: (arr, word) ->
|
68 | arr.indexOf(word) isnt -1
|
69 |
|
70 | noop: ->
|
71 |
|
72 | size: (arr) ->
|
73 | return 0 unless arr
|
74 | arr.length
|