-
Notifications
You must be signed in to change notification settings - Fork 0
/
hl2.js
115 lines (87 loc) · 2.69 KB
/
hl2.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
'use strict';
var fs = require('fs');
var path = require('path');
var _ = require('highland');
const STRING_NEW_LINE = '\n';
const STRING_EMPTY = '';
const RE_INCLUDE = /include\s*\(\s*["']([^"']+)["']\s*\)\s*;/g;
function Wrapper(begin, end) {
var isStarted = false;
return _.pipeline(
_.consume(function (err, chunk, push, next) {
if (err) {
push(err);
next();
return;
}
if (chunk === _.nil) {
push(null, end)
push(null, _.nil);
return;
}
if (!isStarted) {
push(null, begin)
isStarted = true;
}
push(null, chunk);
next();
})
)
}
function BaseIncludes(_options) {
var options = _options || {};
var cache = [STRING_EMPTY];
var stream = create();
stream.regExp = RE_INCLUDE;
stream.cwd = options.cwd || process.cwd();
function create() {
return _.pipeline(
_.map(split),
_.append(cache),
_.flatten
);
}
function split(chunk) {
var content = cache.pop() + chunk;
var splitted = [];
var carret = 0;
var parsed;
while ((parsed = stream.regExp.exec(content)) !== null) {
if (carret !== parsed.index) {
splitted.push(content.substring(carret, parsed.index));
}
splitted.push(stream.createReadStream(stream.normalizeParsed(parsed)));
carret = stream.regExp.lastIndex;
}
cache.push(carret ? content.substring(carret) : content);
return splitted;
}
stream.normalizeParsed = function (parsed) {
var absolute = path.resolve(stream.cwd, parsed[1]);
return {
path: absolute,
dirname: path.dirname(absolute),
relative: path.relative(stream.cwd, absolute)
}
}
stream.wrapTempalte = function (path, position) {
return `/* ${path}: ${position} */ /**/` + STRING_NEW_LINE;
}
stream.createReadStream = function (options) {
var wrapBegin = stream.wrapTempalte(options.relative, 'begin');
var wrapEnd = stream.wrapTempalte(options.relative, 'end');
return fs
.createReadStream(options.path)
.pipe(BaseIncludes({
cwd: options.dirname,
}))
.pipe(Wrapper(wrapBegin, wrapEnd));
}
return stream;
}
console.time('x');
fs
.createReadStream(__dirname + '/../demo/1.js')
.pipe(BaseIncludes({cwd: __dirname + '/../demo/'}))
.on('end', () => console.timeEnd('x'))
.pipe(process.stdout);