-
Notifications
You must be signed in to change notification settings - Fork 95
/
index.js
283 lines (240 loc) · 8.28 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
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
'use strict'
const replaceOperator = require('./replace-operator')
const replaceFunction = require('./replace-function')
const replaceVariable = require('./replace-variable')
const concat = require('concat-stream')
const setIndent = require('./indent')
const through = require('through2')
const Vinyl = require('vinyl')
const PluginError = require('plugin-error')
const extend = require('extend')
const path = require('path')
const fs = require('fs')
module.exports = function(opts) {
if (typeof opts === 'string') {
opts = {prefix: opts}
}
opts = extend({}, {
basepath: '@file',
prefix: '@@',
suffix: '',
context: {},
filters: false,
indent: false
}, opts)
if (opts.basepath !== '@file') {
opts.basepath = opts.basepath === '@root' ? process.cwd() : path.resolve(opts.basepath)
}
var customWebRoot = !!opts.context.webRoot
function fileInclude(file, enc, cb) {
if (!customWebRoot) {
// built-in webRoot variable, example usage: <link rel=stylesheet href=@@webRoot/style.css>
opts.context.webRoot =
path.relative(path.dirname(file.path), file.base).replace(/\\/g, '/') || '.'
}
if (file.isNull()) {
cb(null, file)
} else if (file.isStream()) {
file.contents.pipe(concat(function(data) {
try {
data = include(file, String(data))
cb(null, data)
} catch (e) {
cb(new PluginError('gulp-file-include', e.message))
}
}))
} else if (file.isBuffer()) {
try {
file = include(file, String(file.contents))
cb(null, file)
} catch (e) {
cb(new PluginError('gulp-file-include', e.message))
}
}
}
return through.obj(fileInclude)
/**
* utils
*/
function stripCommentedIncludes(content, opts) {
// remove single line html comments that use the format: <!-- @@include() -->
var regex = new RegExp('<!--(.*)' + opts.prefix + '[ ]*include([\\s\\S]*?)[ ]*' + opts.suffix + '-->', 'g')
return content.replace(regex, '')
}
function include(file, text, data) {
var filebase = opts.basepath === '@file' ? path.dirname(file.path) : opts.basepath
var currentFilename = path.resolve(file.base, file.path)
data = extend(true, {}, opts.context, data || {})
data.content = text
text = stripCommentedIncludes(text, opts)
text = replaceOperator(text, {
prefix: opts.prefix,
suffix: opts.suffix,
name: 'if',
handler: conditionalHandler
})
text = replaceOperator(text, {
prefix: opts.prefix,
suffix: opts.suffix,
name: 'for',
handler: forHandler
})
text = replaceVariable(text, data, opts)
text = replaceFunction(text, {
prefix: opts.prefix,
suffix: opts.suffix,
name: 'include',
handler: includeHandler
})
text = replaceFunction(text, {
prefix: opts.prefix,
suffix: opts.suffix,
name: 'loop',
handler: loopHandler
})
function conditionalHandler(inst) {
try {
var condition = new Function('var context = this; with (context) { return ' + inst.args + '; }').call(data) // eslint-disable-line
} catch (error) {
throw new Error(error.message + ': ' + inst.args)
}
return condition ? inst.body : ''
}
function forHandler(inst) {
var forLoop = 'for' + inst.args + ' { result+=`' + inst.body + '`; }'
var condition = 'var context = this; with (context) { var result=""; ' + forLoop + ' return result; }'
try {
var result = new Function(condition).call(data) // eslint-disable-line
} catch (error) {
throw new Error(error.message + ': ' + forLoop)
}
return result
}
function includeHandler(inst) {
var args = /^['|"]([^'|"]*)['|"](,\s*({[\s\S]*}|['|"]([^'|"]*)['|"]|\s*)|)/.exec(inst.args)
if (args) {
var includePath = path.resolve(filebase, args[1])
// for checking if we are not including the current file again
if (currentFilename.toLowerCase() === includePath.toLowerCase()) {
throw new Error('recursion detected in file: ' + currentFilename)
}
var includeContent = fs.readFileSync(includePath, 'utf-8')
if (opts.indent) {
includeContent = setIndent(inst.before, inst.before.length, includeContent)
}
// need to double each `$` to escape it in the `replace` function
// includeContent = includeContent.replace(/\$/gi, '$$$$');
// apply filters on include content
if (typeof opts.filters === 'object') {
includeContent = applyFilters(includeContent, args.input)
}
var recFile = new Vinyl({
cwd: process.cwd(),
base: file.base,
path: includePath,
contents: Buffer.from(includeContent)
})
var data = {};
if(args[4]){
var jsonfile = file.base + args[4];
if (fs.existsSync(jsonfile)) {
data = require(jsonfile)
} else {
return console.error('JSON file not exists:', jsonfile)
}
}else if(args[3]) {
data = JSON.parse(args[3]);
}
recFile = include(recFile, includeContent, data)
return String(recFile.contents)
}
}
function loopHandler(inst) {
var args = /[^)"']*["']([^"']*)["'](,\s*([\s\S]*())){0,1}\s*/.exec(inst.args)
var arr = []
if (args) {
// loop array in the json file
if (args[3].match(/^('|")[^']|[^"]('|")$/)) {
// clean filename var and define path
var jsonfile = file.base + args[3].replace(/^('|")/, '').replace(/('|")$/, '')
// check if json file exists
if (fs.existsSync(jsonfile)) {
arr = require(jsonfile)
} else {
return console.error('JSON file not exists:', jsonfile)
}
} else {
// loop array in the function
try {
arr = JSON.parse(args[3])
} catch (err) {
return console.error(err, args[3])
}
}
if (arr) {
var includePath = path.resolve(filebase, args[1])
// for checking if we are not including the current file again
if (currentFilename.toLowerCase() === includePath.toLowerCase()) {
throw new Error('recursion detected in file: ' + currentFilename)
}
var includeContent = fs.readFileSync(includePath, 'utf-8')
if (opts.indent) {
includeContent = setIndent(inst.before, inst.before.length, includeContent)
}
// apply filters on include content
if (typeof opts.filters === 'object') {
includeContent = applyFilters(includeContent, args.input)
}
var recFile = new Vinyl({
cwd: process.cwd(),
base: file.base,
path: includePath,
contents: Buffer.from(includeContent)
})
var contents = ''
for (var i in arr) {
if (arr.hasOwnProperty(i)) {
var context = arr[i]
recFile = include(recFile, includeContent, args[3] ? context : {})
// why handler dont reconize underscore?
// if (typeof context == 'object' && typeof context['_key'] == 'undefined') {
// context['_key'] = i;
// }
contents += String(recFile.contents)
}
}
}
return contents
}
}
file.contents = Buffer.from(text)
return file
}
function applyFilters(includeContent, match) {
if (!match.match(/\)+$/)) {
// nothing to filter return unchanged
return includeContent
}
// now get the ordered list of filters
var filterlist = match.split('(').slice(0, -1)
filterlist = filterlist.map(function(str) {
return opts.filters[str.trim()]
})
// compose them together into one function
var filter = filterlist.reduce(compose)
// check match for filter options object
var options = match.match('{([^}]*)}')
// and apply the composed function to the stringified content
if (options) {
options = JSON.parse(options[0])
return filter(String(includeContent), options)
} else {
return filter(String(includeContent))
}
}
}
function compose(f, g) {
return function(x) {
return f(g(x))
}
}