|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. |
| 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 | + */ |
| 8 | + |
| 9 | +import {createHash} from 'crypto'; |
| 10 | +import {relative} from 'path'; |
| 11 | +/* eslint-disable-next-line no-restricted-imports */ |
| 12 | +import {readFileSync} from 'fs'; |
| 13 | +import type {Config} from '@jest/types'; |
| 14 | + |
| 15 | +type CacheKeyOptions = { |
| 16 | + config: Config.ProjectConfig; |
| 17 | + instrument: boolean; |
| 18 | +}; |
| 19 | + |
| 20 | +type GetCacheKeyFunction = ( |
| 21 | + fileData: string, |
| 22 | + filePath: Config.Path, |
| 23 | + configStr: string, |
| 24 | + options: CacheKeyOptions, |
| 25 | +) => string; |
| 26 | + |
| 27 | +function getGlobalCacheKey(files: Array<string>, values: Array<string>) { |
| 28 | + return [ |
| 29 | + process.env.NODE_ENV, |
| 30 | + process.env.BABEL_ENV, |
| 31 | + ...values, |
| 32 | + ...files.map((file: string) => readFileSync(file)), |
| 33 | + ] |
| 34 | + .reduce( |
| 35 | + (hash, chunk) => hash.update('\0', 'utf8').update(chunk || ''), |
| 36 | + createHash('md5'), |
| 37 | + ) |
| 38 | + .digest('hex'); |
| 39 | +} |
| 40 | + |
| 41 | +function getCacheKeyFunction(globalCacheKey: string): GetCacheKeyFunction { |
| 42 | + return (src, file, _configString, options) => { |
| 43 | + const {config, instrument} = options; |
| 44 | + return createHash('md5') |
| 45 | + .update(globalCacheKey) |
| 46 | + .update('\0', 'utf8') |
| 47 | + .update(src) |
| 48 | + .update('\0', 'utf8') |
| 49 | + .update(config.rootDir ? relative(config.rootDir, file) : '') |
| 50 | + .update('\0', 'utf8') |
| 51 | + .update(instrument ? 'instrument' : '') |
| 52 | + .digest('hex'); |
| 53 | + }; |
| 54 | +} |
| 55 | + |
| 56 | +export default ( |
| 57 | + files: Array<string> = [], |
| 58 | + values: Array<string> = [], |
| 59 | +): GetCacheKeyFunction => getCacheKeyFunction(getGlobalCacheKey(files, values)); |
0 commit comments