createCacheKeyFunction.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. const crypto = require('crypto');
  9. const fs = require('fs');
  10. const path = require('path');
  11. function getGlobalCacheKey(files, values) {
  12. const presetVersion = require('../package').dependencies['babel-preset-fbjs'];
  13. const chunks = [
  14. process.env.NODE_ENV,
  15. process.env.BABEL_ENV,
  16. presetVersion,
  17. ...values,
  18. ...files.map(file => fs.readFileSync(file)),
  19. ];
  20. return chunks
  21. .reduce(
  22. (hash, chunk) => hash.update('\0', 'utf-8').update(chunk || ''),
  23. crypto.createHash('md5')
  24. )
  25. .digest('hex');
  26. }
  27. function getCacheKeyFunction(globalCacheKey) {
  28. return (src, file, configString, options) => {
  29. const {instrument, config} = options;
  30. const rootDir = config && config.rootDir;
  31. return crypto
  32. .createHash('md5')
  33. .update(globalCacheKey)
  34. .update('\0', 'utf8')
  35. .update(src)
  36. .update('\0', 'utf8')
  37. .update(rootDir ? path.relative(config.rootDir, file) : '')
  38. .update('\0', 'utf8')
  39. .update(instrument ? 'instrument' : '')
  40. .digest('hex');
  41. };
  42. }
  43. module.exports = (files = [], values = []) => {
  44. return getCacheKeyFunction(getGlobalCacheKey(files, values));
  45. };