UNPKG

2.12 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const fs = require("fs");
4const lodash_1 = require("lodash");
5const os_1 = require("os");
6const path_1 = require("path");
7const YAML = require("yamljs");
8const defaultCfgName_1 = require("../const/defaultCfgName");
9const _data = Symbol('data');
10class ConfigWriter {
11 constructor(file = ConfigWriter.filepath) {
12 this.file = file;
13 this.refresh();
14 }
15 get data() {
16 return this[_data];
17 }
18 /** This will automatically save */
19 clear() {
20 this[_data] = {};
21 return this.save();
22 }
23 get(key, scope = "global" /* DEFAULT_SCOPE */) {
24 return lodash_1.get(this[_data], [scope, key], null);
25 }
26 refresh() {
27 try {
28 const contents = fs.readFileSync(this.file, 'utf8');
29 const parsed = YAML.parse(contents);
30 this[_data] = lodash_1.isEmpty(parsed) ? {} : parsed;
31 }
32 catch (_a) {
33 this[_data] = {};
34 }
35 return this;
36 }
37 refreshAndSave() {
38 const d = lodash_1.cloneDeep(this[_data]);
39 this.refresh();
40 lodash_1.merge(this[_data], d);
41 return this.save();
42 }
43 save() {
44 if (lodash_1.isEmpty(this[_data])) {
45 try {
46 fs.unlinkSync(this.file);
47 }
48 catch (_a) {
49 //noop
50 }
51 }
52 else {
53 //tslint:disable-next-line:no-magic-numbers
54 fs.writeFileSync(this.file, YAML.stringify(this[_data], Number.MAX_VALUE, 2));
55 }
56 return this;
57 }
58 set(key, value, scope = "global" /* DEFAULT_SCOPE */) {
59 lodash_1.set(this[_data], [scope, key], value);
60 return this;
61 }
62 unset(key, scope = "global" /* DEFAULT_SCOPE */) {
63 lodash_1.unset(this[_data], [scope, key]);
64 if (lodash_1.isEmpty(this[_data][scope])) {
65 delete this[_data][scope];
66 }
67 return this;
68 }
69}
70exports.ConfigWriter = ConfigWriter;
71ConfigWriter.filepath = path_1.join(os_1.homedir(), defaultCfgName_1.defaultCfgName);