-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
83 lines (64 loc) · 2.2 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
// by Yair-Even-Or
// v1.0.1
var through2 = require('through2'),
gutil = require('gulp-util'),
path = require('path'),
File = require('vinyl');
var PLUGIN_NAME = 'gulp-file-contents-to-keys',
files = {},
outputFile = null,
options = {
name : 'var templates',
folderDelimiter : '|',
removeFileTypes : true,
};
function parseFileName( file ){
var name = file.path.replace(file.base, '');
if( options.removeFileTypes )
name = name.split('.').slice(0, -1).join('.'); // trim file type (no ".html" for example)
return name;
}
function parseFileContent( file ){
var contents = file.contents.toString("utf-8");
if( options.minify )
contents = contents.replace( /\s[\r\n ]+/g, '' ) // remove new lines
.replace(/>\s+</g, "><"); // remove whitespaces between tags
return contents;
}
/**
* Iterates on each file in the stream
*/
function iterateFile( file, enc, callback ){
outputFile = outputFile || file;
var fileName = parseFileName(file),
path = files; // path.relative(file.base, file.path);
filePathArr = fileName.split('\\');
filePathArr.forEach((v, i) => {
// last part is the file name itself and not a path
if( i == filePathArr.length - 1 )
path[v] = parseFileContent(file);
else if( v in path )
path = path[v];
else
path = path[v] = {};
})
callback();
}
/**
* Push the end result of the files iteration back to the stream
*/
function iterationResult( callback ){
outputFile = outputFile ? outputFile.clone() : new File();
// if the user wants to concatenate all the files into one
if( options.fileName )
outputFile.path = path.resolve(outputFile.base, options.fileName);
outputFile.contents = new Buffer(
options.name + ' = ' + JSON.stringify(files, null, 4) + ';'
);
this.push(outputFile);
callback();
}
module.exports = function( userOptions ){
options = Object.assign(options, userOptions);
return through2.obj(iterateFile, iterationResult);
};