/
TemplateWriter.js
339 lines (282 loc) · 8.68 KB
/
TemplateWriter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
const fastglob = require("fast-glob");
const fs = require("fs-extra");
const parsePath = require("parse-filepath");
const Template = require("./Template");
const TemplatePath = require("./TemplatePath");
const TemplateMap = require("./TemplateMap");
const TemplateRender = require("./TemplateRender");
const TemplatePassthroughManager = require("./TemplatePassthroughManager");
const EleventyError = require("./EleventyError");
const TemplateGlob = require("./TemplateGlob");
const EleventyExtensionMap = require("./EleventyExtensionMap");
const config = require("./Config");
const debug = require("debug")("Eleventy:TemplateWriter");
const debugDev = require("debug")("Dev:Eleventy:TemplateWriter");
function TemplateWriter(
inputPath,
outputDir,
templateKeys,
templateData,
isPassthroughAll
) {
this.config = config.getConfig();
this.input = inputPath;
this.inputDir = this._getInputPathDir(inputPath);
this.templateKeys = templateKeys;
this.outputDir = outputDir;
this.templateData = templateData;
this.isVerbose = true;
this.isDryRun = false;
this.writeCount = 0;
this.includesDir = this.inputDir + "/" + this.config.dir.includes;
// Duplicated with TemplateData.getDataDir();
this.dataDir = this.inputDir + "/" + this.config.dir.data;
this.extensionMap = new EleventyExtensionMap(this.templateKeys);
this.passthroughAll = isPassthroughAll;
this.setPassthroughManager();
this.setupGlobs();
}
/* For testing */
TemplateWriter.prototype.overrideConfig = function(config) {
this.config = config;
};
TemplateWriter.prototype.setupGlobs = function() {
// Input was a directory
if (this.input === this.inputDir) {
this.templateGlobs = TemplateGlob.map(
this.extensionMap.getGlobs(this.inputDir)
);
} else {
this.templateGlobs = TemplateGlob.map([this.input]);
}
this.cachedIgnores = this.getIgnores();
if (this.passthroughAll) {
this.watchedGlobs = TemplateGlob.map([
TemplateGlob.normalizePath(this.input, "/**")
]).concat(this.cachedIgnores);
} else {
this.watchedGlobs = this.templateGlobs.concat(this.cachedIgnores);
}
this.templateGlobsWithIgnores = this.watchedGlobs.concat(
this.getTemplateIgnores()
);
};
TemplateWriter.prototype.setPassthroughManager = function(mgr) {
if (!mgr) {
mgr = new TemplatePassthroughManager();
mgr.setInputDir(this.inputDir);
mgr.setOutputDir(this.outputDir);
}
this.passthroughManager = mgr;
};
TemplateWriter.prototype.restart = function() {
this.writeCount = 0;
this.passthroughManager.reset();
this.cachedPaths = null;
this.setupGlobs();
debugDev("Resetting counts to 0");
};
TemplateWriter.prototype.getIncludesDir = function() {
return this.includesDir;
};
TemplateWriter.prototype.getDataDir = function() {
return this.dataDir;
};
TemplateWriter.prototype._getInputPathDir = function(inputPath) {
// Input points to a file
if (!TemplatePath.isDirectorySync(inputPath)) {
return parsePath(inputPath).dir || ".";
}
// Input is a dir
if (inputPath) {
return inputPath;
}
return ".";
};
TemplateWriter.prototype.getFiles = function() {
return this.templateGlobsWithIgnores;
};
TemplateWriter.prototype.getRawFiles = function() {
return this.templateGlobs;
};
TemplateWriter.getFileIgnores = function(
ignoreFile,
defaultIfFileDoesNotExist
) {
let dir = parsePath(ignoreFile).dir || ".";
let ignorePath = TemplatePath.normalize(ignoreFile);
let ignoreContent;
try {
ignoreContent = fs.readFileSync(ignorePath, "utf-8");
} catch (e) {
ignoreContent = defaultIfFileDoesNotExist || "";
}
let ignores = [];
if (ignoreContent) {
ignores = ignoreContent
.split("\n")
.map(line => {
return line.trim();
})
.filter(line => {
// empty lines or comments get filtered out
return line.length > 0 && line.charAt(0) !== "#";
})
.map(line => {
let path = TemplateGlob.normalizePath(dir, "/", line);
debug(`${ignoreFile} ignoring: ${path}`);
try {
let stat = fs.statSync(path);
if (stat.isDirectory()) {
return "!" + path + "/**";
}
return "!" + path;
} catch (e) {
return "!" + path;
}
});
}
return ignores;
};
TemplateWriter.prototype.getGlobWatcherFiles = function() {
// TODO is it better to tie the includes and data to specific file extensions or keep the **?
return this.templateGlobs
.concat(this.getIncludesAndDataDirs())
.concat(this.getPassthroughPaths());
};
TemplateWriter.prototype.getGlobWatcherIgnores = function() {
// convert to format without ! since they are passed in as a separate argument to glob watcher
return this.cachedIgnores.map(ignore =>
TemplatePath.stripLeadingDotSlash(ignore.substr(1))
);
};
TemplateWriter.prototype.getIgnores = function() {
let files = [];
if (this.config.useGitIgnore) {
files = files.concat(
TemplateWriter.getFileIgnores(
this.inputDir + "/.gitignore",
"node_modules/"
)
);
}
files = files.concat(
TemplateWriter.getFileIgnores(this.inputDir + "/.eleventyignore")
);
files = files.concat(TemplateGlob.map("!" + this.outputDir + "/**"));
return files;
};
TemplateWriter.prototype.getPassthroughPaths = function() {
let paths = [];
paths = paths.concat(this.passthroughManager.getConfigPathGlobs());
// These are already added in the root templateGlobs
// paths = paths.concat(this.extensionMap.getPrunedGlobs(this.inputDir));
return paths;
};
TemplateWriter.prototype.getIncludesAndDataDirs = function() {
let files = [];
if (this.config.dir.includes) {
files = files.concat(TemplateGlob.map(this.includesDir + "/**"));
}
if (this.config.dir.data && this.config.dir.data !== ".") {
files = files.concat(TemplateGlob.map(this.dataDir + "/**"));
}
return files;
};
TemplateWriter.prototype.getTemplateIgnores = function() {
return this.getIncludesAndDataDirs().map(function(dir) {
return "!" + dir;
});
};
TemplateWriter.prototype._getAllPaths = async function() {
debug("Searching for: %o", this.templateGlobsWithIgnores);
if (!this.cachedPaths) {
this.cachedPaths = TemplatePath.addLeadingDotSlashArray(
await fastglob.async(this.templateGlobsWithIgnores)
);
}
return this.cachedPaths;
};
TemplateWriter.prototype._createTemplate = function(path) {
let tmpl = new Template(
path,
this.inputDir,
this.outputDir,
this.templateData
);
tmpl.setIsVerbose(this.isVerbose);
tmpl.setDryRun(this.isDryRun);
/*
* Sample filter: arg str, return pretty HTML string
* function(str) {
* return pretty(str, { ocd: true });
* }
*/
for (let filterName in this.config.filters) {
let filter = this.config.filters[filterName];
if (typeof filter === "function") {
tmpl.addTransform(filter);
}
}
return tmpl;
};
TemplateWriter.prototype._addToTemplateMap = async function(paths) {
let promises = [];
for (let path of paths) {
if (TemplateRender.hasEngine(path)) {
promises.push(
this.templateMap.add(this._createTemplate(path)).then(() => {
debug(`${path} added to map.`);
})
);
}
}
return Promise.all(promises);
};
TemplateWriter.prototype._createTemplateMap = async function(paths) {
this.templateMap = new TemplateMap();
await this._addToTemplateMap(paths);
await this.templateMap.cache();
debugDev("TemplateMap cache complete.");
return this.templateMap;
};
TemplateWriter.prototype._writeTemplate = async function(mapEntry) {
let tmpl = mapEntry.template;
try {
return tmpl.write(mapEntry.outputPath, mapEntry.data).then(() => {
this.writeCount += tmpl.getWriteCount();
});
} catch (e) {
throw EleventyError.make(
new Error(`Having trouble writing template: ${mapEntry.outputPath}`),
e
);
}
};
TemplateWriter.prototype.write = async function() {
let promises = [];
let paths = await this._getAllPaths();
debug("Found: %o", paths);
promises.push(this.passthroughManager.copyAll(paths));
// TODO optimize await here
await this._createTemplateMap(paths);
debug("Template map created.");
for (let mapEntry of this.templateMap.getMap()) {
promises.push(this._writeTemplate(mapEntry));
}
return Promise.all(promises);
};
TemplateWriter.prototype.setVerboseOutput = function(isVerbose) {
this.isVerbose = isVerbose;
};
TemplateWriter.prototype.setDryRun = function(isDryRun) {
this.isDryRun = !!isDryRun;
this.passthroughManager.setDryRun(this.isDryRun);
};
TemplateWriter.prototype.getCopyCount = function() {
return this.passthroughManager.getCopyCount();
};
TemplateWriter.prototype.getWriteCount = function() {
return this.writeCount;
};
module.exports = TemplateWriter;