forked from FrankFang/gulp-html-extend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
255 lines (206 loc) · 7.24 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
/* Created by frank on 14-7-24. */
/* jshint -W040:true */
'use strict';
var fs = require('fs')
var path = require('path')
var through2 = require('through2')
var gUtil = require('gulp-util')
var PluginError = gUtil.PluginError
var es = require('event-stream')
var extend = require('node.extend')
var pkg = require('./package.json')
var defaultOptions = {
annotations: true,
verbose: false
}
var noop = function () { }
var _options
var log = noop
module.exports = function (options) {
_options = extend({}, defaultOptions, options || {})
if (_options.verbose) {
log = gUtil.log
}
return through2.obj(function (file, enc, cb) {
if (file.isNull()) {
return cb(null, file)
}
if (file.isStream()) {
return cb(new PluginError(pkg.name, 'Streaming is not supported'))
}
if (file.isBuffer()) {
extendFile(file,_options, function (noMaster) {
return cb(null, file)
})
}
})
}
function makeFile(absolutePath, cb) {
if (cb) {
fs.readFile(absolutePath, function (error, data) {
if (error) { throw error }
var file = new gUtil.File({
base: path.dirname(absolutePath),
path: absolutePath,
contents: new Buffer(data),
})
cb(file)
})
} else {
return new gUtil.File({
base: path.dirname(absolutePath),
path: absolutePath,
contents: new Buffer(fs.readFileSync(absolutePath)),
})
}
}
function extendFile(file, options ,afterExtend) {
log('[going to extend]', file.path)
interpolateIncludedContent(file, options)
var master = findMaster(file.contents.toString('utf-8'))
if (!master) {
log('[no master]', file.path)
afterExtend()
return
}
var masterRelativePath = master.path
log('[find master path]' + masterRelativePath)
if (!masterRelativePath) {
afterExtend()
return
}
var masterAbsolute
if(options.root && isRelativeToRoot(masterRelativePath)){
masterAbsolute = path.join(process.cwd(), options.root, masterRelativePath)
}else{
masterAbsolute = path.join(path.dirname(file.path), masterRelativePath)
}
makeFile(masterAbsolute, function (masterFile) {
extendFile(masterFile, _options, function () {
var masterContent = masterFile.contents.toString()
var operatorRegEx = /(<!-- @@(?:(?:\n?.)*?)-->)/g
var masterContentCleared = masterContent.replace(operatorRegEx, function(operator){
return operator.replace(/\n/g, '');
})
var lines = splitByLine(masterContentCleared)
var newLines = lines.map(function (line, index, array) {
line = interpolateVariables(line, master.context)
var blockName = findPlaceholder(line)
if (blockName) {
var blockContent = getBlockContent(file.contents.toString(), blockName)
return blockContent || line
} else {
return line
}
})
var newContent = newLines.join('\n')
file.contents = new Buffer(newContent)
return afterExtend()
})
})
}
function interpolateIncludedContent(file, options) {
var fileContent = file.contents.toString()
var operatorRegEx = /(<!--\s*?@@(?:(?:\n?.)*?)-->)/g
var fileContentCleared = fileContent.replace(operatorRegEx, function(operator){
return operator.replace(/\n/g, '');
})
var fileLines = splitByLine(fileContentCleared)
var includedLines = fileLines.map(function (line) {
var include = findInclude(line)
if (include && include.path) {
var includeAbsolutePath
if(options.root && isRelativeToRoot(include.path)){
includeAbsolutePath = path.join(process.cwd(), options.root, include.path)
}else{
includeAbsolutePath = path.join(path.dirname(file.path), include.path)
}
log('[include]', includeAbsolutePath)
var includedFile = makeFile(includeAbsolutePath)
if (include.context) {
includedFile.contents = new Buffer(interpolateVariables(includedFile.contents.toString(),
include.context))
}
interpolateIncludedContent(includedFile, options)
if (_options.annotations) {
return [
'<!-- start ' + path.basename(includeAbsolutePath) + '-->',
includedFile.contents.toString(),
'<!-- end ' + path.basename(includeAbsolutePath) + '-->'
].join('\n')
} else {
return includedFile.contents.toString()
}
} else {
return line
}
})
file.contents = new Buffer(includedLines.join('\n'))
}
function findMaster(string) {
var regex = /<!--\s*@@master\s*[= ]\s*(\S+?)\s*(?:\s+(.+)\s*)?-->(?:\r\n|\n|\r|$)/
var match = string.match(regex)
return match ? {
path: match[1],
context: match[2] ? JSON.parse(match[2]) : null
} : null
}
function findInclude(string) {
var regex = /<!--\s*@@include\s*[= ]\s*(\S+?)\s*(?:\s+(.+)\s*)?-->(?:\r\n|\n|\r|$)/
var match = string.match(regex)
return match ? {
path: match[1],
context: match[2] ? JSON.parse(match[2]) : null
} : null
}
function findPlaceholder(string) {
var regex = /<!--\s*@@placeholder\s*[= ]\s*(\S+?)\s*-->/
var match = string.match(regex)
return match ? match[1] : null
}
function interpolateVariables(template, context) {
if (!context) { return template }
if (template.indexOf('@@var') < 0) { return template }
var regex = /<!--\s*@@var\s*[= ]\s*(\S+?)\s*(?:"([^"\\]*(?:\\.[^"\\]*)*)"\s*)?-->/
var match = regex.exec(template)
while (match) {
if (match[2] !== undefined) {
match[2] = match[2].replace(/\\"/g, '"');
}
template = template.replace(match[0], context[match[1]] || match[2] || '')
match = regex.exec(template)
}
return template
}
function getBlockContent(string, blockName) {
var result = ''
var lines = splitByLine(string)
var inBlock = false
var regex = new RegExp('<!--\\s*@@block\\s*[= ]\\s*' + blockName + '\\s*-->')
return [ _options.annotations ? '<!-- start ' + blockName + ' -->' : '',
lines.reduce(function (prev, current) {
if (inBlock) {
var matchEnd = /<!--\s*@@close\s*-->/.test(current)
if (matchEnd) {
inBlock = false
return prev
}
return prev + (prev === '' ? '' : '\n') + current
}
var matchBegin = regex.test(current)
if (matchBegin) {
inBlock = true
return prev
} else {
return prev
}
}, ''),
_options.annotations ? '\n<!-- end ' + blockName + ' -->' : ''
].join('\n')
}
function splitByLine(string) {
return string.split(/\r\n|\n|\r/)
}
function isRelativeToRoot(p){
return p.indexOf('/') === 0
}