UNPKG

1.9 kBJavaScriptView Raw
1/**
2
3 config-editor.js
4
5 Helper functions to edit the shipp.json file.
6
7**/
8
9
10//
11// Dependencies
12//
13
14var _ = require("lodash"),
15 fs = require("fs"),
16 path = require("path");
17
18
19var editor = module.exports = {
20
21 config: null,
22
23 defaults: require("../server/defaults.js"),
24
25 filename: path.join(process.cwd(), "shipp.json"),
26
27
28 /**
29
30 Loads and caches the config file
31
32 **/
33
34 load: function() {
35
36 if (editor.config) return editor.config;
37
38 try {
39 editor.config = fs.readFileSync(editor.filename, "utf8");
40 } catch (err) {
41 editor.config = Object.assign({}, editor.defaults);
42 }
43
44 // We don't want this in the try/catch loop as it could overwrite custom
45 // configuration files
46 if ("string" === typeof editor.config)
47 editor.config = JSON.parse(editor.config);
48
49 return editor.config;
50
51 },
52
53
54 /**
55
56 Loads defaults but does not write
57
58 **/
59
60 loadDefaults: function() {
61 editor.config = editor.defaults;
62 },
63
64
65 /**
66
67 Get a key from the config file.
68
69 @param {String} key The key to lookup (supports dot-notation)
70 @returns {*} The value of the key
71
72 **/
73
74 get: function(key) {
75 return _.get(editor.load(), key);
76 },
77
78
79 /**
80
81 Sets a key in the config file.
82
83 @param {String} key The path of the property to set (supports dot-notation)
84 @param {*} val The value to set
85
86 **/
87
88 set: function(key, val) {
89 _.set(editor.load(), key, val);
90 },
91
92
93 /**
94
95 Removes the property in the config.
96
97 @param {String} key The path of the property to unset (supports dot-notation)
98
99 **/
100
101 unset: function(key) {
102 _.unset(editor.load(), key);
103 },
104
105
106 /**
107
108 Saves the config.
109
110 **/
111
112 save: function() {
113 fs.writeFileSync(editor.filename, JSON.stringify(editor.load(), null, 2), "utf8");
114 },
115
116
117 /**
118
119 Removes the config file
120
121 **/
122
123 remove: function() {
124 fs.unlinkSync(editor.filename);
125 }
126
127};