UNPKG

2.36 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const tslib_1 = require("tslib");
4const fs = require("fs-extra");
5const lodash_1 = require("lodash");
6const typescript_lazy_get_decorator_1 = require("typescript-lazy-get-decorator");
7const YAML = require("yamljs");
8const AbstractReadWriter_1 = require("./AbstractReadWriter");
9class ObjectWriter extends AbstractReadWriter_1.AbstractReadWriter {
10 constructor(path, format) {
11 super(path);
12 this.format = format;
13 this.read();
14 }
15 get parseFn() {
16 //tslint:disable:no-unbound-method
17 switch (this.format) {
18 case 1 /* YAML */:
19 return YAML.parse.bind(YAML);
20 default:
21 return JSON.parse;
22 }
23 //tslint:enable:no-unbound-method
24 }
25 get stringifyFn() {
26 //tslint:disable:no-unbound-method no-magic-numbers
27 switch (this.format) {
28 case 1 /* YAML */:
29 return YAML.stringify.bind(YAML);
30 default:
31 return (v) => JSON.stringify(v, null, 2);
32 }
33 //tslint:enable:no-unbound-method no-magic-numbers
34 }
35 get(p) {
36 return lodash_1.get(this.contents, p);
37 }
38 has(p) {
39 return lodash_1.has(this.contents, p);
40 }
41 read() {
42 lodash_1.noop(this.dirname);
43 try {
44 this.contents = this.parseFn(fs.readFileSync(this.file, 'utf8'));
45 }
46 catch (e) {
47 if (e.code === 'ENOENT') {
48 this.contents = {};
49 }
50 else {
51 throw e;
52 }
53 }
54 return this;
55 }
56 set(p, v, override = true) {
57 if (override || !this.has(p)) {
58 lodash_1.set(this.contents, p, v);
59 }
60 return this;
61 }
62 toString() {
63 return this.stringifyFn(this.contents) + '\n';
64 }
65}
66tslib_1.__decorate([
67 typescript_lazy_get_decorator_1.LazyGetter(),
68 tslib_1.__metadata("design:type", Function),
69 tslib_1.__metadata("design:paramtypes", [])
70], ObjectWriter.prototype, "parseFn", null);
71tslib_1.__decorate([
72 typescript_lazy_get_decorator_1.LazyGetter(),
73 tslib_1.__metadata("design:type", Function),
74 tslib_1.__metadata("design:paramtypes", [])
75], ObjectWriter.prototype, "stringifyFn", null);
76exports.ObjectWriter = ObjectWriter;