Skip to content

Commit

Permalink
Enforce _foo.default || _foo to import lib files in tests (#14673)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Jun 19, 2022
1 parent a32306d commit f0ec180
Show file tree
Hide file tree
Showing 50 changed files with 154 additions and 64 deletions.
1 change: 1 addition & 0 deletions .eslintrc.cjs
Expand Up @@ -83,6 +83,7 @@ module.exports = {
"error",
{ version: "12.17.0", ignores: ["modules"] },
],
"@babel/development-internal/require-default-import-fallback": "error",
},
},
{
Expand Down
5 changes: 2 additions & 3 deletions eslint/babel-eslint-plugin-development-internal/src/index.cjs
@@ -1,7 +1,6 @@
const reportErrorMessageFormat = require("./rules/report-error-message-format.cjs");

const rules = {
"report-error-message-format": reportErrorMessageFormat,
"report-error-message-format": require("./rules/report-error-message-format.cjs"),
"require-default-import-fallback": require("./rules/require-default-import-fallback.cjs"),
};

exports.rules = rules;
Expand Down
@@ -0,0 +1,76 @@
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "",
},
fixable: "code",
},
create(ctx) {
return {
ImportDeclaration(node) {
const filename = ctx.getFilename();
const src = node.source.value;
if (
// Not a source file in the monorepo
(!src.includes("/lib/") && !src.startsWith("@babel/")) ||
// This package already always uses the ESM entrypoint.
src === "@babel/helper-plugin-test-runner" ||
// Unclear if we'll convert this or it will stay as JSON.
src.startsWith("@babel/compat-data") ||
// This will not become an ESM file.
src.endsWith(".cjs") ||
// @babel/core automatically unwraps .default from plugins/presets.
/^@babel\/(plugin|preset)-/.test(src) ||
(src.endsWith("./lib/index.js") &&
/babel-(plugin|preset)-/.test(filename))
) {
return;
}

const defaultSpecifier = node.specifiers.find(
spec => spec.type === "ImportDefaultSpecifier",
);
if (!defaultSpecifier) return;

const scope = ctx.getScope();

const { name: local } = defaultSpecifier.local;
const { references } = scope.variables.find(v => v.name === local);

const isRef = node => node.type === "Identifier" && node.name === local;
const isRefDefault = node =>
node.type === "MemberExpression" &&
!node.computed &&
node.property.name === "default" &&
isRef(node.object);

for (const { identifier } of references) {
const base =
identifier.parent.type === "MemberExpression"
? identifier.parent.parent
: identifier.parent;

if (
base.type !== "LogicalExpression" ||
base.operator !== "||" ||
!isRefDefault(base.left) ||
!isRef(base.right)
) {
const expected = `${local}.default || ${local}`;
ctx.report({
node: identifier,
message: `Default imports of source files must be used with an explicit fallback: \`${expected}\``,
fix(fixer) {
const base = isRefDefault(identifier.parent)
? identifier.parent
: identifier;
return fixer.replaceText(base, `(${expected})`);
},
});
}
}
},
};
},
};
2 changes: 1 addition & 1 deletion packages/babel-code-frame/test/index.js
Expand Up @@ -2,7 +2,7 @@ import chalk from "chalk";
import stripAnsi from "strip-ansi";

import _codeFrame, { codeFrameColumns } from "../lib/index.js";
const codeFrame = _codeFrame.default;
const codeFrame = _codeFrame.default || _codeFrame;

describe("@babel/code-frame", function () {
test("basic usage", function () {
Expand Down
3 changes: 3 additions & 0 deletions packages/babel-core/package.json
Expand Up @@ -66,7 +66,10 @@
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "workspace:^",
"@babel/plugin-syntax-flow": "workspace:^",
"@babel/plugin-transform-flow-strip-types": "workspace:^",
"@babel/plugin-transform-modules-commonjs": "workspace:^",
"@babel/preset-env": "workspace:^",
"@jridgewell/trace-mapping": "^0.3.8",
"@types/convert-source-map": "^1.5.1",
"@types/debug": "^4.1.0",
Expand Down
10 changes: 5 additions & 5 deletions packages/babel-core/test/api.js
Expand Up @@ -5,11 +5,11 @@ import generator from "@babel/generator";
import { fileURLToPath } from "url";

import _Plugin from "../lib/config/plugin.js";
const Plugin = _Plugin.default;
const Plugin = _Plugin.default || _Plugin;

import presetEnv from "../../babel-preset-env/lib/index.js";
import pluginSyntaxFlow from "../../babel-plugin-syntax-flow/lib/index.js";
import pluginFlowStripTypes from "../../babel-plugin-transform-flow-strip-types/lib/index.js";
import presetEnv from "@babel/preset-env";
import pluginSyntaxFlow from "@babel/plugin-syntax-flow";
import pluginFlowStripTypes from "@babel/plugin-transform-flow-strip-types";

const cwd = path.dirname(fileURLToPath(import.meta.url));

Expand Down Expand Up @@ -73,7 +73,7 @@ describe("parser and generator options", function () {
return opts.parser.parse(code);
},
print: function (ast) {
return generator(ast);
return (generator.default || generator)(ast);
},
};

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/test/config-chain.js
Expand Up @@ -6,7 +6,7 @@ import * as babel from "../lib/index.js";
import rimraf from "rimraf";

import _getTargets from "@babel/helper-compilation-targets";
const getTargets = _getTargets.default;
const getTargets = _getTargets.default || _getTargets;

const dirname = path.dirname(fileURLToPath(import.meta.url));

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/test/config-loading.js
Expand Up @@ -8,7 +8,7 @@ import { createRequire } from "module";

const require = createRequire(import.meta.url);

const loadConfig = _loadConfigRunner.default.sync;
const loadConfig = (_loadConfigRunner.default || _loadConfigRunner).sync;

describe("@babel/core config loading", () => {
const FILEPATH = path.join(
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/test/evaluation.js
@@ -1,7 +1,7 @@
import { parse } from "@babel/parser";

import _traverse from "@babel/traverse";
const traverse = _traverse.default;
const traverse = _traverse.default || _traverse;

describe("evaluation", function () {
function addTest(code, type, value, notConfident) {
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/test/merge-map.js
@@ -1,5 +1,5 @@
import _mergeSourceMap from "../lib/transformation/file/merge-map.js";
const mergeSourceMap = _mergeSourceMap.default;
const mergeSourceMap = _mergeSourceMap.default || _mergeSourceMap;

describe("merge-map", () => {
it("returns a plain js object", () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/test/path.js
Expand Up @@ -3,7 +3,7 @@ import { fileURLToPath } from "url";
import path from "path";

import _Plugin from "../lib/config/plugin.js";
const Plugin = _Plugin.default;
const Plugin = _Plugin.default || _Plugin;

const cwd = path.dirname(fileURLToPath(import.meta.url));

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/test/plugins.js
Expand Up @@ -2,7 +2,7 @@ import runner from "@babel/helper-transform-fixture-test-runner";
import { fileURLToPath } from "url";
import path from "path";

runner.default(
(runner.default || runner)(
path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures/plugins"),
"plugins",
);
2 changes: 1 addition & 1 deletion packages/babel-core/test/transformation.js
Expand Up @@ -2,7 +2,7 @@ import runner from "@babel/helper-transform-fixture-test-runner";
import { fileURLToPath } from "url";
import path from "path";

runner.default(
(runner.default || runner)(
path.join(
path.dirname(fileURLToPath(import.meta.url)),
"/fixtures/transformation",
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-generator/test/arrow-functions.js
@@ -1,7 +1,7 @@
import { parse } from "@babel/parser";

import _generate from "../lib/index.js";
const generate = _generate.default;
const generate = _generate.default || _generate;

describe("parameter parentheses", () => {
// Common source text for several snapshot tests
Expand Down
6 changes: 3 additions & 3 deletions packages/babel-generator/test/index.js
Expand Up @@ -8,8 +8,8 @@ import { fileURLToPath } from "url";

import _Printer from "../lib/printer.js";
import _generate, { CodeGenerator } from "../lib/index.js";
const Printer = _Printer.default;
const generate = _generate.default;
const Printer = _Printer.default || _Printer;
const generate = _generate.default || _generate;

describe("generation", function () {
it("completeness", function () {
Expand Down Expand Up @@ -806,7 +806,7 @@ describe("CodeGenerator", function () {
});
});

const suites = fixtures.default(
const suites = (fixtures.default || fixtures)(
path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures"),
);

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-helper-annotate-as-pure/test/index.js
@@ -1,5 +1,5 @@
import _annotateAsPure from "../lib/index.js";
const annotateAsPure = _annotateAsPure.default;
const annotateAsPure = _annotateAsPure.default || _annotateAsPure;

describe("@babel/helper-annotate-as-pure", () => {
it("will add leading comment", () => {
Expand Down
3 changes: 2 additions & 1 deletion packages/babel-helper-check-duplicate-nodes/test/index.js
@@ -1,6 +1,7 @@
import _checkDuplicateNodes from "../lib/index.js";
import { parseSync, traverse, types as t } from "@babel/core";
const checkDuplicateNodes = _checkDuplicateNodes.default;
const checkDuplicateNodes =
_checkDuplicateNodes.default || _checkDuplicateNodes;

describe("checkDuplicateNodes", () => {
it("should throw on duplicate AST nodes within same parent", () => {
Expand Down
Expand Up @@ -2,7 +2,7 @@ import { dirname, resolve } from "path";
import { fileURLToPath } from "url";

import _getTargets from "../../lib/index.js";
const getTargets = _getTargets.default;
const getTargets = _getTargets.default || _getTargets;

const currentDir = dirname(fileURLToPath(import.meta.url));

Expand Down
Expand Up @@ -2,7 +2,7 @@ import { fileURLToPath } from "url";
import path from "path";

import _getTargets from "../../lib/index.js";
const getTargets = _getTargets.default;
const getTargets = _getTargets.default || _getTargets;

it("allows custom browserslist env", () => {
const actual = getTargets(
Expand Down
Expand Up @@ -2,7 +2,7 @@ import { fileURLToPath } from "url";
import path from "path";

import _getTargets from "../../lib/index.js";
const getTargets = _getTargets.default;
const getTargets = _getTargets.default || _getTargets;

const oldCwd = process.cwd();

Expand Down
Expand Up @@ -2,7 +2,7 @@ import { fileURLToPath } from "url";
import path from "path";

import _getTargets from "../../lib/index.js";
const getTargets = _getTargets.default;
const getTargets = _getTargets.default || _getTargets;

const oldCwd = process.cwd();

Expand Down
Expand Up @@ -3,7 +3,7 @@ import { join, dirname } from "path";
import { fileURLToPath } from "url";

import _getTargets from "../lib/index.js";
const getTargets = _getTargets.default;
const getTargets = _getTargets.default || _getTargets;

describe("getTargets", () => {
it("parses", () => {
Expand Down
5 changes: 3 additions & 2 deletions packages/babel-helper-optimise-call-expression/test/index.js
Expand Up @@ -3,8 +3,9 @@ import * as t from "@babel/types";

import _generator from "@babel/generator";
import _optimizeCallExpression from "../lib/index.js";
const generator = _generator.default;
const optimizeCallExpression = _optimizeCallExpression.default;
const generator = _generator.default || _generator;
const optimizeCallExpression =
_optimizeCallExpression.default || _optimizeCallExpression;

function transformInput(input, thisIdentifier) {
const ast = parse(input);
Expand Down
5 changes: 3 additions & 2 deletions packages/babel-helper-plugin-test-runner/esm.mjs
@@ -1,11 +1,12 @@
import _cjs from "./lib/index.js";
const cjs = _cjs.default || _cjs;

const adapter = _cjs.default.bind();
const adapter = cjs.bind();

// For backward compatibility with the CJS-only version, this makes
// import _x from "@babel/helper-plugin-test-runner"
// const x = _x.default
// still work.
adapter.default = _cjs.default;
adapter.default = cjs;

export default adapter;
2 changes: 1 addition & 1 deletion packages/babel-helper-simple-access/test/index.js
Expand Up @@ -7,7 +7,7 @@ const plugin = (_api, options) => {
return {
visitor: {
Program(path) {
simplifyAccess.default(
(simplifyAccess.default || simplifyAccess)(
path,
new Set(bindingNames),
includeUpdateExpression,
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-highlight/test/index.js
Expand Up @@ -2,7 +2,7 @@ import chalk from "chalk";
import stripAnsi from "strip-ansi";

import _highlight, { shouldHighlight, getChalk } from "../lib/index.js";
const highlight = _highlight.default;
const highlight = _highlight.default || _highlight;

describe("@babel/highlight", function () {
function stubColorSupport(supported) {
Expand Down
3 changes: 2 additions & 1 deletion packages/babel-parser/test/helpers/run-fixture-tests.js
Expand Up @@ -10,7 +10,8 @@ import toContextualSyntaxError from "./to-contextual-syntax-error.js";

const { CI, OVERWRITE } = process.env;
const { stringify, parse: JSONParse } = JSON;
const checkDuplicateNodes = _checkDuplicateNodes.default;
const checkDuplicateNodes =
_checkDuplicateNodes.default || _checkDuplicateNodes;

const writeFileWithNewline = (path, string) =>
writeFileSync(path, `${string}\n`, "utf-8");
Expand Down
Expand Up @@ -2,7 +2,8 @@ import { parse } from "@babel/parser";

import _shouldStoreRHSInTemporaryVariable from "../lib/shouldStoreRHSInTemporaryVariable.js";
const shouldStoreRHSInTemporaryVariable =
_shouldStoreRHSInTemporaryVariable.default;
_shouldStoreRHSInTemporaryVariable.default ||
_shouldStoreRHSInTemporaryVariable;

function getFistObjectPattern(program) {
return parse(program, { sourceType: "module" }).program.body[0]
Expand Down
@@ -1,5 +1,6 @@
import _getOptionSpecificExcludesFor from "../lib/get-option-specific-excludes.js";
const getOptionSpecificExcludesFor = _getOptionSpecificExcludesFor.default;
const getOptionSpecificExcludesFor =
_getOptionSpecificExcludesFor.default || _getOptionSpecificExcludesFor;

describe("defaults", () => {
describe("getOptionSpecificExcludesFor", () => {
Expand Down
10 changes: 6 additions & 4 deletions packages/babel-preset-env/test/index.spec.js
Expand Up @@ -7,10 +7,12 @@ import _removeRegeneratorEntryPlugin from "../lib/polyfills/regenerator.js";
import _pluginLegacyBabelPolyfill from "../lib/polyfills/babel-polyfill.js";
import _transformations from "../lib/module-transformations.js";
import _availablePlugins from "../lib/available-plugins.js";
const removeRegeneratorEntryPlugin = _removeRegeneratorEntryPlugin.default;
const pluginLegacyBabelPolyfill = _pluginLegacyBabelPolyfill.default;
const transformations = _transformations.default;
const availablePlugins = _availablePlugins.default;
const removeRegeneratorEntryPlugin =
_removeRegeneratorEntryPlugin.default || _removeRegeneratorEntryPlugin;
const pluginLegacyBabelPolyfill =
_pluginLegacyBabelPolyfill.default || _pluginLegacyBabelPolyfill;
const transformations = _transformations.default || _transformations;
const availablePlugins = _availablePlugins.default || _availablePlugins;

import { createRequire } from "module";
const require = createRequire(import.meta.url);
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-preset-env/test/normalize-options.spec.js
Expand Up @@ -4,7 +4,7 @@ import _normalizeOptions, {
validateUseBuiltInsOption,
normalizePluginName,
} from "../lib/normalize-options.js";
const normalizeOptions = _normalizeOptions.default;
const normalizeOptions = _normalizeOptions.default || _normalizeOptions;

describe("normalize-options", () => {
describe("normalizeOptions", () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-preset-flow/test/normalize-options.spec.js
@@ -1,5 +1,5 @@
import _normalizeOptions from "../lib/normalize-options.js";
const normalizeOptions = _normalizeOptions.default;
const normalizeOptions = _normalizeOptions.default || _normalizeOptions;

describe("normalize options", () => {
(process.env.BABEL_8_BREAKING ? describe : describe.skip)("Babel 8", () => {
Expand Down

0 comments on commit f0ec180

Please sign in to comment.