-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (86 loc) · 2.95 KB
/
index.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
/* global Buffer */
/* global module */
/* global require */
'use strict';
const fs = require('fs');
const through = require('through2');
const PluginError = require('plugin-error');
const _ = require('lodash');
const PLUGIN_NAME = require('./package.json').name;
const getTemplateFileContent = (templateFile, callback) => {
if (templateFile && (typeof templateFile) === 'string') {
fs.readFile(templateFile, (err, data) => {
if (err) {
callback(err);
} else {
data = data.toString();
callback(null, data);
}
});
} else {
callback(new PluginError(PLUGIN_NAME, 'Template file does not exist.'));
}
};
module.exports = (templateFile, options, resultCallback) => {
return through.obj((file, enc, callback) => {
let contentName = 'content';
let defaultOptions = {};
if (file.isNull()) {
callback(null, file);
return;
}
if (file.isStream()) {
callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
return;
}
try {
if (options) {
if ((typeof options) === 'function') {
resultCallback = options;
options = null;
} else {
defaultOptions = JSON.parse(JSON.stringify(options));
}
}
} catch (e) {
callback(new PluginError(PLUGIN_NAME, e));
}
try {
if ((typeof templateFile) === 'function') {
const opt = templateFile(file);
if (opt) {
if (opt.options) {
defaultOptions = JSON.parse(JSON.stringify(opt.options));
}
templateFile = opt.template;
}
}
} catch (e) {
callback(new PluginError(PLUGIN_NAME, e));
}
if (defaultOptions && defaultOptions.contentName) {
contentName = defaultOptions.contentName;
delete defaultOptions.contentName;
}
getTemplateFileContent(templateFile, (err, result) => {
if (err) {
callback(err);
} else {
try {
if (!options) { options = defaultOptions; }
let content = file.contents.toString();
options[contentName] = content;
const tpl = _.template(result);
content = tpl(options);
if ((typeof resultCallback) === 'function') {
content = resultCallback(file, content, _);
}
file.contents = Buffer.from(content);
callback(null, file);
} catch (e) {
callback(new PluginError(PLUGIN_NAME, e.message));
}
}
});
});
};