Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
106 lines (84 loc) · 1.97 KB
/
Copy pathindex.js
File metadata and controls
106 lines (84 loc) · 1.97 KB
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
/**
* @author Fernando Salazar <fernando@blufish.com>
* @author James Gov <james@blufish.com>
* @since Tuesday, September 07, 2016
*/
"use strict";
var through = require('through2'),
concat = require('concat-stream'),
gUtil = require('gulp-util'),
fs = require('fs');
module.exports = function(opts) {
var _pattr = '%%path:',
_regex = /%%path:\w+/g,
_depthLimit = 60,
_depthCount = 0,
_matchCount = 0,
_parsedCount = 0;
/**
* @param object file, string encoding, function cb
* @return void
*/
function fresh(file, encoding, cb) {
switch(true) {
/**
* Pass along null file.
*/
case file.isNull():
cb(null, file);
break;
/**
* @todo support stream
*/
case file.isStream():
file.contents.pipe(concat(function(data) {
try {
file.contents = new Buffer(_parse(String(data)));
cb(null, file);
} catch(e) {
cb(new gUtil.PluginError('gulp-fresh', e.message));
}
}));
break;
/**
* Process file
*/
case file.isBuffer():
try {
file.contents = new Buffer(_parse(String(file.contents)));
cb(null, file);
} catch (e) {
cb(new gUtil.PluginError('gulp-fresh', e.message));
}
break;
}
}
/**
* @param string content, function handle
* @return string
*/
function _parse(content) {
var matches = content.match(_regex),
i, key;
_depthCount ++;
if(_depthCount >= _depthLimit)
throw new Error('Depth Limit Reached');
if(matches === null) {
return content;
} else {
for(i = 0; i < matches.length; i++) {
_matchCount ++;
key = matches[i].replace(_pattr, '');
if(typeof opts[key] === 'undefined') {
throw new Error('Path Key Not Found: ' + key);
} else {
_parsedCount ++;
content = content.replace(matches[i], fs.readFileSync(opts[key], 'utf-8'));
if(_matchCount >= _parsedCount)
return _parse(content);
}
}
}
}
return through.obj(fresh);
}