UNPKG

1.98 kBtext/coffeescriptView Raw
1'use strict'
2
3rc = require 'rc'
4async = require 'async'
5fs = require 'fs-extra'
6dotProp = require 'dot-prop'
7jsonFuture = require 'json-future'
8parser = require 'parse-config-file'
9parserAsync = async.asyncify parser
10serializer = require('yaml-parser').safeDump
11
12module.exports =
13
14 createJSON: (opts, cb)->
15 jsonFuture.saveAsync opts.file, opts.data, (err) -> cb err
16
17 ###*
18 * A sweet way to update JSON Arrays, Objects or String from String.
19 * @param {Object} opts [description]
20 * @param {Function} cb Standard NodeJS callback.
21 * @return {[type]} Standard NodeJS callback.
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