UNPKG

2.45 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.checksumPattern = exports.checksumFile = exports.makeHash = void 0;
4const tslib_1 = require("tslib");
5const fslib_1 = require("@yarnpkg/fslib");
6const crypto_1 = require("crypto");
7const globby_1 = tslib_1.__importDefault(require("globby"));
8function makeHash(...args) {
9 const hash = crypto_1.createHash(`sha512`);
10 for (const arg of args)
11 hash.update(arg ? arg : ``);
12 return hash.digest(`hex`);
13}
14exports.makeHash = makeHash;
15function checksumFile(path) {
16 return new Promise((resolve, reject) => {
17 const hash = crypto_1.createHash(`sha512`);
18 const stream = fslib_1.xfs.createReadStream(path);
19 stream.on(`data`, chunk => {
20 hash.update(chunk);
21 });
22 stream.on(`error`, error => {
23 reject(error);
24 });
25 stream.on(`end`, () => {
26 resolve(hash.digest(`hex`));
27 });
28 });
29}
30exports.checksumFile = checksumFile;
31async function checksumPattern(pattern, { cwd }) {
32 // Note: We use a two-pass glob instead of using the expandDirectories option
33 // from globby, because the native implementation is broken.
34 //
35 // Ref: https://github.com/sindresorhus/globby/issues/147
36 const dirListing = await globby_1.default(pattern, {
37 cwd: fslib_1.npath.fromPortablePath(cwd),
38 expandDirectories: false,
39 onlyDirectories: true,
40 unique: true,
41 });
42 const dirPatterns = dirListing.map(entry => {
43 return `${entry}/**/*`;
44 });
45 const listing = await globby_1.default([pattern, ...dirPatterns], {
46 cwd: fslib_1.npath.fromPortablePath(cwd),
47 expandDirectories: false,
48 onlyFiles: false,
49 unique: true,
50 });
51 listing.sort();
52 const hashes = await Promise.all(listing.map(async (entry) => {
53 const parts = [Buffer.from(entry)];
54 const p = fslib_1.npath.toPortablePath(entry);
55 const stat = await fslib_1.xfs.lstatPromise(p);
56 if (stat.isSymbolicLink())
57 parts.push(Buffer.from(await fslib_1.xfs.readlinkPromise(p)));
58 else if (stat.isFile())
59 parts.push(await fslib_1.xfs.readFilePromise(p));
60 return parts.join(`\u0000`);
61 }));
62 const hash = crypto_1.createHash(`sha512`);
63 for (const sub of hashes)
64 hash.update(sub);
65 return hash.digest(`hex`);
66}
67exports.checksumPattern = checksumPattern;