aboutsummaryrefslogtreecommitdiffhomepage
path: root/cli/config.js
blob: bb5c4ad5ee73331814c1011be1e5ca95f81cff4a (plain) (blame)
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
/* jshint node:true */

'use strict';

var fs = require('fs'),
    path = require('path'),
    safe = require('safetydance'),
    _ = require('underscore');

exports = module.exports = {
    clear: clear,
    set: set,
    get: get,
    unset: unset,
    has: has,

    // convenience
    server: function () { return get('server'); },
    accessToken: function () { return get('accessToken'); }
};

var HOME = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var CONFIG_FILE_PATH = path.join(HOME, '.surfer.json');

var gConfig = (function () {
    return safe.JSON.parse(safe.fs.readFileSync(CONFIG_FILE_PATH)) || {};
})();

function save() {
    fs.writeFileSync(CONFIG_FILE_PATH, JSON.stringify(gConfig, null, 4));
}

function clear() {
    safe.fs.unlinkSync(CONFIG_FILE_PATH);
}

function set(key, value) {
    if (typeof key === 'object') {
        _.extend(gConfig, key);
    } else {
        safe.set(gConfig, key, value);
    }
    save();
}

function get(key) {
    return safe.query(gConfig, key);
}

function unset(key /*, .... */) {
    for (var i = 0; i < arguments.length; i++) {
        gConfig = safe.unset(gConfig, arguments[i]);
    }

    save();
}

function has(key /*, ... */) {
    for (var i = 0; i < arguments.length; i++) {
        if (!(arguments[i] in gConfig)) return false;
    }
    return true;
}