-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.js
106 lines (95 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
104
105
106
"use strict";
var crypto = require("crypto");
var PluginError = require("plugin-error");
var _ = require("lodash");
var mkdirp = require("mkdirp");
var slash = require("slash");
var through = require("through");
var Vinyl = require("vinyl");
var fs = require("fs");
var path = require("path");
var compareBuffer =
typeof Buffer.compare !== "undefined"
? Buffer.compare
: function(a, b) {
// Naive implementation of Buffer comparison for older
// Node versions. Doesn't follow the same spec as
// Buffer.compare, but we're only interested in equality.
if (a.length !== b.length) {
return -1;
}
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return -1;
}
}
return 0;
};
function hashsum(options) {
options = _.defaults(options || {}, {
dest: process.cwd(),
hash: "sha1",
force: false,
delimiter: " ",
json: false,
stream: false
});
options = _.defaults(options, {
filename: options.hash.toUpperCase() + "SUMS"
});
var hashesFilePath = path.resolve(options.dest, options.filename);
var hashes = {};
function processFile(file) {
if (file.isNull()) {
return;
}
if (file.isStream()) {
this.emit(
"error",
new PluginError("gulp-hashsum", "Streams not supported")
);
return;
}
var filePath = path.resolve(options.dest, file.path);
hashes[
slash(path.relative(path.dirname(hashesFilePath), filePath))
] = crypto
.createHash(options.hash)
.update(file.contents, "binary")
.digest("hex");
this.push(file);
}
function writeSums() {
var contents;
if (options.json) {
contents = JSON.stringify(hashes);
} else {
var lines = _.keys(hashes)
.sort()
.map(function(key) {
return hashes[key] + options.delimiter + key + "\n";
});
contents = lines.join("");
}
var data = new Buffer(contents);
if (options.stream) {
this.emit(
"data",
new Vinyl({
path: hashesFilePath,
contents: data
})
);
} else if (
options.force ||
!fs.existsSync(hashesFilePath) ||
compareBuffer(fs.readFileSync(hashesFilePath), data) !== 0
) {
mkdirp(path.dirname(hashesFilePath));
fs.writeFileSync(hashesFilePath, data);
}
this.emit("end");
}
return through(processFile, writeSums);
}
module.exports = hashsum;