forked from gulp-community/gulp-header
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·103 lines (86 loc) · 2.47 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
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Module dependencies.
*/
const Concat = require('concat-with-sourcemaps');
const through = require('through2');
const simpleTemplate = (str, obj) => {
const replacer = (match, val) => val.split('.').reduce((acc, subVal) => acc && acc[subVal] || '', obj);
return str
.replace(/\${(.*?)}/g, replacer)
.replace(/<%=\s*(.*?)\s*%>/g, replacer)
}
;
const stream = require('stream');
const path = require('path');
/**
* gulp-header plugin
*/
module.exports = (headerText, data) => {
headerText = headerText || '';
function TransformStream(file, enc, cb) {
// format template
const filename = path.basename(file.path);
const template =
data === false
? headerText
: simpleTemplate(headerText,
Object.assign({}, file.data || {}, { file: file, filename: filename }, data)
);
if (file && typeof file === 'string') {
this.push(template + file);
return cb();
}
// if not an existing file, passthrough
if (!isExistingFile(file)) {
this.push(file);
return cb();
}
// handle file stream;
if (file.isStream()) {
const stream = through();
stream.write(Buffer.from(template));
stream.on('error', this.emit.bind(this, 'error'));
file.contents = file.contents.pipe(stream);
this.push(file);
return cb();
}
// variables to handle direct file content manipulation
const concat = new Concat(true, filename);
// add template
concat.add(null, Buffer.from(template));
// add sourcemap
concat.add(file.relative, file.contents, file.sourceMap);
// make sure streaming content is preserved
if (file.contents && !isStream(file.contents)) {
file.contents = concat.content;
}
// apply source map
if (concat.sourceMapping) {
file.sourceMap = JSON.parse(concat.sourceMap);
}
// make sure the file goes through the next gulp plugin
this.push(file);
// tell the stream engine that we are done with this file
cb();
}
return through.obj(TransformStream);
};
/**
* is stream?
*/
const isStream = obj => {
return obj instanceof stream.Stream;
};
/**
* Is File, and Exists
*/
const isExistingFile = file => {
try {
if (!(file && typeof file === 'object')) return false;
if (file.isDirectory()) return false;
if (file.isStream()) return true;
if (file.isBuffer()) return true;
if (typeof file.contents === 'string') return true;
} catch (err) {}
return false;
};