Compiler: unfork prettier config (#30205)

Updates the prettier config to format all `.ts` and `.tsx` files in the
repo using the existing defaults and removing overrides.

The first commit in this PR contains the config changes, the second is
just the result of running `yarn prettier-all`.
This commit is contained in:
Jan Kassens
2024-07-18 17:00:24 -04:00
committed by GitHub
parent 6fac743ed7
commit fd2b3e13d3
1898 changed files with 12437 additions and 12663 deletions

View File

@@ -5,15 +5,15 @@
* LICENSE file in the root directory of this source tree.
*/
import type * as BabelCore from "@babel/core";
import { NodePath } from "@babel/core";
import * as t from "@babel/types";
import type * as BabelCore from '@babel/core';
import {NodePath} from '@babel/core';
import * as t from '@babel/types';
export default function AnnotateReactCodeBabelPlugin(
_babel: typeof BabelCore
_babel: typeof BabelCore,
): BabelCore.PluginObj {
return {
name: "annotate-react-code",
name: 'annotate-react-code',
visitor: {
Program(prog): void {
annotate(prog);
@@ -56,23 +56,23 @@ function buildTypeOfReactForget(): t.Statement {
// typeof globalThis[Symbol.for("react_forget")]
return t.expressionStatement(
t.unaryExpression(
"typeof",
'typeof',
t.memberExpression(
t.identifier("globalThis"),
t.identifier('globalThis'),
t.callExpression(
t.memberExpression(
t.identifier("Symbol"),
t.identifier("for"),
t.identifier('Symbol'),
t.identifier('for'),
false,
false,
false
),
[t.stringLiteral("react_forget")]
[t.stringLiteral('react_forget')],
),
true,
false
false,
),
true
)
true,
),
);
}
@@ -89,9 +89,9 @@ type BabelFn =
| NodePath<t.ArrowFunctionExpression>;
export function isComponentDeclaration(
node: t.FunctionDeclaration
node: t.FunctionDeclaration,
): node is ComponentDeclaration {
return Object.prototype.hasOwnProperty.call(node, "__componentDeclaration");
return Object.prototype.hasOwnProperty.call(node, '__componentDeclaration');
}
/*
@@ -101,7 +101,7 @@ export function isComponentDeclaration(
function isComponentOrHookLike(
node: NodePath<
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
>
>,
): boolean {
const functionName = getFunctionName(node);
// Check if the name is component or hook like:
@@ -114,7 +114,7 @@ function isComponentOrHookLike(
* helpers are _usually_ named with lowercase, but some code may
* violate this rule
*/
node.get("params").length <= 1
node.get('params').length <= 1
);
} else if (functionName !== null && isHook(functionName)) {
// Hooks have hook invocations or JSX, but can take any # of arguments
@@ -151,11 +151,11 @@ function isHook(path: NodePath<t.Expression | t.PrivateName>): boolean {
} else if (
path.isMemberExpression() &&
!path.node.computed &&
isHook(path.get("property"))
isHook(path.get('property'))
) {
const obj = path.get("object").node;
const obj = path.get('object').node;
const isPascalCaseNameSpace = /^[A-Z].*/;
return obj.type === "Identifier" && isPascalCaseNameSpace.test(obj.name);
return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name);
} else {
return false;
}
@@ -177,8 +177,8 @@ function isComponentName(path: NodePath<t.Expression>): boolean {
function isForwardRefCallback(path: NodePath<t.Expression>): boolean {
return !!(
path.parentPath.isCallExpression() &&
path.parentPath.get("callee").isExpression() &&
isReactAPI(path.parentPath.get("callee"), "forwardRef")
path.parentPath.get('callee').isExpression() &&
isReactAPI(path.parentPath.get('callee'), 'forwardRef')
);
}
@@ -190,22 +190,22 @@ function isForwardRefCallback(path: NodePath<t.Expression>): boolean {
function isMemoCallback(path: NodePath<t.Expression>): boolean {
return (
path.parentPath.isCallExpression() &&
path.parentPath.get("callee").isExpression() &&
isReactAPI(path.parentPath.get("callee"), "memo")
path.parentPath.get('callee').isExpression() &&
isReactAPI(path.parentPath.get('callee'), 'memo')
);
}
function isReactAPI(
path: NodePath<t.Expression | t.PrivateName | t.V8IntrinsicIdentifier>,
functionName: string
functionName: string,
): boolean {
const node = path.node;
return (
(node.type === "Identifier" && node.name === functionName) ||
(node.type === "MemberExpression" &&
node.object.type === "Identifier" &&
node.object.name === "React" &&
node.property.type === "Identifier" &&
(node.type === 'Identifier' && node.name === functionName) ||
(node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
node.object.name === 'React' &&
node.property.type === 'Identifier' &&
node.property.name === functionName)
);
}
@@ -218,7 +218,7 @@ function callsHooksOrCreatesJsx(node: NodePath<t.Node>): boolean {
createsJsx = true;
},
CallExpression(call) {
const callee = call.get("callee");
const callee = call.get('callee');
if (callee.isExpression() && isHook(callee)) {
invokesHooks = true;
}
@@ -239,10 +239,10 @@ function callsHooksOrCreatesJsx(node: NodePath<t.Node>): boolean {
function getFunctionName(
path: NodePath<
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
>
>,
): NodePath<t.Expression> | null {
if (path.isFunctionDeclaration()) {
const id = path.get("id");
const id = path.get('id');
if (id.isIdentifier()) {
return id;
}
@@ -250,31 +250,31 @@ function getFunctionName(
}
let id: NodePath<t.LVal | t.Expression | t.PrivateName> | null = null;
const parent = path.parentPath;
if (parent.isVariableDeclarator() && parent.get("init").node === path.node) {
if (parent.isVariableDeclarator() && parent.get('init').node === path.node) {
// const useHook = () => {};
id = parent.get("id");
id = parent.get('id');
} else if (
parent.isAssignmentExpression() &&
parent.get("right").node === path.node &&
parent.get("operator") === "="
parent.get('right').node === path.node &&
parent.get('operator') === '='
) {
// useHook = () => {};
id = parent.get("left");
id = parent.get('left');
} else if (
parent.isProperty() &&
parent.get("value").node === path.node &&
!parent.get("computed") &&
parent.get("key").isLVal()
parent.get('value').node === path.node &&
!parent.get('computed') &&
parent.get('key').isLVal()
) {
/*
* {useHook: () => {}}
* {useHook() {}}
*/
id = parent.get("key");
id = parent.get('key');
} else if (
parent.isAssignmentPattern() &&
parent.get("right").node === path.node &&
!parent.get("computed")
parent.get('right').node === path.node &&
!parent.get('computed')
) {
/*
* const {useHook = () => {}} = {};
@@ -283,7 +283,7 @@ function getFunctionName(
* Kinda clowny, but we'd said we'd follow spec convention for
* `IsAnonymousFunctionDefinition()` usage.
*/
id = parent.get("left");
id = parent.get('left');
}
if (id !== null && (id.isIdentifier() || id.isMemberExpression())) {
return id;

View File

@@ -5,27 +5,27 @@
* LICENSE file in the root directory of this source tree.
*/
"use strict";
'use strict';
const { tests } = require("./eslint-plugin-react-hooks-test-cases");
const {tests} = require('./eslint-plugin-react-hooks-test-cases');
const {
runBabelPluginReactCompiler,
} = require("../dist/Babel/RunReactCompilerBabelPlugin");
const fs = require("fs");
const path = require("path");
const prettier = require("prettier");
const prettierConfigPath = require.resolve("../.prettierrc");
const process = require("process");
const { createHash } = require("crypto");
const { create } = require("domain");
} = require('../dist/Babel/RunReactCompilerBabelPlugin');
const fs = require('fs');
const path = require('path');
const prettier = require('prettier');
const prettierConfigPath = require.resolve('../.prettierrc');
const process = require('process');
const {createHash} = require('crypto');
const {create} = require('domain');
const FIXTURES_DIR = path.join(
process.cwd(),
"src",
"__tests__",
"fixtures",
"compiler",
"rules-of-hooks"
'src',
'__tests__',
'fixtures',
'compiler',
'rules-of-hooks'
);
const PRETTIER_OPTIONS = prettier.resolveConfig.sync(FIXTURES_DIR, {
@@ -34,10 +34,10 @@ const PRETTIER_OPTIONS = prettier.resolveConfig.sync(FIXTURES_DIR, {
const fixtures = [];
for (const test of tests.valid) {
fixtures.push({ code: test.code, valid: true });
fixtures.push({code: test.code, valid: true});
}
for (const test of tests.invalid) {
fixtures.push({ code: test.code, valid: false });
fixtures.push({code: test.code, valid: false});
}
for (const fixture of fixtures) {
@@ -47,8 +47,8 @@ for (const fixture of fixtures) {
// Does the fixture pass with hooks validation disabled? if not skip it
runBabelPluginReactCompiler(
fixture.code,
"rules-of-hooks.js",
"typescript",
'rules-of-hooks.js',
'typescript',
{
environment: {
validateHooksUsage: false,
@@ -59,8 +59,8 @@ for (const fixture of fixtures) {
try {
runBabelPluginReactCompiler(
fixture.code,
"rules-of-hooks.js",
"typescript",
'rules-of-hooks.js',
'typescript',
{
environment: {
validateHooksUsage: true,
@@ -74,7 +74,7 @@ for (const fixture of fixtures) {
error = e;
}
let code = fixture.code;
let prefix = "";
let prefix = '';
if (error !== null) {
prefix = `todo.bail.`;
code = `// @skip\n// Unsupported input\n${code}`;
@@ -92,11 +92,11 @@ for (const fixture of fixtures) {
code = `// @skip\n// Failed but should have passed\n${code}`;
}
const formatted = prettier.format(code, PRETTIER_OPTIONS);
const hmac = createHash("sha256");
hmac.update(formatted, "utf8");
const hmac = createHash('sha256');
hmac.update(formatted, 'utf8');
let name = `${prefix}rules-of-hooks-${hmac
.digest("hex")
.digest('hex')
.substring(0, 12)}.js`;
const fixturePath = path.join(FIXTURES_DIR, name);
fs.writeFileSync(fixturePath, formatted, "utf8");
fs.writeFileSync(fixturePath, formatted, 'utf8');
}

View File

@@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
"use strict";
'use strict';
// NOTE: Extracted from https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js
@@ -13,9 +13,9 @@
* A string template tag that removes padding from the left side of multi-line strings
*/
function normalizeIndent(strings) {
const codeLines = strings[0].split("\n");
const codeLines = strings[0].split('\n');
const leftPadding = codeLines[1].match(/\s+/)[0];
return codeLines.map((line) => line.slice(leftPadding.length)).join("\n");
return codeLines.map(line => line.slice(leftPadding.length)).join('\n');
}
module.exports.tests = {

View File

@@ -5,6 +5,6 @@
* LICENSE file in the root directory of this source tree.
*/
const makeE2EConfig = require("../jest/makeE2EConfig");
const makeE2EConfig = require('../jest/makeE2EConfig');
module.exports = makeE2EConfig("e2e no forget", false);
module.exports = makeE2EConfig('e2e no forget', false);

View File

@@ -5,9 +5,9 @@
* LICENSE file in the root directory of this source tree.
*/
const makeE2EConfig = require("../jest/makeE2EConfig");
const makeE2EConfig = require('../jest/makeE2EConfig');
const config = makeE2EConfig("e2e with forget", true);
config.setupFilesAfterEnv = ["<rootDir>/../scripts/jest/setupEnvE2E.js"];
const config = makeE2EConfig('e2e with forget', true);
config.setupFilesAfterEnv = ['<rootDir>/../scripts/jest/setupEnvE2E.js'];
module.exports = config;

View File

@@ -6,10 +6,10 @@
*/
module.exports = {
displayName: "main",
preset: "ts-jest",
rootDir: "../../src",
testPathIgnorePatterns: ["e2e", "TestDriver", "test-utils", "fixtures"],
displayName: 'main',
preset: 'ts-jest',
rootDir: '../../src',
testPathIgnorePatterns: ['e2e', 'TestDriver', 'test-utils', 'fixtures'],
globals: {
__DEV__: true,
},

View File

@@ -8,27 +8,27 @@
module.exports = function makeE2EConfig(displayName, useForget) {
return {
displayName,
testEnvironment: "jsdom",
rootDir: "../../src",
testMatch: ["**/*.e2e.(js|tsx)"],
testEnvironment: 'jsdom',
rootDir: '../../src',
testMatch: ['**/*.e2e.(js|tsx)'],
modulePathIgnorePatterns: [
// ignore snapshots from the opposite forget configuration
useForget ? ".*\\.no-forget\\.snap$" : ".*\\.with-forget\\.snap$",
useForget ? '.*\\.no-forget\\.snap$' : '.*\\.with-forget\\.snap$',
// ignore snapshots from the main project
".*\\.ts\\.snap$",
'.*\\.ts\\.snap$',
],
globals: {
__FORGET__: useForget,
},
snapshotResolver: useForget
? "<rootDir>/../scripts/jest/snapshot-resolver-with-forget.js"
: "<rootDir>/../scripts/jest/snapshot-resolver-no-forget.js",
? '<rootDir>/../scripts/jest/snapshot-resolver-with-forget.js'
: '<rootDir>/../scripts/jest/snapshot-resolver-no-forget.js',
transform: {
"\\.[tj]sx?$": useForget
? "<rootDir>/../scripts/jest/transform-with-forget"
: "<rootDir>/../scripts/jest/transform-no-forget",
'\\.[tj]sx?$': useForget
? '<rootDir>/../scripts/jest/transform-with-forget'
: '<rootDir>/../scripts/jest/transform-no-forget',
},
transformIgnorePatterns: ["/node_modules/"],
transformIgnorePatterns: ['/node_modules/'],
};
};

View File

@@ -6,7 +6,7 @@
*/
module.exports = function makeSnapshotResolver(useForget) {
const modeExtension = useForget ? ".with-forget" : ".no-forget";
const modeExtension = useForget ? '.with-forget' : '.no-forget';
return {
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath + modeExtension + snapshotExtension,
@@ -17,6 +17,6 @@ module.exports = function makeSnapshotResolver(useForget) {
-modeExtension.length - snapshotExtension.length
),
testPathForConsistencyCheck: "some/__tests__/example.test.js",
testPathForConsistencyCheck: 'some/__tests__/example.test.js',
};
};

View File

@@ -5,19 +5,19 @@
* LICENSE file in the root directory of this source tree.
*/
import { jsx } from "@babel/plugin-syntax-jsx";
import babelJest from "babel-jest";
import { compile } from "babel-plugin-react-compiler";
import { execSync } from "child_process";
import {jsx} from '@babel/plugin-syntax-jsx';
import babelJest from 'babel-jest';
import {compile} from 'babel-plugin-react-compiler';
import {execSync} from 'child_process';
import type { NodePath, Visitor } from "@babel/traverse";
import type { CallExpression, FunctionDeclaration } from "@babel/types";
import * as t from "@babel/types";
import type {NodePath, Visitor} from '@babel/traverse';
import type {CallExpression, FunctionDeclaration} from '@babel/types';
import * as t from '@babel/types';
import {
EnvironmentConfig,
validateEnvironmentConfig,
} from "babel-plugin-react-compiler";
import { basename } from "path";
} from 'babel-plugin-react-compiler';
import {basename} from 'path';
/**
* -- IMPORTANT --
@@ -30,14 +30,14 @@ const forgetOptions: EnvironmentConfig = validateEnvironmentConfig({
enableAssumeHooksFollowRulesOfReact: true,
enableFunctionOutlining: false,
});
const debugMode = process.env["DEBUG_FORGET_COMPILER"] != null;
const debugMode = process.env['DEBUG_FORGET_COMPILER'] != null;
module.exports = (useForget: boolean) => {
function createTransformer() {
return babelJest.createTransformer({
passPerPreset: true,
presets: [
"@babel/preset-typescript",
'@babel/preset-typescript',
{
plugins: [
useForget
@@ -49,36 +49,36 @@ module.exports = (useForget: boolean) => {
* (see https://github.com/jestjs/jest/blob/v29.6.2/packages/babel-jest/src/index.ts#L84)
*/
compilerCacheKey: execSync(
"yarn --silent --cwd ../.. hash packages/babel-plugin-react-compiler/dist"
'yarn --silent --cwd ../.. hash packages/babel-plugin-react-compiler/dist',
).toString(),
transformOptionsCacheKey: forgetOptions,
e2eTransformerCacheKey,
},
]
: "@babel/plugin-syntax-jsx",
: '@babel/plugin-syntax-jsx',
],
},
"@babel/preset-react",
'@babel/preset-react',
{
plugins: [
[
function BabelPluginRewriteRequirePath(): { visitor: Visitor } {
function BabelPluginRewriteRequirePath(): {visitor: Visitor} {
return {
visitor: {
CallExpression(path: NodePath<CallExpression>): void {
const { callee } = path.node;
const {callee} = path.node;
if (
callee.type === "Identifier" &&
callee.name === "require"
callee.type === 'Identifier' &&
callee.name === 'require'
) {
const arg = path.node.arguments[0];
if (arg.type === "StringLiteral") {
if (arg.type === 'StringLiteral') {
/*
* The compiler adds requires of "React", which is expected to be a wrapper
* around the "react" package. For tests, we just rewrite the require.
*/
if (arg.value === "React") {
arg.value = "react";
if (arg.value === 'React') {
arg.value = 'react';
}
}
}
@@ -87,7 +87,7 @@ module.exports = (useForget: boolean) => {
};
},
],
"@babel/plugin-transform-modules-commonjs",
'@babel/plugin-transform-modules-commonjs',
],
},
],
@@ -125,7 +125,7 @@ function isReactComponentLike(fn: NodePath<FunctionDeclaration>): boolean {
fn.traverse({
DirectiveLiteral(path) {
if (path.node.value === "use no forget") {
if (path.node.value === 'use no forget') {
hasNoUseForgetDirective = true;
}
},
@@ -140,7 +140,7 @@ function isReactComponentLike(fn: NodePath<FunctionDeclaration>): boolean {
CallExpression(path) {
// Is there hook usage?
if (
path.node.callee.type === "Identifier" &&
path.node.callee.type === 'Identifier' &&
!/^use[A-Z0-9]/.test(path.node.callee.name)
) {
isReactComponent = true;
@@ -170,7 +170,7 @@ function ReactForgetFunctionTransform() {
const filename = basename(state.file.opts.filename);
if (fn.node.loc && fn.node.id) {
console.log(
` Compiling ${filename}:${fn.node.loc.start.line}:${fn.node.loc.start.column} ${fn.node.id.name}`
` Compiling ${filename}:${fn.node.loc.start.line}:${fn.node.loc.start.column} ${fn.node.id.name}`,
);
} else {
console.log(` Compiling ${filename} ${fn.node.id?.name}`);
@@ -180,11 +180,11 @@ function ReactForgetFunctionTransform() {
const compiled = compile(
fn,
forgetOptions,
"Other",
"_c",
'Other',
'_c',
null,
null,
null,
null
);
compiledFns.add(compiled);
@@ -193,14 +193,14 @@ function ReactForgetFunctionTransform() {
compiled.params,
compiled.body,
compiled.generator,
compiled.async
compiled.async,
);
fn.replaceWith(fun);
fn.skip();
},
};
return {
name: "react-forget-e2e",
name: 'react-forget-e2e',
inherits: jsx,
visitor,
};

View File

@@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
const ReactCompilerRuntime = require("react/compiler-runtime");
const ReactCompilerRuntime = require('react/compiler-runtime');
/*
* Our e2e babel transform currently only compiles functions, not programs.

View File

@@ -5,6 +5,6 @@
* LICENSE file in the root directory of this source tree.
*/
const makeSnapshotResolver = require("./makeSnapshotResolver");
const makeSnapshotResolver = require('./makeSnapshotResolver');
module.exports = makeSnapshotResolver(false);

View File

@@ -5,6 +5,6 @@
* LICENSE file in the root directory of this source tree.
*/
const makeSnapshotResolver = require("./makeSnapshotResolver");
const makeSnapshotResolver = require('./makeSnapshotResolver');
module.exports = makeSnapshotResolver(true);

View File

@@ -5,4 +5,4 @@
* LICENSE file in the root directory of this source tree.
*/
module.exports = require("./makeTransform")(false);
module.exports = require('./makeTransform')(false);

View File

@@ -5,4 +5,4 @@
* LICENSE file in the root directory of this source tree.
*/
module.exports = require("./makeTransform")(true);
module.exports = require('./makeTransform')(true);