-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
117 lines (94 loc) · 3.37 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
'use strict';
import { Transform } from 'stream';
import path from 'path';
import Twig from 'twig';
import PluginError from 'plugin-error';
const PLUGIN_NAME = 'gulp5-twig';
function replaceExt(nPath, ext) {
if (typeof nPath !== 'string' || nPath.length === 0) {
return nPath;
}
const nFileName = `${path.basename(nPath, path.extname(nPath))}${ext}`;
const nFilepath = path.join(path.dirname(nPath), nFileName);
// Handle the case when the path starts with './'.
if (nPath.startsWith(`.${path.sep}`) || nPath.startsWith('./')) {
return `.${path.sep}${nFilepath}`;
}
return nFilepath;
}
export default function(options) {
return new Transform({
objectMode: true,
async transform(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
return callback(new PluginError(PLUGIN_NAME, 'Streaming not supported!'));
}
const {
changeExt = true,
extname = '.html',
useFileContents = false,
twigParameters = {},
data: optionsData,
cache,
functions,
filters,
extend,
errorLogToConsole = false, // The default value is set.
onError,
} = options || {};
const data = file.data || optionsData || {};
const keepExtension = changeExt === false || extname === true;
const target = {
path: keepExtension ? file.path : replaceExt(file.path, extname || ''),
relative: keepExtension ? file.relative : replaceExt(file.relative, extname || ''),
};
try {
const { twig } = Twig;
if (cache !== true) {
Twig.cache(false);
}
if (functions) {
functions.forEach(func => {
Twig.extendFunction(func.name, func.func);
});
}
if (filters) {
filters.forEach(filter => {
Twig.extendFilter(filter.name, filter.func);
});
}
if (extend) {
Twig.extend(extend);
}
const template = twig({
...twigParameters,
rethrow: true,
async: false,
path: file.path,
data: useFileContents ? file.contents.toString() : undefined,
});
file.contents = Buffer.from(
template.render({
...data,
_target: target,
_file: file,
}),
);
file.path = target.path;
callback(null, file);
} catch (error) {
if (errorLogToConsole) {
console.error(`${PLUGIN_NAME}: ${error.message}`);
}
if (typeof onError === 'function') {
onError(error);
return callback();
}
callback(new PluginError(PLUGIN_NAME, error));
}
},
});
}