-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
83 lines (68 loc) · 2.42 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
'use strict';
var path = require('path');
var rework = require('rework');
var url = require('rework-plugin-url');
var through = require('through2');
var mkpath = require('mkpath');
var fs = require('fs');
var merge = require('merge');
var md5 = require('md5');
var fileExists = require('file-exists');
module.exports = function (opt) {
var options = merge({
output_assets: null,
output_css: null,
exclude: [],
overwrite: false
}, opt);
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
return;
}
if (file.isStream()) {
return this.emit('error', PluginError('gulp-css-rebase', 'Streaming not supported')); // eslint-disable-line
}
var adjusted = adjust(file);
file.contents = new Buffer(adjusted);
cb(null, file);
});
function adjust(file) {
var css = file.contents.toString();
return rework(css)
.use(url(function (url) {
if (!/^(data|\/|\w+:\/\/)/.test(url)) {
var assetPath = path.join(path.dirname(file.path), url);
var assetFolder = md5(path.relative(process.cwd(), path.dirname(assetPath)));
var IsExclude = false;
for (var index in options.exclude) {
if (options.exclude[index] === assetPath.substr(0, options.exclude[index].length)) {
IsExclude = true;
break;
}
}
var newPath = !IsExclude
? path.normalize(path.join(options.output_assets, assetFolder, path.basename(assetPath)))
: path.normalize(assetPath)
;
if (
(!IsExclude && !fileExists(newPath))
||
(!IsExclude && options.overwrite)
) {
mkpath(path.dirname(newPath), function (err) {
if (err) {
throw err;
}
fs
.createReadStream(assetPath.replace(/[\#|\?].*$/, ''))
.pipe(fs.createWriteStream(newPath.replace(/[\#|\?].*$/, '')))
;
});
}
url = path.relative(options.output_css, newPath);
}
return url;
}))
.toString();
}
};