ronantakizawa/codereview-bench huggingface dataset:
Repository: facebook/jest
File: packages/create-jest/src/runCreate.ts (TypeScript)

Code before:

  if (!fs.existsSync(projectPackageJsonPath)) {
    throw new NotFoundPackageJsonError(rootDir);
  }

  const questions = defaultQuestions.slice(0);
  let hasJestProperty = false;
  let projectPackageJson: ProjectPackageJson;

  try {
    projectPackageJson = JSON.parse(
      fs.readFileSync(projectPackageJsonPath, 'utf-8'),
    ) as ProjectPackageJson;
  } catch {
    throw new MalformedPackageJsonError(projectPackageJsonPath);
  }

  if (projectPackageJson.jest) {
    hasJestProperty = true;
  }

  const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext =>
    fs.existsSync(path.join(rootDir, getConfigFilename(ext))),
  );

  if (hasJestProperty || Boolean(existingJestConfigExt)) {
    const result: {continue: boolean} = await prompts({
      initial: true,
      message:
        'It seems that you already have a jest configuration, do you want to override it?',
      name: 'continue',
      type: 'confirm',
    });

    if (!result.continue) {
      console.log();
      console.log('Aborting...');
      return;
    }
  }

  // Add test script installation only if needed
  if (
    !projectPackageJson.scripts ||
    projectPackageJson.scripts.test !== 'jest'
  ) {
    questions.unshift(testScriptQuestion);
  }

  // Start the init process
  console.log();

Review comment (suggestion):
```suggestion
  if (hasJestProperty || existingJestConfigExt != null) {
```

Code after:
    ) as ProjectPackageJson;
  } catch {
    throw new MalformedPackageJsonError(projectPackageJsonPath);
  }

  if (projectPackageJson.jest) {
    hasJestProperty = true;
  }

  const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext =>
    fs.existsSync(path.join(rootDir, getConfigFilename(ext))),
  );

  if (hasJestProperty || existingJestConfigExt != null) {
    const result: {continue: boolean} = await prompts({
      initial: true,
      message:
        'It seems that you already have a jest configuration, do you want to override it?',
      name: 'continue',
      type: 'confirm',
    });

    if (!result.continue) {
      console.log();
      console.log('Aborting...');
      return;
    }
  }

  // Add test script installation only if needed
  if (
    !projectPackageJson.scripts ||
    projectPackageJson.scripts.test !== 'jest'
  ) {
    questions.unshift(testScriptQuestion);
  }

  // Start the init process
  console.log();
  console.log(
    chalk.underline(
      'The following questions will help Jest to create a suitable configuration for your project\n',
    ),
  );

  let promptAborted = false;

  const results = (await prompts(questions, {
    onCancel: () => {
      promptAborted = true;
    },
Repository: facebook/jest
File: packages/create-jest/src/runCreate.ts (TypeScript)

Code before:
  );

  let promptAborted = false;

  const results = (await prompts(questions, {
    onCancel: () => {
      promptAborted = true;
    },
  })) as PromptsResults;

  if (promptAborted) {
    console.log();
    console.log('Aborting...');
    return;
  }

  // Determine if Jest should use JS or TS for the config file
  const jestConfigFileExt = results.useTypescript
    ? JEST_CONFIG_EXT_TS
    : projectPackageJson.type === 'module'
    ? JEST_CONFIG_EXT_MJS
    : JEST_CONFIG_EXT_JS;

  // Determine Jest config path
  const jestConfigPath =
    typeof existingJestConfigExt !== 'undefined'
      ? getConfigFilename(existingJestConfigExt)
      : path.join(rootDir, getConfigFilename(jestConfigFileExt));

  const shouldModifyScripts = results.scripts;

  if (shouldModifyScripts || hasJestProperty) {
    const modifiedPackageJson = modifyPackageJson({
      projectPackageJson,
      shouldModifyScripts,
    });

    fs.writeFileSync(projectPackageJsonPath, modifiedPackageJson);

    console.log('');
    console.log(`✏️  Modified ${chalk.cyan(projectPackageJsonPath)}`);
  }

  const generatedConfig = generateConfigFile(
    results,
    projectPackageJson.type === 'module' ||
      jestConfigPath.endsWith(JEST_CONFIG_EXT_MJS),
  );

  fs.writeFileSync(jestConfigPath, generatedConfig);


Review comment (suggestion):
```suggestion
    existingJestConfigExt != null
```

Code after:
    console.log('Aborting...');
    return;
  }

  // Determine if Jest should use JS or TS for the config file
  const jestConfigFileExt = results.useTypescript
    ? JEST_CONFIG_EXT_TS
    : projectPackageJson.type === 'module'
    ? JEST_CONFIG_EXT_MJS
    : JEST_CONFIG_EXT_JS;

  // Determine Jest config path
  const jestConfigPath =
    existingJestConfigExt != null
      ? getConfigFilename(existingJestConfigExt)
      : path.join(rootDir, getConfigFilename(jestConfigFileExt));

  const shouldModifyScripts = results.scripts;

  if (shouldModifyScripts || hasJestProperty) {
    const modifiedPackageJson = modifyPackageJson({
      projectPackageJson,
      shouldModifyScripts,
    });

    fs.writeFileSync(projectPackageJsonPath, modifiedPackageJson);

    console.log('');
    console.log(`✏️  Modified ${chalk.cyan(projectPackageJsonPath)}`);
  }

  const generatedConfig = generateConfigFile(
    results,
    projectPackageJson.type === 'module' ||
      jestConfigPath.endsWith(JEST_CONFIG_EXT_MJS),
  );

  fs.writeFileSync(jestConfigPath, generatedConfig);

  console.log('');
  console.log(
    `📝  Configuration file created at ${chalk.cyan(jestConfigPath)}`,
  );
}
Repository: facebook/jest
File: packages/create-jest/src/runCreate.ts (TypeScript)

Code before:
      .epilogue('Documentation: https://jestjs.io/').argv;

    const rootDir =
      typeof argv._[0] !== 'undefined' ? String(argv._[0]) : undefined;

    await runCreate(rootDir);
  } catch (error: unknown) {
    clearLine(process.stderr);
    clearLine(process.stdout);
    if (error instanceof Error && Boolean(error?.stack)) {
      console.error(chalk.red(error.stack));
    } else {
      console.error(chalk.red(error));
    }

    exit(1);
    throw error;
  }
}

export async function runCreate(
  rootDir: string = process.cwd(),
): Promise<void> {
  rootDir = tryRealpath(rootDir);
  // prerequisite checks
  const projectPackageJsonPath: string = path.join(rootDir, PACKAGE_JSON);

  if (!fs.existsSync(projectPackageJsonPath)) {
    throw new NotFoundPackageJsonError(rootDir);
  }

  const questions = defaultQuestions.slice(0);
  let hasJestProperty = false;
  let projectPackageJson: ProjectPackageJson;

  try {
    projectPackageJson = JSON.parse(
      fs.readFileSync(projectPackageJsonPath, 'utf-8'),
    ) as ProjectPackageJson;
  } catch {
    throw new MalformedPackageJsonError(projectPackageJsonPath);
  }

  if (projectPackageJson.jest) {
    hasJestProperty = true;
  }

  const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext =>
    fs.existsSync(path.join(rootDir, getConfigFilename(ext))),
  );


Review comment (suggestion):
Interesting why ESLint did not catch this:

```suggestion
  const projectPackageJsonPath = path.join(rootDir, PACKAGE_JSON);
```

Code after:
      console.error(chalk.red(error.stack));
    } else {
      console.error(chalk.red(error));
    }

    exit(1);
    throw error;
  }
}

export async function runCreate(rootDir = process.cwd()): Promise<void> {
  rootDir = tryRealpath(rootDir);
  // prerequisite checks
  const projectPackageJsonPath = path.join(rootDir, PACKAGE_JSON);

  if (!fs.existsSync(projectPackageJsonPath)) {
    throw new NotFoundPackageJsonError(rootDir);
  }

  const questions = defaultQuestions.slice(0);
  let hasJestProperty = false;
  let projectPackageJson: ProjectPackageJson;

  try {
    projectPackageJson = JSON.parse(
      fs.readFileSync(projectPackageJsonPath, 'utf-8'),
    ) as ProjectPackageJson;
  } catch {
    throw new MalformedPackageJsonError(projectPackageJsonPath);
  }

  if (projectPackageJson.jest) {
    hasJestProperty = true;
  }

  const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext =>
    fs.existsSync(path.join(rootDir, getConfigFilename(ext))),
  );

  if (hasJestProperty || existingJestConfigExt != null) {
    const result: {continue: boolean} = await prompts({
      initial: true,
      message:
        'It seems that you already have a jest configuration, do you want to override it?',
      name: 'continue',
      type: 'confirm',
    });

    if (!result.continue) {
      console.log();
      console.log('Aborting...');
Repository: facebook/jest
File: packages/create-jest/src/runCreate.ts (TypeScript)

Code before:
      .usage('Usage: $0 [rootDir]')
      .version(getVersion())
      .alias('help', 'h')
      .epilogue('Documentation: https://jestjs.io/').argv;

    const rootDir =
      typeof argv._[0] !== 'undefined' ? String(argv._[0]) : undefined;

    await runCreate(rootDir);
  } catch (error: unknown) {
    clearLine(process.stderr);
    clearLine(process.stdout);
    if (error instanceof Error && Boolean(error?.stack)) {
      console.error(chalk.red(error.stack));
    } else {
      console.error(chalk.red(error));
    }

    exit(1);
    throw error;
  }
}

export async function runCreate(
  rootDir: string = process.cwd(),
): Promise<void> {
  rootDir = tryRealpath(rootDir);
  // prerequisite checks
  const projectPackageJsonPath: string = path.join(rootDir, PACKAGE_JSON);

  if (!fs.existsSync(projectPackageJsonPath)) {
    throw new NotFoundPackageJsonError(rootDir);
  }

  const questions = defaultQuestions.slice(0);
  let hasJestProperty = false;
  let projectPackageJson: ProjectPackageJson;

  try {
    projectPackageJson = JSON.parse(
      fs.readFileSync(projectPackageJsonPath, 'utf-8'),
    ) as ProjectPackageJson;
  } catch {
    throw new MalformedPackageJsonError(projectPackageJsonPath);
  }

  if (projectPackageJson.jest) {
    hasJestProperty = true;
  }

  const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext =>

Review comment (suggestion):
```suggestion
export async function runCreate(rootDir = process.cwd()): Promise<void> {
```

Code after:
    clearLine(process.stderr);
    clearLine(process.stdout);
    if (error instanceof Error && Boolean(error?.stack)) {
      console.error(chalk.red(error.stack));
    } else {
      console.error(chalk.red(error));
    }

    exit(1);
    throw error;
  }
}

export async function runCreate(rootDir = process.cwd()): Promise<void> {
  rootDir = tryRealpath(rootDir);
  // prerequisite checks
  const projectPackageJsonPath = path.join(rootDir, PACKAGE_JSON);

  if (!fs.existsSync(projectPackageJsonPath)) {
    throw new NotFoundPackageJsonError(rootDir);
  }

  const questions = defaultQuestions.slice(0);
  let hasJestProperty = false;
  let projectPackageJson: ProjectPackageJson;

  try {
    projectPackageJson = JSON.parse(
      fs.readFileSync(projectPackageJsonPath, 'utf-8'),
    ) as ProjectPackageJson;
  } catch {
    throw new MalformedPackageJsonError(projectPackageJsonPath);
  }

  if (projectPackageJson.jest) {
    hasJestProperty = true;
  }

  const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext =>
    fs.existsSync(path.join(rootDir, getConfigFilename(ext))),
  );

  if (hasJestProperty || existingJestConfigExt != null) {
    const result: {continue: boolean} = await prompts({
      initial: true,
      message:
        'It seems that you already have a jest configuration, do you want to override it?',
      name: 'continue',
      type: 'confirm',
    });
Repository: facebook/jest
File: packages/create-jest/src/runCreate.ts (TypeScript)

Code before:
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as path from 'path';
import chalk = require('chalk');
import exit = require('exit');
import * as fs from 'graceful-fs';
import prompts = require('prompts');
import yargs = require('yargs');
import {getVersion} from '@jest/core';
import {constants} from 'jest-config';
import {clearLine, tryRealpath} from 'jest-util';
import {MalformedPackageJsonError, NotFoundPackageJsonError} from './errors';
import generateConfigFile from './generateConfigFile';
import modifyPackageJson from './modifyPackageJson';
import defaultQuestions, {testScriptQuestion} from './questions';
import type {ProjectPackageJson, PromptsResults} from './types';

const {
  JEST_CONFIG_BASE_NAME,
  JEST_CONFIG_EXT_MJS,
  JEST_CONFIG_EXT_JS,
  JEST_CONFIG_EXT_TS,
  JEST_CONFIG_EXT_ORDER,
  PACKAGE_JSON,
} = constants;

const getConfigFilename = (ext: string) => JEST_CONFIG_BASE_NAME + ext;

export async function runCLI(): Promise<void> {
  try {
    const argv = await yargs(process.argv.slice(2))
      .usage('Usage: $0 [rootDir]')
      .version(getVersion())
      .alias('help', 'h')

Review comment (suggestion):
Importing `@jest/core` will ship almost the whole Jest with `create-jest`. Not sure if that is worth.

Code after:
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as path from 'path';
import chalk = require('chalk');
import exit = require('exit');
import * as fs from 'graceful-fs';
import prompts = require('prompts');
import {constants} from 'jest-config';
import {clearLine, tryRealpath} from 'jest-util';
import {MalformedPackageJsonError, NotFoundPackageJsonError} from './errors';
import generateConfigFile from './generateConfigFile';
import modifyPackageJson from './modifyPackageJson';
import defaultQuestions, {testScriptQuestion} from './questions';
import type {ProjectPackageJson, PromptsResults} from './types';

const {
  JEST_CONFIG_BASE_NAME,
  JEST_CONFIG_EXT_MJS,
  JEST_CONFIG_EXT_JS,
  JEST_CONFIG_EXT_TS,
  JEST_CONFIG_EXT_ORDER,
  PACKAGE_JSON,
} = constants;

const getConfigFilename = (ext: string) => JEST_CONFIG_BASE_NAME + ext;

export async function runCLI(): Promise<void> {
  try {
    const rootDir = process.argv[2];
    await runCreate(rootDir);
  } catch (error: unknown) {
    clearLine(process.stderr);
    clearLine(process.stdout);
    if (error instanceof Error && Boolean(error?.stack)) {
Repository: facebook/jest
File: packages/create-jest/src/generateConfigFile.ts (TypeScript)

Code before:
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import type {Config} from '@jest/types';
import {defaults, descriptions} from 'jest-config';
import type {PromptsResults} from './types';

const stringifyOption = (
  option: keyof Config.InitialOptions,
  map: Partial<Config.InitialOptions>,
  linePrefix = '',
): string => {
  const optionDescription = `  // ${descriptions[option] ?? ''}`;
  const stringifiedObject = `${option}: ${JSON.stringify(
    map[option],
    null,
    2,
  )}`;

  return `${optionDescription}\n${stringifiedObject
    .split('\n')
    .map(line => `  ${linePrefix}${line}`)
    .join('\n')},`;
};

const generateConfigFile = (
  results: PromptsResults,
  generateEsm = false,
): string => {
  const {useTypescript, coverage, coverageProvider, clearMocks, environment} =
    results;

  const overrides: Record<string, unknown> = {};

  if (coverage) {
    Object.assign(overrides, {
      collectCoverage: true,
      coverageDirectory: 'coverage',

Review comment (suggestion):
```suggestion
  const optionDescription = descriptions[option] ? `  // ${descriptions[option]}` : '';
```

Code after:
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import type {Config} from '@jest/types';
import {defaults, descriptions} from 'jest-config';
import type {PromptsResults} from './types';

const stringifyOption = (
  option: keyof Config.InitialOptions,
  map: Partial<Config.InitialOptions>,
  linePrefix = '',
): string => {
  const description = descriptions[option];
  const optionDescription =
    description != null && description.length > 0 ? `  // ${description}` : '';
  const stringifiedObject = `${option}: ${JSON.stringify(
    map[option],
    null,
    2,
  )}`;

  return `${optionDescription}\n${stringifiedObject
    .split('\n')
    .map(line => `  ${linePrefix}${line}`)
    .join('\n')},`;
};

const generateConfigFile = (
  results: PromptsResults,
  generateEsm = false,
): string => {
  const {useTypescript, coverage, coverageProvider, clearMocks, environment} =
    results;

  const overrides: Record<string, unknown> = {};

  if (coverage) {
    Object.assign(overrides, {
Repository: facebook/jest
File: packages/jest-core/src/lib/activeFiltersMessage.ts (TypeScript)

Code before:
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import chalk = require('chalk');
import type {Config} from '@jest/types';

const activeFilters = (globalConfig: Config.GlobalConfig): string => {
  const {testNamePattern, testPathPattern} = globalConfig;
  if (testNamePattern || testPathPattern) {
    const filters = [
      testPathPattern
        ? chalk.dim('filename ') + chalk.yellow(`/${testPathPattern}/`)
        : null,
      testNamePattern
        ? chalk.dim('test name ') + chalk.yellow(`/${testNamePattern}/`)
        : null,
    ]
      .filter(Boolean)
      .join(', ');

    const messages = `\n${chalk.bold('Active Filters: ')}${filters}`;

    return messages;
  }

  return '';
};

export default activeFilters;


Review comment (suggestion):
could use https://github.com/jestjs/jest/blob/edeecfae240bfd54b33f3c9eae156bd157447e5a/packages/jest-util/src/index.ts#L32

Code after:
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import chalk = require('chalk');
import type {Config} from '@jest/types';
import {isNonNullable} from 'jest-util';

const activeFilters = (globalConfig: Config.GlobalConfig): string => {
  const {testNamePattern, testPathPattern} = globalConfig;
  if (testNamePattern || testPathPattern) {
    const filters = [
      testPathPattern
        ? chalk.dim('filename ') + chalk.yellow(`/${testPathPattern}/`)
        : null,
      testNamePattern
        ? chalk.dim('test name ') + chalk.yellow(`/${testNamePattern}/`)
        : null,
    ]
      .filter(isNonNullable)
      .join(', ');

    const messages = `\n${chalk.bold('Active Filters: ')}${filters}`;

    return messages;
  }

  return '';
};

export default activeFilters;
Repository: facebook/jest
File: packages/jest-test-sequencer/src/__tests__/test_sequencer.test.ts (TypeScript)

Code before:

const secondContext: TestContext = {
  config: makeProjectConfig({
    cache: true,
    cacheDirectory: '/cache2',
    haste: {},
    id: 'test2',
  }),
  hasteFS: {
    getSize: path => path.length,
  },
};

const toTests = (paths: Array<string>) =>
  paths.map<Test>(path => ({
    context,
    duration: undefined,
    path,
  }));

beforeEach(() => {
  jest.clearAllMocks();
  sequencer = new TestSequencer({
    contexts: [],
    globalConfig: {} as Config.GlobalConfig,
  });
});

test('sorts by file size if there is no timing information', () => {
  expect(sequencer.sort(toTests(['/test-a.js', '/test-ab.js']))).toEqual([
    {context, duration: undefined, path: '/test-ab.js'},
    {context, duration: undefined, path: '/test-a.js'},
  ]);
});

test('sorts based on timing information', () => {
  fs.readFileSync.mockImplementationOnce(() =>
    JSON.stringify({
      '/test-a.js': [SUCCESS, 5],
      '/test-ab.js': [SUCCESS, 3],
    }),
  );
  expect(sequencer.sort(toTests(['/test-a.js', '/test-ab.js']))).toEqual([
    {context, duration: 5, path: '/test-a.js'},
    {context, duration: 3, path: '/test-ab.js'},
  ]);
});

test('sorts based on failures and timing information', () => {
  fs.readFileSync.mockImplementationOnce(() =>
    JSON.stringify({

Review comment (suggestion):
Not sure if this is ideal, but since the Jest `TestSequencer` doesn't use either contexts, or globalConfig, it should be fine to have stand ins here, for now.

Alternatively we could make `TestSequencerOptions` optional, or even properly create contexts and globalConfig in the beforeEach.

lmk what you think.

Code after:
const secondContext: TestContext = {
  config: makeProjectConfig({
    cache: true,
    cacheDirectory: '/cache2',
    haste: {},
    id: 'test2',
  }),
  hasteFS: {
    getSize: path => path.length,
  },
};

const toTests = (paths: Array<string>) =>
  paths.map<Test>(path => ({
    context,
    duration: undefined,
    path,
  }));

beforeEach(() => {
  jest.clearAllMocks();
  sequencer = new TestSequencer();
});

test('sorts by file size if there is no timing information', () => {
  expect(sequencer.sort(toTests(['/test-a.js', '/test-ab.js']))).toEqual([
    {context, duration: undefined, path: '/test-ab.js'},
    {context, duration: undefined, path: '/test-a.js'},
  ]);
});

test('sorts based on timing information', () => {
  fs.readFileSync.mockImplementationOnce(() =>
    JSON.stringify({
      '/test-a.js': [SUCCESS, 5],
      '/test-ab.js': [SUCCESS, 3],
    }),
  );
  expect(sequencer.sort(toTests(['/test-a.js', '/test-ab.js']))).toEqual([
    {context, duration: 5, path: '/test-a.js'},
    {context, duration: 3, path: '/test-ab.js'},
  ]);
});

test('sorts based on failures and timing information', () => {
  fs.readFileSync.mockImplementationOnce(() =>
    JSON.stringify({
      '/test-a.js': [SUCCESS, 5],
      '/test-ab.js': [FAIL, 0],
      '/test-c.js': [FAIL, 6],
      '/test-d.js': [SUCCESS, 2],