1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
11 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
12 | };
|
13 | Object.defineProperty(exports, "__esModule", { value: true });
|
14 | exports.MustacheFile = void 0;
|
15 | const mustache_1 = __importDefault(require("mustache"));
|
16 | const mrm_core_1 = require("mrm-core");
|
17 | const fs_1 = require("fs");
|
18 | const File_1 = require("../Base/File");
|
19 |
|
20 |
|
21 |
|
22 | class MustacheFile extends File_1.File {
|
23 | constructor(basePath, filename, templatePath) {
|
24 | super(basePath);
|
25 | this.templatePath = templatePath;
|
26 | this.partialsPaths = {};
|
27 | this.templateData = {};
|
28 | this.actions = [];
|
29 | this.removeOnRollback = true;
|
30 | this.overwrite = false;
|
31 | this.cdIn();
|
32 | this.filePointer = (0, mrm_core_1.file)(filename);
|
33 | this.cdOut();
|
34 | }
|
35 | |
36 |
|
37 |
|
38 | getPartials() {
|
39 | return Object.keys(this.partialsPaths).reduce((result, name) => {
|
40 | result[name] = this.readTemplate(this.partialsPaths[name]);
|
41 | return result;
|
42 | }, {});
|
43 | }
|
44 | |
45 |
|
46 |
|
47 | readTemplate(templatePath) {
|
48 | try {
|
49 | return (0, fs_1.readFileSync)(templatePath, 'utf8');
|
50 | }
|
51 | catch (err) {
|
52 | if (err.code === 'ENOENT') {
|
53 | throw Error(`Template file not found: ${templatePath}`);
|
54 | }
|
55 | else {
|
56 | throw err;
|
57 | }
|
58 | }
|
59 | }
|
60 | |
61 |
|
62 |
|
63 | get() {
|
64 | return this.filePointer.get();
|
65 | }
|
66 | |
67 |
|
68 |
|
69 | exists() {
|
70 | return this.filePointer.exists();
|
71 | }
|
72 | |
73 |
|
74 |
|
75 |
|
76 | partials(partials) {
|
77 | this.partialsPaths = partials;
|
78 | return this;
|
79 | }
|
80 | |
81 |
|
82 |
|
83 | apply(contents) {
|
84 | this.templateData = contents || {};
|
85 | return this;
|
86 | }
|
87 | |
88 |
|
89 |
|
90 | commit() {
|
91 | this.cdIn();
|
92 | |
93 |
|
94 |
|
95 |
|
96 | if (this.filePointer.exists() && !this.overwrite) {
|
97 | this.cdOut();
|
98 | return;
|
99 | }
|
100 | try {
|
101 | this.filePointer.save(mustache_1.default.render(this.readTemplate(this.templatePath), this.templateData, this.getPartials()));
|
102 | this.cdOut();
|
103 | }
|
104 | catch (error) {
|
105 | this.cdOut();
|
106 | throw error;
|
107 | }
|
108 | }
|
109 | |
110 |
|
111 |
|
112 | rollback() {
|
113 | this.cdIn();
|
114 | |
115 |
|
116 |
|
117 |
|
118 | if (this.filePointer.exists() && this.removeOnRollback) {
|
119 | this.filePointer.delete();
|
120 | }
|
121 | this.cdOut();
|
122 | }
|
123 | }
|
124 | exports.MustacheFile = MustacheFile;
|