UNPKG

2.34 kBJavaScriptView Raw
1'use strict';
2var helpers = require('broccoli-kitchen-sink-helpers');
3var crypto = require('crypto');
4var statPathsFor = require('./lib/stat-paths-for');
5var heimdall = require('heimdalljs');
6var Cache = require('./lib/cache');
7var cacheKey = require('./lib/cache-key');
8var logger = require('heimdalljs-logger')('hash-for-dep:');
9
10var CACHE = new Cache();
11
12function HashForDepSchema() {
13 this.paths = 0;
14}
15
16function cacheGet(key) {
17 return CACHE[key]
18}
19
20function cacheGet(key) {
21 return CACHE[key]
22}
23
24function cacheSet(key, value) {
25 CACHE[key] = value;
26 return value;
27}
28/* @public
29 *
30 * @method hashForDep
31 * @param {String} name name of the dependency
32 * @param {String} dir (optional) root dir to run the hash resolving from
33 * @param {String} _hashTreeOverride (optional) private, used internally for testing
34 * @param {Boolean} _skipCache (optional) intended to bypass cache
35 * @return {String} a hash representing the stats of this module and all its descendents
36 */
37module.exports = function hashForDep(name, dir, _hashTreeOverride, _skipCache) {
38 var skipCache = false;
39 var key, hash;
40
41 if (typeof _hashTreeOverride === 'function' || _skipCache === true) {
42 skipCache = true;
43 } else {
44 key = cacheKey(name, dir);
45 }
46
47 var heimdallNodeOptions = {
48 name: 'hashForDep(' + name + ')',
49 hashForDep: true,
50 dependencyName: name,
51 rootDir: dir,
52 skipCache: skipCache,
53 cacheKey: key
54 };
55
56 var heimdallNode = heimdall.start(heimdallNodeOptions, HashForDepSchema);
57
58 if (skipCache === false && CACHE.has(key)) {
59 logger.info('cache hit: %s', key);
60 hash = CACHE.get(key);
61 } else {
62 var start = Date.now();
63
64 var inputHashes = statPathsFor(name, dir).map(function(statPath) {
65 var hashFn = _hashTreeOverride || helpers.hashTree;
66
67 heimdallNode.stats.paths++;
68
69 return hashFn(statPath);
70 }).join(0x00);
71
72 hash = crypto.createHash('sha1').
73 update(inputHashes).digest('hex');
74
75 logger.info('cache miss: %s, paths: %d, took: %dms', key, heimdallNode.stats.paths, Date.now() - start);
76
77 if (skipCache === false) {
78 CACHE.set(key, hash);
79 }
80 }
81
82 heimdallNode.stop();
83 return hash;
84};
85
86module.exports._resetCache = function() {
87 CACHE = new Cache();
88};
89
90Object.defineProperty(module.exports, '_cache', {
91 get: function() {
92 return CACHE;
93 }
94});