Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: make sure to call realpath when accessing cwd #7613

Merged
merged 2 commits into from
Jan 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions packages/babel-jest/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@ import {transformSync as babelTransform, loadPartialConfig} from '@babel/core';
const THIS_FILE = fs.readFileSync(__filename);
const jestPresetPath = require.resolve('babel-preset-jest');
const babelIstanbulPlugin = require.resolve('babel-plugin-istanbul');
const cwd = process.cwd();

const createTransformer = (options: any): Transformer => {
// Allow incoming options to override `cwd`
options = Object.assign({cwd}, options, {
options = {
...options,
caller: {
name: 'babel-jest',
supportsStaticESM: false,
Expand All @@ -36,20 +35,24 @@ const createTransformer = (options: any): Transformer => {
plugins: (options && options.plugins) || [],
presets: ((options && options.presets) || []).concat(jestPresetPath),
sourceMaps: 'both',
});
};

delete options.cacheDirectory;
delete options.filename;

const loadBabelConfig = (cwd, filename) =>
// `cwd` first to allow incoming options to override it
loadPartialConfig({cwd, ...options, filename});

return {
canInstrument: true,
getCacheKey(
fileData: string,
filename: Path,
configString: string,
{instrument, rootDir}: CacheKeyOptions,
{config, instrument, rootDir}: {config: ProjectConfig} & CacheKeyOptions,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

): string {
const babelOptions = loadPartialConfig({...options, filename});
const babelOptions = loadBabelConfig(config.cwd, filename);
const configPath = [
babelOptions.config || '',
babelOptions.babelrc || '',
Expand Down Expand Up @@ -82,9 +85,7 @@ const createTransformer = (options: any): Transformer => {
config: ProjectConfig,
transformOptions?: TransformOptions,
): string | TransformedSource {
const babelOptions = {
...loadPartialConfig({...options, filename}).options,
};
const babelOptions = {...loadBabelConfig(config.cwd, filename).options};

if (transformOptions && transformOptions.instrument) {
babelOptions.auxiliaryCommentBefore = ' istanbul ignore next ';
Expand Down
6 changes: 4 additions & 2 deletions packages/jest-cli/src/SearchSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ export default class SearchSource {
tests: toTests(
this._context,
paths
.map(p => path.resolve(process.cwd(), p))
.map(p => path.resolve(this._context.config.cwd, p))
.filter(this.isTestFilePath.bind(this)),
),
};
Expand All @@ -197,7 +197,9 @@ export default class SearchSource {
collectCoverage: boolean,
): SearchResult {
if (Array.isArray(paths) && paths.length) {
const resolvedPaths = paths.map(p => path.resolve(process.cwd(), p));
const resolvedPaths = paths.map(p =>
path.resolve(this._context.config.cwd, p),
);
return this.findRelatedTests(new Set(resolvedPaths), collectCoverage);
}
return {tests: []};
Expand Down
19 changes: 16 additions & 3 deletions packages/jest-cli/src/getNoTestFound.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import type {GlobalConfig} from 'types/Config';
import type {TestRunData} from 'types/TestRunner';

import chalk from 'chalk';
import pluralize from './pluralize';

export default function getNoTestFound(testRunData, globalConfig): string {
export default function getNoTestFound(
testRunData: TestRunData,
globalConfig: GlobalConfig,
): string {
const testFiles = testRunData.reduce(
(current, testRun) => current + testRun.matches.total || 0,
0,
Expand All @@ -25,7 +38,7 @@ export default function getNoTestFound(testRunData, globalConfig): string {
'\n' +
'Run with `--passWithNoTests` to exit with code 0' +
'\n' +
`In ${chalk.bold(process.cwd())}` +
`In ${chalk.bold(globalConfig.rootDir)}` +
'\n' +
` ${pluralize('file', testFiles, 's')} checked across ${pluralize(
'project',
Expand Down
16 changes: 13 additions & 3 deletions packages/jest-cli/src/getNoTestsFoundMessage.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import type {GlobalConfig} from 'types/Config';
import type {TestRunData} from 'types/TestRunner';

import getNoTestFound from './getNoTestFound';
import getNoTestFoundRelatedToChangedFiles from './getNoTestFoundRelatedToChangedFiles';
import getNoTestFoundVerbose from './getNoTestFoundVerbose';
import getNoTestFoundFailed from './getNoTestFoundFailed';

export default function getNoTestsFoundMessage(
testRunData,
globalConfig,
testRunData: TestRunData,
globalConfig: GlobalConfig,
): string {
if (globalConfig.onlyFailures) {
return getNoTestFoundFailed();
Expand Down
3 changes: 2 additions & 1 deletion packages/jest-cli/src/lib/init/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import chalk from 'chalk';
import fs from 'fs';
import path from 'path';
import prompts from 'prompts';
import {sync as realpath} from 'realpath-native';
import defaultQuestions, {testScriptQuestion} from './questions';
import {NotFoundPackageJsonError, MalformedPackageJsonError} from './errors';
import {PACKAGE_JSON, JEST_CONFIG} from '../../constants';
Expand All @@ -24,7 +25,7 @@ type PromptsResults = {
scripts: boolean,
};

export default async (rootDir: string = process.cwd()) => {
export default async (rootDir: string = realpath(process.cwd())) => {
// prerequisite checks
const projectPackageJsonPath: string = path.join(rootDir, PACKAGE_JSON);
const jestConfigPath: string = path.join(rootDir, JEST_CONFIG);
Expand Down
20 changes: 8 additions & 12 deletions packages/jest-cli/src/runJest.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ import type {Context} from 'types/Context';
import type {ChangedFilesPromise} from 'types/ChangedFiles';
import type {GlobalConfig} from 'types/Config';
import type {AggregatedResult} from 'types/TestResult';
import type {TestRunData} from 'types/TestRunner';
import type {JestHookEmitter} from 'types/JestHooks';
import type TestWatcher from './TestWatcher';

import micromatch from 'micromatch';
import chalk from 'chalk';
import path from 'path';
import {sync as realpath} from 'realpath-native';
import {Console, formatTestResults} from 'jest-util';
import exit from 'exit';
import fs from 'graceful-fs';
Expand Down Expand Up @@ -62,10 +64,7 @@ const getTestPaths = async (

const filteredTests = data.tests.filter((test, i) => shouldTestArray[i]);

return Object.assign({}, data, {
allTests: filteredTests.length,
tests: filteredTests,
});
return {...data, allTests: filteredTests.length, tests: filteredTests};
};

const processResults = (runResults, options) => {
Expand All @@ -90,12 +89,12 @@ const processResults = (runResults, options) => {
}
if (isJSON) {
if (outputFile) {
const filePath = path.resolve(process.cwd(), outputFile);
SimenB marked this conversation as resolved.
Show resolved Hide resolved
const cwd = realpath(process.cwd());
const filePath = path.resolve(cwd, outputFile);

fs.writeFileSync(filePath, JSON.stringify(formatTestResults(runResults)));
outputStream.write(
`Test results written to: ` +
`${path.relative(process.cwd(), filePath)}\n`,
`Test results written to: ${path.relative(cwd, filePath)}\n`,
);
} else {
process.stdout.write(JSON.stringify(formatTestResults(runResults)));
Expand Down Expand Up @@ -150,7 +149,7 @@ export default (async function runJest({

let collectCoverageFrom = [];

const testRunData = await Promise.all(
const testRunData: TestRunData = await Promise.all(
contexts.map(async context => {
const matches = await getTestPaths(
globalConfig,
Expand Down Expand Up @@ -242,10 +241,7 @@ export default (async function runJest({
globalConfig.silent !== true &&
globalConfig.verbose !== false
) {
// $FlowFixMe Object.assign
const newConfig: GlobalConfig = Object.assign({}, globalConfig, {
verbose: true,
});
const newConfig: GlobalConfig = {...globalConfig, verbose: true};
globalConfig = Object.freeze(newConfig);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/jest-resolve/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import type {ModuleMap} from 'types/HasteMap';
import type {ResolveModuleConfig} from 'types/Resolve';
import type {ErrorWithCode} from 'types/Errors';

import fs from 'fs';
import path from 'path';
import {sync as realpath} from 'realpath-native';
import nodeModulesPaths from './nodeModulesPaths';
import isBuiltinModule from './isBuiltinModule';
import defaultResolver from './defaultResolver';
Expand Down Expand Up @@ -53,7 +53,7 @@ const NATIVE_PLATFORM = 'native';

// We might be inside a symlink.
const cwd = process.cwd();
const resolvedCwd = fs.realpathSync(cwd) || cwd;
const resolvedCwd = realpath(cwd) || cwd;
const nodePaths = process.env.NODE_PATH
? process.env.NODE_PATH.split(path.delimiter)
.filter(Boolean)
Expand Down
3 changes: 2 additions & 1 deletion packages/jest-runtime/src/cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {EnvironmentClass} from 'types/Environment';
import chalk from 'chalk';
import os from 'os';
import path from 'path';
import {sync as realpath} from 'realpath-native';
import yargs from 'yargs';
import {Console, setGlobal} from 'jest-util';
import {validateCLIOptions} from 'jest-validate';
Expand Down Expand Up @@ -59,7 +60,7 @@ export function run(cliArgv?: Argv, cliInfo?: Array<string>) {
return;
}

const root = process.cwd();
const root = realpath(process.cwd());
const filePath = path.resolve(root, argv._[0]);

if (argv.debug) {
Expand Down
5 changes: 5 additions & 0 deletions types/TestRunner.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,8 @@ export type TestFramework = (
export type TestRunnerOptions = {
serial: boolean,
};

export type TestRunData = Array<{
context: Context,
matches: {allTests: number, tests: Array<Test>, total: number},
}>;
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4503,7 +4503,7 @@ diacritics-map@^0.1.0:
resolved "https://registry.yarnpkg.com/diacritics-map/-/diacritics-map-0.1.0.tgz#6dfc0ff9d01000a2edf2865371cac316e94977af"
integrity sha1-bfwP+dAQAKLt8oZTccrDFulJd68=

[email protected], diff@^3.2.0:
[email protected]:
version "3.5.0"
resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12"
integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==
Expand Down