-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
79 lines (67 loc) · 2.51 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
/*
gulp-imports
Author: Jim Cowart (http://freshbrewedcode.com/jimcowart)
License: MIT (http://www.opensource.org/licenses/mit-license)
Version 0.0.3 (really, it should be 0.0.0.0.0.0.2)
*/
/*global require, module, Buffer */
var fs = require( 'fs' );
var path = require( 'path' );
var evs = require( 'event-stream' );
var g_util = require( 'gulp-util' );
// TODO: adjust these to be more forgiving with whitespace....
var patterns = {
html: /([<][!][-]{2}).?import[(]?.?["'](.*)["'].?[)]?.?[-]{2}[>]/g,
js: /([\/]{2}|[\/][*]).?import.?[(]?.?["'](.*)["'].?[)]?[;]?.*?(\n[*][\/])?/g,
css: /([\/]{2}|[\/][*]).?import[(]?.?["'](.*)["'].?[)]?([*][\/])?/g,
yaml: /([ \t]*)[-][ ]?import[:][ ]*["'](.*)["']/g,
yml: /([ \t]*)[-][ ]?import[:][ ]*["'](.*)["']/g,
json: /([ \t]*)[-][ ]?import[:][ ]*["'](.*)["']/g
};
var getExtension = function( p ) {
return path.extname( p ).substr( 1 ).toLowerCase();
};
function getImport( ext, contents, dirname ) {
patterns[ ext ].lastIndex = 0; // OH lastIndex - how I HATE you.
var match = patterns[ ext ].exec( contents );
return match ? {
matchText: match[ 0 ],
index: match.index,
path: path.join( dirname, match[ 2 ] )
} : undefined;
}
function processMatch( _import, contents ) {
return contents.substring( 0, _import.index ) +
processFile(
_import.path,
String( fs.readFileSync( _import.path ) )
) +
contents.substring( _import.index + _import.matchText.length );
}
function processFile( p, contents ) {
var ext = getExtension( p );
var processed = contents,
_import;
while (_import = getImport( ext, processed, path.dirname( p ) )) {
processed = processMatch( _import, processed );
}
return processed;
}
module.exports = function() {
function processImports( file ) {
var contents = String( file.contents );
var ext = getExtension( file.path );
// I'm no stream guru - so I have no idea if this can be done.....yet....
if ( file.isStream() ) {
this.emit( 'error', new g_util.PluginError( 'gulp-imports', 'Yikes - sorry about this, but streams are not supported yet.' ) );
}
if ( patterns.hasOwnProperty( ext ) ) {
if ( file.isBuffer() ) {
contents = processFile( file.path, contents );
file.contents = new Buffer( contents );
}
}
this.emit( 'data', file );
}
return evs.through( processImports );
};