1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const tslib_1 = require("tslib");
|
4 | const fs = require("fs-extra");
|
5 | const lazy_get_decorator_1 = require("lazy-get-decorator");
|
6 | const lodash_1 = require("lodash");
|
7 | const YAML = require("yamljs");
|
8 | const AbstractReadWriter_1 = require("./AbstractReadWriter");
|
9 | class ObjectWriter extends AbstractReadWriter_1.AbstractReadWriter {
|
10 | constructor(path, format) {
|
11 | super(path);
|
12 | this.format = format;
|
13 | this.read();
|
14 | }
|
15 | get parseFn() {
|
16 |
|
17 | switch (this.format) {
|
18 | case 1 :
|
19 | return YAML.parse.bind(YAML);
|
20 | default:
|
21 | return JSON.parse;
|
22 | }
|
23 |
|
24 | }
|
25 | get stringifyFn() {
|
26 |
|
27 | switch (this.format) {
|
28 | case 1 :
|
29 | return (v$) => YAML.stringify(v$, Number.MAX_VALUE, 2);
|
30 | default:
|
31 | return (v$) => JSON.stringify(v$, null, 2);
|
32 | }
|
33 |
|
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 | }
|
66 | tslib_1.__decorate([
|
67 | lazy_get_decorator_1.LazyGetter(),
|
68 | tslib_1.__metadata("design:type", Function),
|
69 | tslib_1.__metadata("design:paramtypes", [])
|
70 | ], ObjectWriter.prototype, "parseFn", null);
|
71 | tslib_1.__decorate([
|
72 | lazy_get_decorator_1.LazyGetter(),
|
73 | tslib_1.__metadata("design:type", Function),
|
74 | tslib_1.__metadata("design:paramtypes", [])
|
75 | ], ObjectWriter.prototype, "stringifyFn", null);
|
76 | exports.ObjectWriter = ObjectWriter;
|