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

fix: reading tsconfig file and compilerOptions, prettier supressTypeErrors message #2053

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
"commander": "12.1.0",
"enquirer": "2.4.1",
"glob": "11.0.0",
"minimatch": "10.0.1",
"strip-ansi": "7.1.0",
"ts-api-utils": "2.0.0"
},
Expand All @@ -57,7 +56,6 @@
"@release-it/conventional-changelog": "9.0.3",
"@types/eslint-plugin-markdown": "2.0.2",
"@types/glob": "8.1.0",
"@types/minimatch": "5.1.2",
"@types/node": "22.10.1",
"@types/prop-types": "15.7.13",
"@types/react": "18.3.12",
Expand Down
6 changes: 0 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions src/cleanups/builtin/suppressTypeErrors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
DiagnosticWithStart,
getLineForDiagnostic,
isDiagnosticWithStart,
stringifyDiagnosticMessageText,
userFriendlyDiagnosticMessageText,
} from "../../../shared/diagnostics.js";
import { FileMutator } from "../../../shared/fileMutator.js";

Expand Down Expand Up @@ -33,8 +33,14 @@ export const suppressRemainingTypeIssues: FileMutator = (request) => {
}
}

const currentDir = request.services.program.getCurrentDirectory();

return Array.from(diagnosticsPerLine).map(([line, diagnostics]) => {
const messages = diagnostics.map(stringifyDiagnosticMessageText).join(" ");
const messages = diagnostics
.map((diagnostic) =>
userFriendlyDiagnosticMessageText(diagnostic, currentDir),
)
.join(" ");
return {
insertion: `// @ts-expect-error -- TODO: ${messages}\n`,
range: {
Expand Down
19 changes: 11 additions & 8 deletions src/options/fillOutRawOptions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ProcessOutput } from "../output/types.js";
import { collectOptionals } from "../shared/arrays.js";
import { ReactPropTypesHint, ReactPropTypesOptionality } from "./enums.js";
import { ParsedCompilerOptions } from "./parseRawCompilerOptions.js";
import { ParsedTsConfig } from "./parseRawCompilerOptions.js";
import { collectAddedMutators } from "./parsing/collectAddedMutators.js";
import { collectFileOptions } from "./parsing/collectFileOptions.js";
import { collectNoImplicitAny } from "./parsing/collectNoImplicitAny.js";
Expand All @@ -11,29 +11,32 @@ import { collectStrictNullChecks } from "./parsing/collectStrictNullChecks.js";
import { PendingTypeStatOptions, RawTypeStatOptions } from "./types.js";

export interface OptionsFromRawOptionsSettings {
compilerOptions: Readonly<ParsedCompilerOptions>;
cwd: string;
output: ProcessOutput;
projectPath: string;
rawOptions: RawTypeStatOptions;
tsConfig: Readonly<ParsedTsConfig>;
}

/**
* Combines Node and CLi argument options with project and file metadata into pending TypeStat options.
* @returns Parsed TypeStat options, or a string for an error complaint.
*/
export const fillOutRawOptions = ({
compilerOptions,
cwd,
output,
projectPath,
rawOptions,
tsConfig,
}: OptionsFromRawOptionsSettings): PendingTypeStatOptions => {
const rawOptionTypes = rawOptions.types ?? {};
const compilerOptions = tsConfig.compilerOptions;
const noImplicitAny = collectNoImplicitAny(compilerOptions, rawOptions);
const noImplicitThis = collectNoImplicitThis(compilerOptions, rawOptions);
const { compilerStrictNullChecks, typeStrictNullChecks } =
collectStrictNullChecks(compilerOptions, rawOptionTypes);
const strictNullChecks = collectStrictNullChecks(
compilerOptions,
rawOptionTypes,
);

const packageOptions = collectPackageOptions(cwd, rawOptions);

Expand All @@ -51,7 +54,7 @@ export const fillOutRawOptions = ({
...compilerOptions,
noImplicitAny,
noImplicitThis,
strictNullChecks: compilerStrictNullChecks,
strictNullChecks,
},
files: collectFileOptions(rawOptions),
filters: collectOptionals(rawOptions.filters),
Expand All @@ -74,7 +77,7 @@ export const fillOutRawOptions = ({
ReactPropTypesOptionality.AsWritten,
},
},
include: rawOptions.include ?? compilerOptions.include,
include: rawOptions.include ?? tsConfig.include,
mutators: collectAddedMutators(
rawOptions,
packageOptions.directory,
Expand All @@ -85,7 +88,7 @@ export const fillOutRawOptions = ({
postProcess: { shell },
projectPath,
types: {
strictNullChecks: typeStrictNullChecks,
strictNullChecks,
},
};
};
6 changes: 3 additions & 3 deletions src/options/loadPendingOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { fillOutRawOptions } from "./fillOutRawOptions.js";
import { findRawOptions } from "./findRawOptions.js";
import { findComplaintForOptions } from "./optionVerification.js";
import { parseRawCompilerOptions } from "./parseRawCompilerOptions.js";
import { parseRawTsConfig } from "./parseRawCompilerOptions.js";
import { PendingTypeStatOptions, RawTypeStatOptions } from "./types.js";

/**
Expand Down Expand Up @@ -34,14 +34,14 @@
for (let i = 0; i < allRawOptions.length; i += 1) {
const rawOptions = allRawOptions[i];
const projectPath = getProjectPath(cwd, filePath, rawOptions);
const compilerOptions = await parseRawCompilerOptions(cwd, projectPath);
const tsConfig = await parseRawTsConfig(cwd, projectPath);

Check warning on line 37 in src/options/loadPendingOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/options/loadPendingOptions.ts#L37

Added line #L37 was not covered by tests

const filledOutOptions = fillOutRawOptions({
compilerOptions,
cwd,
output,
projectPath,
rawOptions,
tsConfig,

Check warning on line 44 in src/options/loadPendingOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/options/loadPendingOptions.ts#L44

Added line #L44 was not covered by tests
});
const complaint = findComplaintForOptions(filledOutOptions);
if (complaint) {
Expand Down
46 changes: 17 additions & 29 deletions src/options/parseRawCompilerOptions.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,37 @@
import { glob } from "glob";
import { minimatch } from "minimatch";
import * as fs from "node:fs";
import * as fsp from "node:fs/promises";
import * as path from "node:path";
import ts from "typescript";

import { createParseConfigHost } from "../services/createParseConfigHost.js";
import { stringifyDiagnosticMessageText } from "../shared/diagnostics.js";

export interface ParsedCompilerOptions extends ts.CompilerOptions {
export interface ParsedTsConfig {
compilerOptions: ts.CompilerOptions;
include?: string[];
}

export const parseRawCompilerOptions = async (
export const parseRawTsConfig = async (
cwd: string,
projectPath: string,
): Promise<ts.CompilerOptions> => {
): Promise<ParsedTsConfig> => {
const configRaw = (await fsp.readFile(projectPath)).toString();
const compilerOptions = ts.parseConfigFileTextToJson(projectPath, configRaw);
if (compilerOptions.error !== undefined) {
const configResult = ts.parseConfigFileTextToJson(projectPath, configRaw);
if (configResult.error !== undefined) {
throw new Error(
`Could not parse compiler options from '${projectPath}': ${stringifyDiagnosticMessageText(compilerOptions.error)}`,
`Could not parse compiler options from '${projectPath}': ${stringifyDiagnosticMessageText(configResult.error)}`,

Check warning on line 20 in src/options/parseRawCompilerOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/options/parseRawCompilerOptions.ts#L20

Added line #L20 was not covered by tests
);
}

const config = compilerOptions.config as ParsedCompilerOptions;
const config = configResult.config as ParsedTsConfig;

// TSConfig includes often come in a glob form like ["src"]
config.include &&= ts.parseJsonConfigFileContent(
compilerOptions.config,
{
fileExists: (filePath) => fs.statSync(filePath).isFile(),
readDirectory: (rootDir, extensions, excludes, includes) =>
includes
.flatMap((include) => glob.sync(path.join(rootDir, include)))
.filter(
(filePath) =>
!excludes?.some((exclude) => minimatch(filePath, exclude)) &&
extensions.some((extension) => filePath.endsWith(extension)),
)
.map((filePath) => path.relative(rootDir, filePath)),
readFile: (filePath) => fs.readFileSync(filePath).toString(),
useCaseSensitiveFileNames: true,
},
const parserConfig = ts.parseJsonConfigFileContent(
configResult.config,
createParseConfigHost(),
cwd,
).fileNames;
);

// TSConfig includes often come in a glob form like ["src"]
config.include &&= parserConfig.fileNames;
config.compilerOptions = parserConfig.options;

return config;
};
15 changes: 3 additions & 12 deletions src/options/parsing/collectNoImplicitAny.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,7 @@ import ts from "typescript";
import { RawTypeStatOptions } from "../types.js";

export const collectNoImplicitAny = (
compilerOptions: Readonly<ts.CompilerOptions>,
compilerOptions: Readonly<ts.CompilerOptions> | undefined,
rawOptions: RawTypeStatOptions,
): boolean => {
if (rawOptions.fixes?.noImplicitAny !== undefined) {
return rawOptions.fixes.noImplicitAny;
}

if (compilerOptions.noImplicitAny !== undefined) {
return compilerOptions.noImplicitAny;
}

return false;
};
): boolean =>
rawOptions.fixes?.noImplicitAny || compilerOptions?.noImplicitAny || false;
15 changes: 3 additions & 12 deletions src/options/parsing/collectNoImplicitThis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,7 @@ import ts from "typescript";
import { RawTypeStatOptions } from "../types.js";

export const collectNoImplicitThis = (
compilerOptions: Readonly<ts.CompilerOptions>,
compilerOptions: Readonly<ts.CompilerOptions> | undefined,
rawOptions: RawTypeStatOptions,
): boolean => {
if (rawOptions.fixes?.noImplicitThis !== undefined) {
return rawOptions.fixes.noImplicitThis;
}

if (compilerOptions.noImplicitThis !== undefined) {
return compilerOptions.noImplicitThis;
}

return false;
};
): boolean =>
rawOptions.fixes?.noImplicitThis || compilerOptions?.noImplicitThis || false;
35 changes: 6 additions & 29 deletions src/options/parsing/collectStrictNullChecks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,10 @@ import ts from "typescript";
import { RawTypeStatTypeOptions } from "../types.js";

export const collectStrictNullChecks = (
compilerOptions: Readonly<ts.CompilerOptions>,
compilerOptions: Readonly<ts.CompilerOptions> | undefined,
rawOptionTypes: RawTypeStatTypeOptions,
) => {
const typeStrictNullChecks = rawOptionTypes.strictNullChecks;
const compilerStrictNullChecks = collectCompilerStrictNullChecks(
compilerOptions,
typeStrictNullChecks,
);

return { compilerStrictNullChecks, typeStrictNullChecks };
};

const collectCompilerStrictNullChecks = (
compilerOptions: Readonly<ts.CompilerOptions>,
typeStrictNullChecks: boolean | undefined,
): boolean => {
if (typeStrictNullChecks !== undefined) {
return typeStrictNullChecks;
}

if (compilerOptions.strictNullChecks !== undefined) {
return compilerOptions.strictNullChecks;
}

if (compilerOptions.strict !== undefined) {
return compilerOptions.strict;
}

return false;
};
): boolean =>
rawOptionTypes.strictNullChecks ||
compilerOptions?.strictNullChecks ||
compilerOptions?.strict ||
false;
11 changes: 1 addition & 10 deletions src/options/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export interface BaseTypeStatOptions {
/**
* Parsed TypeScript compiler options with relevant fields filled out.
*/
readonly compilerOptions: Readonly<TypeStatCompilerOptions>;
readonly compilerOptions: Readonly<ts.CompilerOptions>;

/**
* Directives for file-level changes.
Expand Down Expand Up @@ -161,15 +161,6 @@ export interface TypeStatOptions extends BaseTypeStatOptions {
readonly fileNames: readonly string[];
}

/**
* Parsed TypeScript compiler options with relevant fields filled out.
*/
export type TypeStatCompilerOptions = ts.CompilerOptions & {
noImplicitAny: boolean;
noImplicitThis: boolean;
strictNullChecks: boolean;
};

/**
* Directives for file-level changes.
*/
Expand Down
18 changes: 18 additions & 0 deletions src/services/createParseConfigHost.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import ts from "typescript";

export const createParseConfigHost = (): ts.ParseConfigHost => {
return {
// eslint-disable-next-line @typescript-eslint/unbound-method
directoryExists: ts.sys.directoryExists,
// eslint-disable-next-line @typescript-eslint/unbound-method
fileExists: ts.sys.fileExists,
getCurrentDirectory: () => process.cwd(),
// eslint-disable-next-line @typescript-eslint/unbound-method
getDirectories: ts.sys.getDirectories,
// eslint-disable-next-line @typescript-eslint/unbound-method
readDirectory: ts.sys.readDirectory,
// eslint-disable-next-line @typescript-eslint/unbound-method
readFile: ts.sys.readFile,
useCaseSensitiveFileNames: true,
};
};
10 changes: 2 additions & 8 deletions src/services/createProgramConfiguration.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as fs from "node:fs";
import * as path from "node:path";
import ts from "typescript";

import { TypeStatOptions } from "../options/types.js";
import { collectOptionals, uniquify } from "../shared/arrays.js";
import { normalizeAndSlashify } from "../shared/paths.js";
import { createParseConfigHost } from "./createParseConfigHost.js";

export const createProgramConfiguration = (options: TypeStatOptions) => {
// Create a TypeScript configuration using the raw options
Expand All @@ -13,13 +13,7 @@ export const createProgramConfiguration = (options: TypeStatOptions) => {
...options.compilerOptions,
skipLibCheck: true,
},
{
fileExists: fs.existsSync,
// eslint-disable-next-line @typescript-eslint/unbound-method
readDirectory: ts.sys.readDirectory,
readFile: (file) => fs.readFileSync(file, "utf8"),
useCaseSensitiveFileNames: true,
},
createParseConfigHost(),
path.resolve(path.dirname(options.projectPath)),
{ noEmit: true },
);
Expand Down
Loading
Loading