-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (76 loc) · 2.26 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
var _ = require('lodash');
var path = require('path');
var through = require('through2');
module.exports = gulpClipper;
function gulpClipper(fileName, options){
fileName = fileName || 'gulpClips.js';
var clipper = new Clipper(options);
var latestFile;
function populateClips(file, encoding, cb){
latestFile=file;
if(file.clipped){
return cb();
}
file.clipped = true;
clipper.processString(''+file.contents);
return cb();
}
function endStream(cb){
if (!latestFile) {
return cb();
}
var joinedFile = latestFile.clone({contents: false});
joinedFile.path = path.join(latestFile.base, fileName);
var clipsJs = 'window.gulpClips = ' + JSON.stringify(clipper.getClips())+';';
joinedFile.contents = new Buffer(clipsJs);
this.length = 0;
this.push(joinedFile);
cb();
}
return through.obj(populateClips, endStream);
}
function Clipper(options){
_.defaults(this, {
clips: {},
activeClips: {},
startRe: /@gulpClipperStart:(.*):/,
stopRe: /@gulpClipperStop:(.*):/,
});
_.extend(this, options);
}
Clipper.prototype = {
processString: function(string){
_.each(string.split('\n'), (line)=>{
this.processLine(line);
});
this.clearActiveClips();
},
processLine: function(line){
this.removeActiveClips(line);
_.each(this.activeClips, (isActiveClip, clipTag)=>{
this.clips[clipTag] = this.clips[clipTag] || [];
this.clips[clipTag].push(line);
});
this.addActiveClips(line);
},
removeActiveClips: function(line){
var stopClippingKey = _.get(this.stopRe.exec(line), '1');
if(stopClippingKey){
delete this.activeClips[stopClippingKey];
}
},
addActiveClips: function(line){
var startClippingKey = _.get(this.startRe.exec(line), '1');
if(startClippingKey){
this.activeClips[startClippingKey] = true;
}
},
clearActiveClips: function(){
this.activeClips = {};
},
getClips: function(){
return _.mapValues(this.clips, function(value){
return value.join('\n')
});
}
}