Skip to content

Commit

Permalink
chore: enable prefer-template (#9544)
Browse files Browse the repository at this point in the history
* prefer-template

* review

* cleanup

* minor cleanup
  • Loading branch information
abrahamguo authored Aug 14, 2024
1 parent a4acc2b commit 243fb5f
Show file tree
Hide file tree
Showing 22 changed files with 62 additions and 73 deletions.
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ export default tseslint.config(
'prefer-object-has-own': 'error',
'prefer-object-spread': 'error',
'prefer-rest-params': 'error',
'prefer-template': 'error',
radix: 'error',

//
Expand Down
21 changes: 9 additions & 12 deletions packages/ast-spec/tests/util/serialize-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,13 @@ export function serializeError(error: unknown, contents: string): unknown {
location: { start, end },
} = error;

return (
name +
'\n' +
codeFrameColumns(
contents,
{
start: { line: start.line, column: start.column + 1 },
end: { line: end.line, column: end.column + 1 },
},
{ highlightCode: false, message },
)
);
return `${name}
${codeFrameColumns(
contents,
{
start: { line: start.line, column: start.column + 1 },
end: { line: end.line, column: end.column + 1 },
},
{ highlightCode: false, message },
)}`;
}
2 changes: 1 addition & 1 deletion packages/ast-spec/tests/util/snapshot-diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function snapshotDiff(
throw new Error('Unexpected null when diffing snapshots.');
}

return 'Snapshot Diff:\n' + difference;
return `Snapshot Diff:\n${difference}`;
}

// https://github.com/facebook/jest/blob/a293b75310cfc209713df1d34d243eb258995316/packages/jest-diff/src/constants.ts#L8
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function getExpectedIndentForNode(
}
function doIndent(line: string, indent: number): string {
for (let i = 0; i < indent; i += 1) {
line = ' ' + line;
line = ` ${line}`;
}
return line;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export default createRule<Options, MessageIds>({
fixer.remove(typeArguments),
fixer.insertTextAfter(
getIDToAttachAnnotation(),
': ' + typeAnnotation,
`: ${typeAnnotation}`,
),
];
},
Expand Down
6 changes: 2 additions & 4 deletions packages/eslint-plugin/src/rules/no-floating-promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,8 @@ export default createRule<Options, MessageId>({
floatingFixAwait: 'Add await operator.',
floatingVoid: messageBaseVoid,
floatingFixVoid: 'Add void operator to ignore.',
floatingUselessRejectionHandler:
messageBase + ' ' + messageRejectionHandler,
floatingUselessRejectionHandlerVoid:
messageBaseVoid + ' ' + messageRejectionHandler,
floatingUselessRejectionHandler: `${messageBase} ${messageRejectionHandler}`,
floatingUselessRejectionHandlerVoid: `${messageBaseVoid} ${messageRejectionHandler}`,
floatingPromiseArray: messagePromiseArray,
floatingPromiseArrayVoid: messagePromiseArrayVoid,
},
Expand Down
4 changes: 2 additions & 2 deletions packages/eslint-plugin/src/rules/no-unsafe-assignment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,8 @@ export default createRule({
): Readonly<Record<string, unknown>> | undefined {
if (receiverType) {
return {
sender: '`' + checker.typeToString(senderType) + '`',
receiver: '`' + checker.typeToString(receiverType) + '`',
sender: `\`${checker.typeToString(senderType)}\``,
receiver: `\`${checker.typeToString(receiverType)}\``,
};
}
return {
Expand Down
16 changes: 7 additions & 9 deletions packages/eslint-plugin/src/rules/prefer-function-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,13 @@ export default createRule({
node.type === AST_NODE_TYPES.TSInterfaceDeclaration &&
isParentExported
) {
const commentsText = comments.reduce((text, comment) => {
return (
text +
(comment.type === AST_TOKEN_TYPES.Line
? `//${comment.value}`
: `/*${comment.value}*/`) +
'\n'
);
}, '');
const commentsText = comments
.map(({ type, value }) =>
type === AST_TOKEN_TYPES.Line
? `//${value}\n`
: `/*${value}*/\n`,
)
.join('');
// comments should move before export and not between export and interface declaration
fixes.push(fixer.insertTextBefore(node.parent, commentsText));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ function getReportDescriptor(
if (lastOperand.isYoda) {
const unaryOperator =
lastOperand.node.right.type === AST_NODE_TYPES.UnaryExpression
? lastOperand.node.right.operator + ' '
? `${lastOperand.node.right.operator} `
: '';

return {
Expand All @@ -386,7 +386,7 @@ function getReportDescriptor(
}
const unaryOperator =
lastOperand.node.left.type === AST_NODE_TYPES.UnaryExpression
? lastOperand.node.left.operator + ' '
? `${lastOperand.node.left.operator} `
: '';
return {
left: unaryOperator + newCode,
Expand Down
5 changes: 1 addition & 4 deletions packages/eslint-plugin/src/rules/unbound-method.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,7 @@ export default createRule<Options, MessageIds>({
},
messages: {
unbound: BASE_MESSAGE,
unboundWithoutThisAnnotation:
BASE_MESSAGE +
'\n' +
'If your function does not access `this`, you can annotate it with `this: void`, or consider using an arrow function instead.',
unboundWithoutThisAnnotation: `${BASE_MESSAGE}\nIf your function does not access \`this\`, you can annotate it with \`this: void\`, or consider using an arrow function instead.`,
},
schema: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,13 @@ export default createRule<[], MessageIds>({
type: 'suggestion',
messages: {
useUnknown: useUnknownMessageBase,
useUnknownArrayDestructuringPattern:
useUnknownMessageBase + ' The thrown error may not be iterable.',
useUnknownObjectDestructuringPattern:
useUnknownMessageBase +
' The thrown error may be nullable, or may not have the expected shape.',
useUnknownSpreadArgs:
useUnknownMessageBase +
' The argument list may contain a handler that does not use `unknown` for the catch callback variable.',
useUnknownArrayDestructuringPattern: `${useUnknownMessageBase} The thrown error may not be iterable.`,
useUnknownObjectDestructuringPattern: `${
useUnknownMessageBase
} The thrown error may be nullable, or may not have the expected shape.`,
useUnknownSpreadArgs: `${
useUnknownMessageBase
} The argument list may contain a handler that does not use \`unknown\` for the catch callback variable.`,
addUnknownTypeAnnotationSuggestion:
'Add an explicit `: unknown` type annotation to the catch variable.',
addUnknownRestTypeAnnotationSuggestion:
Expand Down
26 changes: 14 additions & 12 deletions packages/eslint-plugin/tests/docs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ function renderLintResults(code: string, errors: Linter.LintMessage[]): string {
? Math.max(1, endColumn - startColumn)
: line.length - startColumn,
);
const squiggleWithIndent = ' '.repeat(startColumn) + squiggle + ' ';
const squiggleWithIndent = `${' '.repeat(startColumn)}${squiggle} `;
const errorMessageIndent = ' '.repeat(squiggleWithIndent.length);
output.push(
squiggleWithIndent +
error.message.split('\n').join('\n' + errorMessageIndent),
error.message.replaceAll('\n', `\n${errorMessageIndent}`),
);
} else if (i === endLine) {
output.push('~'.repeat(endColumn));
Expand All @@ -97,7 +97,7 @@ function renderLintResults(code: string, errors: Linter.LintMessage[]): string {
}
}

return output.join('\n').trim() + '\n';
return `${output.join('\n').trim()}\n`;
}

const linter = new Linter({ configType: 'eslintrc' });
Expand Down Expand Up @@ -484,27 +484,28 @@ describe('Validating rule docs', () => {
if (token.meta?.includes('skipValidation')) {
assert.ok(
messages.length === 0,
'Expected not to contain lint errors (with skipValidation):\n' +
token.value,
`Expected not to contain lint errors (with skipValidation):
${token.value}`,
);
} else {
assert.ok(
messages.length > 0,
'Expected to contain at least 1 lint error:\n' + token.value,
`Expected to contain at least 1 lint error:\n${token.value}`,
);
}
} else {
testCaption.push('Correct');
if (token.meta?.includes('skipValidation')) {
assert.ok(
messages.length > 0,
'Expected to contain at least 1 lint error (with skipValidation):\n' +
token.value,
`Expected to contain at least 1 lint error (with skipValidation):\n${
token.value
}`,
);
} else {
assert.ok(
messages.length === 0,
'Expected not to contain lint errors:\n' + token.value,
`Expected not to contain lint errors:\n${token.value}`,
);
}
}
Expand All @@ -514,9 +515,10 @@ describe('Validating rule docs', () => {
}

expect(
testCaption.filter(Boolean).join('\n') +
'\n\n' +
renderLintResults(token.value, messages),
`${testCaption.filter(Boolean).join('\n')}\n\n${renderLintResults(
token.value,
messages,
)}`,
).toMatchSpecificSnapshot(
path.join(eslintOutputSnapshotFolder, `${ruleName}.shot`),
);
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/tools/generate-breaking-changes.mts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async function main(): Promise<void> {
// But this is an internal-only script and it's the easiest way to convert
// the JS raw text into a runtime object. 🤷
let oldRulesObject!: { rules: TypeScriptESLintRules };
eval('oldRulesObject = ' + oldObjectText);
eval(`oldRulesObject = ${oldObjectText}`);
const oldRuleNames = new Set(Object.keys(oldRulesObject.rules));

// 3. Get the keys that exist in (1) (new version) and not (2) (old version)
Expand Down
2 changes: 1 addition & 1 deletion packages/parser/tests/test-utils/test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,6 @@ export function formatSnapshotName(
fileExtension = '.js',
): string {
return `fixtures/${filename
.replace(fixturesDir + '/', '')
.replace(`${fixturesDir}/`, '')
.replace(fileExtension, '')}`;
}
2 changes: 1 addition & 1 deletion packages/typescript-estree/tests/test-utils/test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function formatSnapshotName(
fileExtension = '.js',
): string {
return `fixtures/${filename
.replace(fixturesDir + '/', '')
.replace(`${fixturesDir}/`, '')
.replace(fileExtension, '')}`;
}

Expand Down
5 changes: 2 additions & 3 deletions packages/utils/tests/eslint-utils/getParserServices.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ const baseErrorRegex = (parser?: string): RegExp =>
new RegExp(requiresParserServicesMessageTemplate(parser));
const unknownParserErrorRegex = (parser?: string): RegExp =>
new RegExp(
requiresParserServicesMessageTemplate(parser) +
'\n' +
'Note: detected a parser other than @typescript-eslint/parser. Make sure the parser is configured to forward "parserOptions.project" to @typescript-eslint/parser.',
`${requiresParserServicesMessageTemplate(parser)}
Note: detected a parser other than @typescript-eslint/parser. Make sure the parser is configured to forward "parserOptions.project" to @typescript-eslint/parser.`,
);

describe('getParserServices', () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/website-eslint/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ function makeFilter(filePath: string[] | string): { filter: RegExp } {
const norm = paths.map(item =>
normalizePath(item).replace(/\//g, '[\\\\/]').replace(/\./g, '\\.'),
);
return { filter: new RegExp('(' + norm.join('|') + ')$') };
return { filter: new RegExp(`(${norm.join('|')})$`) };
}

function createResolve(
targetPath: string,
join: string,
): esbuild.OnResolveResult {
const resolvedPackage = requireResolved(targetPath + '/package.json');
const resolvedPackage = requireResolved(`${targetPath}/package.json`);
return {
path: path.join(resolvedPackage, '../src/', join),
};
Expand Down
2 changes: 1 addition & 1 deletion packages/website-eslint/src/mock/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class AssertionError extends Error {
typeof stackStartFunction === 'function'
? stackStartFunction.name
: stackStartFunction.toString();
const idx = out.indexOf('\n' + fn_name);
const idx = out.indexOf(`\n${fn_name}`);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
Expand Down
2 changes: 1 addition & 1 deletion packages/website-eslint/src/mock/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export function resolve(...args) {
continue;
}

resolvedPath = path + '/' + resolvedPath;
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = path.charAt(0) === '/';
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export function createTwoslashInlayProvider(
const inspectionOff = model.getOffsetAt(inspectionPos);

const hint = await (worker.getQuickInfoAtPosition(
'file://' + model.uri.path,
`file://${model.uri.path}`,
inspectionOff,
) as Promise<ts.QuickInfo | undefined>);
if (!hint?.displayParts) {
Expand All @@ -80,7 +80,7 @@ export function createTwoslashInlayProvider(
.join('')
.replace(/\r?\n\s*/g, ' ');
if (text.length > 120) {
text = text.slice(0, 119) + '...';
text = `${text.slice(0, 119)}...`;
}

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export const useSandboxServices = (
if (worker.getLibFiles) {
const libs = await worker.getLibFiles();
for (const [key, value] of Object.entries(libs)) {
system.writeFile('/' + key, value);
system.writeFile(`/${key}`, value);
}
}

Expand Down
6 changes: 2 additions & 4 deletions packages/website/tools/generate-website-dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,8 @@ function replaceImports(text: string, from: string, to: string): string {
function injectImports(text: string, from: string, safeName: string): string {
const regex = new RegExp(`import\\(["']${from}["']\\)`, 'g');
if (regex.test(text)) {
return (
`import type * as ${safeName} from '${from}';\n` +
text.replace(regex, safeName)
);
return `import type * as ${safeName} from '${from}';
${text.replace(regex, safeName)}`;
}
return text;
}
Expand Down

0 comments on commit 243fb5f

Please sign in to comment.