-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.js
52 lines (45 loc) · 1.46 KB
/
utils.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
const crypto = require("crypto");
const path = require("path");
/*
a function to get hash value for an given content with desired string length.
input: ('a{}', 'sha', 10) output: a1b2c3d4e5
*/
function hash(css, algorithm, trim) {
return crypto
.createHash(algorithm)
.update(css)
.digest("hex")
.substr(0, trim);
}
function defaultName(parts) {
return path.join(parts.dir, parts.name + "." + parts.hash + parts.ext);
}
/*
a function to rename a filename by appending hash value.
input: ('./file.css', 'a {}', {algorithm: 'sha256', trim: 10}) output: ./file.a1b2c3d4e5.css
*/
function rename(file, css, opts) {
return opts.name({
dir: path.dirname(file),
name: path.basename(file, path.extname(file)),
ext: path.extname(file),
hash: hash(css, opts.algorithm, opts.trim)
});
}
/*
will return an object of {oldname: newname} to append/update into manifest file.
input: ('./css/file.css', './file.a1b2c3d4e5.css') output: {"file.css": "file.a1b2c3d4e5.css"}
*/
function data(originalName, hashedName, opts) {
var key = path.parse(originalName).base;
var value = path.parse(hashedName).base;
return opts.updateEntry(key, value);
}
function updateEntry(originalName, hashedName) {
return { [originalName]: hashedName };
}
module.exports.hash = hash;
module.exports.rename = rename;
module.exports.defaultName = defaultName;
module.exports.data = data;
module.exports.updateEntry = updateEntry;