Skip to content

Commit

Permalink
[jest-haste-map] Remove mapper option.
Browse files Browse the repository at this point in the history
  • Loading branch information
cpojer committed Feb 17, 2020
1 parent 63593a2 commit 550d6c1
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 117 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,7 @@

- `[jest-config]` Support ESM config files with `.js` extension ([#9573](https://github.com/facebook/jest/9573)).
- `[jest-runtime]` Override `module.createRequire` to return a Jest-compatible `require` function ([#9469](https://github.com/facebook/jest/pull/9469))
- `[jest-haste-map]` [**BREAKING**] Remove `mapper` option ([#9581](https://github.com/facebook/jest/pull/9581))
- `[*]` Support array of paths for `moduleNameMapper` aliases ([#9465](https://github.com/facebook/jest/pull/9465))
- `[jest-reporters]` Adds ability to pass options to the istanbul-reporter through `coverageReporters` ([#9572](https://github.com/facebook/jest/pull/9572))

Expand Down
1 change: 0 additions & 1 deletion packages/jest-haste-map/src/__tests__/index.test.js
Expand Up @@ -426,7 +426,6 @@ describe('HasteMap', () => {
const hasteMap = new HasteMap({
...defaultConfig,
computeSha1: true,
mapper: file => [file],
maxWorkers: 1,
useWatchman,
});
Expand Down
51 changes: 0 additions & 51 deletions packages/jest-haste-map/src/crawlers/__tests__/watchman.test.js
Expand Up @@ -44,7 +44,6 @@ const STRAWBERRY_RELATIVE = path.join(FRUITS_RELATIVE, 'strawberry.js');
const KIWI_RELATIVE = path.join(FRUITS_RELATIVE, 'kiwi.js');
const TOMATO_RELATIVE = path.join(FRUITS_RELATIVE, 'tomato.js');
const MELON_RELATIVE = path.join(VEGETABLES_RELATIVE, 'melon.json');
const DURIAN_RELATIVE = path.join(VEGETABLES_RELATIVE, 'durian.zip');

const WATCH_PROJECT_MOCK = {
[FRUITS]: {
Expand Down Expand Up @@ -174,56 +173,6 @@ describe('watchman watch', () => {
expect(client.end).toBeCalled();
}));

test('applies the mapper when needed', () => {
mockResponse = {
'list-capabilities': {
[undefined]: {
capabilities: ['field-content.sha1hex'],
},
},
query: {
[ROOT_MOCK]: {
clock: 'c:fake-clock:1',
files: [
{
exists: true,
mtime_ms: {toNumber: () => 33},
name: 'vegetables/durian.zip',
size: 43,
},
],
is_fresh_instance: true,
version: '4.5.0',
},
},
'watch-project': WATCH_PROJECT_MOCK,
};

return watchmanCrawl({
data: {
clocks: new Map(),
files: new Map(),
},
extensions: ['js', 'json', 'zip'],
ignore: pearMatcher,
mapper: n =>
n.endsWith('.zip')
? [path.join(n, 'foo.1.js'), path.join(n, 'foo.2.js')]
: null,
rootDir: ROOT_MOCK,
roots: ROOTS,
}).then(({changedFiles, hasteMap, removedFiles}) => {
expect(changedFiles).toEqual(undefined);
expect(hasteMap.files).toEqual(
createMap({
[path.join(DURIAN_RELATIVE, 'foo.1.js')]: ['', 33, 43, 0, '', null],
[path.join(DURIAN_RELATIVE, 'foo.2.js')]: ['', 33, 43, 0, '', null],
}),
);
expect(removedFiles).toEqual(new Map());
});
});

test('updates file map and removedFiles when the clock is given', () => {
mockResponse = {
'list-capabilities': {
Expand Down
29 changes: 7 additions & 22 deletions packages/jest-haste-map/src/crawlers/watchman.ts
Expand Up @@ -7,7 +7,7 @@

import * as path from 'path';
import watchman = require('fb-watchman');
import {Config} from '@jest/types';
import { Config } from '@jest/types';
import * as fastPath from '../lib/fast_path';
import normalizePathSep from '../lib/normalizePathSep';
import H from '../constants';
Expand Down Expand Up @@ -38,7 +38,7 @@ export = async function watchmanCrawl(
hasteMap: InternalHasteMap;
}> {
const fields = ['name', 'exists', 'mtime_ms', 'size'];
const {data, extensions, ignore, rootDir, roots} = options;
const { data, extensions, ignore, rootDir, roots } = options;
const defaultWatchExpression = [
'allof',
['type', 'f'],
Expand All @@ -59,7 +59,7 @@ export = async function watchmanCrawl(
);

if (options.computeSha1) {
const {capabilities} = await cmd('list-capabilities');
const { capabilities } = await cmd('list-capabilities');

if (capabilities.indexOf('field-content.sha1hex') !== -1) {
fields.push('content.sha1hex');
Expand Down Expand Up @@ -125,9 +125,9 @@ export = async function watchmanCrawl(
const relativeRoot = fastPath.relative(rootDir, root);
const query = clocks.has(relativeRoot)
? // Use the `since` generator if we have a clock available
{expression, fields, since: clocks.get(relativeRoot)}
{ expression, fields, since: clocks.get(relativeRoot) }
: // Otherwise use the `glob` filter
{expression, fields, glob};
{ expression, fields, glob };

const response = await cmd('query', root, query);

Expand Down Expand Up @@ -235,23 +235,8 @@ export = async function watchmanCrawl(
nextData = ['', mtime, size, 0, '', sha1hex];
}

const mappings = options.mapper ? options.mapper(filePath) : null;

if (mappings) {
for (const absoluteVirtualFilePath of mappings) {
if (!ignore(absoluteVirtualFilePath)) {
const relativeVirtualFilePath = fastPath.relative(
rootDir,
absoluteVirtualFilePath,
);
files.set(relativeVirtualFilePath, nextData);
changedFiles.set(relativeVirtualFilePath, nextData);
}
}
} else {
files.set(relativeFilePath, nextData);
changedFiles.set(relativeFilePath, nextData);
}
files.set(relativeFilePath, nextData);
changedFiles.set(relativeFilePath, nextData);
}
}
}
Expand Down
73 changes: 34 additions & 39 deletions packages/jest-haste-map/src/index.ts
Expand Up @@ -5,17 +5,17 @@
* LICENSE file in the root directory of this source tree.
*/

import {execSync} from 'child_process';
import {createHash} from 'crypto';
import {EventEmitter} from 'events';
import { execSync } from 'child_process';
import { createHash } from 'crypto';
import { EventEmitter } from 'events';
import * as fs from 'fs';
import {tmpdir} from 'os';
import { tmpdir } from 'os';
import * as path from 'path';
import {NodeWatcher, Watcher as SaneWatcher} from 'sane';
import {Config} from '@jest/types';
import { NodeWatcher, Watcher as SaneWatcher } from 'sane';
import { Config } from '@jest/types';
import serializer from 'jest-serializer';
import Worker from 'jest-worker';
import {getSha1, worker} from './worker';
import { getSha1, worker } from './worker';
import getMockName from './getMockName';
import getPlatformExtension from './lib/getPlatformExtension';
import H from './constants';
Expand All @@ -39,7 +39,6 @@ import {
HasteRegExp,
InternalHasteMap,
HasteMap as InternalHasteMapObject,
Mapper,
MockData,
ModuleMapData,
ModuleMetaData,
Expand All @@ -58,7 +57,6 @@ type Options = {
forceNodeFilesystemAPI?: boolean;
hasteImplModulePath?: string;
ignorePattern?: HasteRegExp;
mapper?: Mapper;
maxWorkers: number;
mocksPattern?: string;
name: string;
Expand All @@ -83,7 +81,6 @@ type InternalOptions = {
forceNodeFilesystemAPI: boolean;
hasteImplModulePath?: string;
ignorePattern?: HasteRegExp;
mapper?: Mapper;
maxWorkers: number;
mocksPattern: RegExp | null;
name: string;
Expand All @@ -102,7 +99,7 @@ type Watcher = {
close(callback: () => void): void;
};

type WorkerInterface = {worker: typeof worker; getSha1: typeof getSha1};
type WorkerInterface = { worker: typeof worker; getSha1: typeof getSha1 };

// TODO: Ditch namespace when this module exports ESM
namespace HasteMap {
Expand All @@ -120,13 +117,13 @@ const PACKAGE_JSON = path.sep + 'package.json';

// TypeScript doesn't like us importing from outside `rootDir`, but it doesn't
// understand `require`.
const {version: VERSION} = require('../package.json');
const { version: VERSION } = require('../package.json');

const canUseWatchman = ((): boolean => {
try {
execSync('watchman --version', {stdio: ['ignore']});
execSync('watchman --version', { stdio: ['ignore'] });
return true;
} catch (e) {}
} catch (e) { }
return false;
})();

Expand All @@ -140,12 +137,12 @@ const getWhiteList = (list: Array<string> | undefined): RegExp | null => {
);
return new RegExp(
'(' +
escapePathSeparator(NODE_MODULES) +
'(?:' +
newList.join('|') +
')(?=$|' +
escapePathSeparator(path.sep) +
'))',
escapePathSeparator(NODE_MODULES) +
'(?:' +
newList.join('|') +
')(?=$|' +
escapePathSeparator(path.sep) +
'))',
'g',
);
}
Expand Down Expand Up @@ -261,7 +258,6 @@ class HasteMap extends EventEmitter {
forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI,
hasteImplModulePath: options.hasteImplModulePath,
ignorePattern: options.ignorePattern,
mapper: options.mapper,
maxWorkers: options.maxWorkers,
mocksPattern: options.mocksPattern
? new RegExp(options.mocksPattern)
Expand All @@ -281,7 +277,7 @@ class HasteMap extends EventEmitter {
if (options.ignorePattern && !(options.ignorePattern instanceof RegExp)) {
this._console.warn(
'jest-haste-map: the `ignorePattern` options as a function is being ' +
'deprecated. Provide a RegExp instead. See https://github.com/facebook/jest/pull/4063.',
'deprecated. Provide a RegExp instead. See https://github.com/facebook/jest/pull/4063.',
);
}

Expand Down Expand Up @@ -437,7 +433,7 @@ class HasteMap extends EventEmitter {
map: ModuleMapData,
mocks: MockData,
filePath: Config.Path,
workerOptions?: {forceInBand: boolean},
workerOptions?: { forceInBand: boolean },
): Promise<void> | null {
const rootDir = this._options.rootDir;

Expand Down Expand Up @@ -651,7 +647,7 @@ class HasteMap extends EventEmitter {
changedFiles?: FileData;
hasteMap: InternalHasteMap;
}): Promise<InternalHasteMap> {
const {removedFiles, changedFiles, hasteMap} = data;
const { removedFiles, changedFiles, hasteMap } = data;

// If any files were removed or we did not track what files changed, process
// every file looking for changes. Otherwise, process only changed files.
Expand Down Expand Up @@ -727,10 +723,10 @@ class HasteMap extends EventEmitter {
/**
* Creates workers or parses files and extracts metadata in-process.
*/
private _getWorker(options?: {forceInBand: boolean}): WorkerInterface {
private _getWorker(options?: { forceInBand: boolean }): WorkerInterface {
if (!this._worker) {
if ((options && options.forceInBand) || this._options.maxWorkers <= 1) {
this._worker = {getSha1, worker};
this._worker = { getSha1, worker };
} else {
// @ts-ignore: assignment of a worker with custom properties.
this._worker = new Worker(require.resolve('./worker'), {
Expand All @@ -755,7 +751,6 @@ class HasteMap extends EventEmitter {
extensions: options.extensions,
forceNodeFilesystemAPI: options.forceNodeFilesystemAPI,
ignore,
mapper: options.mapper,
rootDir: options.rootDir,
roots: options.roots,
};
Expand All @@ -764,18 +759,18 @@ class HasteMap extends EventEmitter {
if (crawl === watchmanCrawl) {
this._console.warn(
`jest-haste-map: Watchman crawl failed. Retrying once with node ` +
`crawler.\n` +
` Usually this happens when watchman isn't running. Create an ` +
`empty \`.watchmanconfig\` file in your project's root folder or ` +
`initialize a git or hg repository in your project.\n` +
` ` +
error,
`crawler.\n` +
` Usually this happens when watchman isn't running. Create an ` +
`empty \`.watchmanconfig\` file in your project's root folder or ` +
`initialize a git or hg repository in your project.\n` +
` ` +
error,
);
return nodeCrawl(crawlerOptions).catch(e => {
throw new Error(
`Crawler retry failed:\n` +
` Original error: ${error.message}\n` +
` Retry error: ${e.message}\n`,
` Original error: ${error.message}\n` +
` Retry error: ${e.message}\n`,
);
});
}
Expand Down Expand Up @@ -808,8 +803,8 @@ class HasteMap extends EventEmitter {
canUseWatchman && this._options.useWatchman
? WatchmanWatcher
: FSEventsWatcher.isSupported()
? FSEventsWatcher
: NodeWatcher;
? FSEventsWatcher
: NodeWatcher;

const extensions = this._options.extensions;
const ignorePattern = this._options.ignorePattern;
Expand Down Expand Up @@ -907,7 +902,7 @@ class HasteMap extends EventEmitter {
}

const add = () => {
eventsQueue.push({filePath, stat, type});
eventsQueue.push({ filePath, stat, type });
return null;
};

Expand Down Expand Up @@ -967,7 +962,7 @@ class HasteMap extends EventEmitter {
hasteMap.map,
hasteMap.mocks,
filePath,
{forceInBand: true},
{ forceInBand: true },
);
// Cleanup
this._cleanup();
Expand Down
6 changes: 2 additions & 4 deletions packages/jest-haste-map/src/types.ts
Expand Up @@ -6,12 +6,11 @@
*/

import * as fs from 'fs';
import {Config} from '@jest/types';
import { Config } from '@jest/types';
import ModuleMap from './ModuleMap';
import HasteFS from './HasteFS';

export type IgnoreMatcher = (item: string) => boolean;
export type Mapper = (item: string) => Array<string> | null;

export type WorkerMessage = {
computeDependencies: boolean;
Expand All @@ -35,7 +34,6 @@ export type CrawlerOptions = {
extensions: Array<string>;
forceNodeFilesystemAPI: boolean;
ignore: IgnoreMatcher;
mapper?: Mapper | null;
rootDir: string;
roots: Array<string>;
};
Expand Down Expand Up @@ -84,7 +82,7 @@ export type RawModuleMap = {
mocks: MockData;
};

type ModuleMapItem = {[platform: string]: ModuleMetaData};
type ModuleMapItem = { [platform: string]: ModuleMetaData };
export type ModuleMetaData = [Config.Path, /* type */ number];

export type HType = {
Expand Down

0 comments on commit 550d6c1

Please sign in to comment.