-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (79 loc) · 2.64 KB
/
Copy pathindex.js
File metadata and controls
92 lines (79 loc) · 2.64 KB
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
// Dependencies
const fs = require('fs');
const through = require('through2');
const path = require('path');
const md5 = require('md5');
const chalk = require('chalk');
const assetCache = {
cacheFile: {},
currentCache: {},
cacheName: false,
filter(cacheName) {
// Set default cache if not specified
assetCache.cacheName = cacheName || './.asset-cache';
// Try to load an existing cache file
try {
assetCache.cacheFile = JSON.parse(fs.readFileSync(assetCache.cacheName));
} catch (err) {
assetCache.cacheFile = {};
}
/**
* Update the current cache and filter out cached files
* @param {object} file - A vinyl file
* @param {string} encoding - Encoding
* @param {function} cb - Callback
*/
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
return cb();
}
if (file.isStream()) {
this.emit('error', new Error('Streaming not supported in gulp-asset-cache'));
return cb();
}
if (file.isBuffer()) {
const relativePath = path.relative(process.cwd(), `${path.dirname(file.path)}/${path.basename(file.path)}`);
const hash = md5(relativePath + file.stat.size);
// Update cache object
assetCache.currentCache[relativePath] = hash;
if (assetCache.cacheFile[relativePath] === assetCache.currentCache[relativePath]) {
console.log(`gulp-asset-cache: ${chalk.green('✔')} ${relativePath} ${chalk.grey('(cached)')}`);
} else {
console.log(`gulp-asset-cache: ${chalk.red('✖')} ${relativePath} ${chalk.grey('(uncached)')}`);
this.push(file);
}
}
return cb();
});
},
cache() {
/**
* Update the current with changed files
* @param {object} file - A vinyl file
* @param {string} encoding - Encoding
* @param {function} cb - Callback
*/
function transform(file, enc, cb) {
const self = this;
const relativePath = path.relative(process.cwd(), `${path.dirname(file.path)}/${path.basename(file.path)}`);
fs.stat(file.path, function callback(err, stats) {
if (err) this.emit('error', new Error(err));
// Update Cache
const hash = md5(relativePath + stats.size);
assetCache.currentCache[relativePath] = hash;
self.push(file);
return cb();
});
}
/**
* Flush updated cache file to disk
* @param {function} cb - Callback
*/
function flush(cb) {
fs.writeFile(assetCache.cacheName, JSON.stringify(assetCache.currentCache, null, 4), cb);
}
return through.obj(transform, flush);
}
};
// Exports
module.exports = assetCache;