Skip to content

Commit

Permalink
refactor: Manually resolve remaining ESLint errors and correct autofixes
Browse files Browse the repository at this point in the history
  • Loading branch information
RandomByte committed Mar 12, 2024
1 parent e517f12 commit 87bf6c9
Show file tree
Hide file tree
Showing 32 changed files with 134 additions and 110 deletions.
2 changes: 1 addition & 1 deletion scripts/metadataProvider/createMetadataInfo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {writeFile} from "node:fs/promises";
import MetadataProvider from "./MetadataProvider";
import MetadataProvider from "./MetadataProvider.js";

import {
forEachSymbol,
Expand Down
1 change: 1 addition & 0 deletions scripts/metadataProvider/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export async function createSemanticModel(apiJsonsRoot: string): Promise<UI5Sema
// Overwrite console.error with a noop since #generate produces a lot of messages error messages
// that we don't want to deal with right now
originalConsoleError = console.error;
// eslint-disable-next-line @typescript-eslint/no-empty-function
console.error = () => {};
}
model = generate({
Expand Down
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ export default async function () {
// await cli.parse();
// yargs registers a get method on the argv property.
// The property needs to be accessed to initialize everything.
cli.argv;
await cli.argv;
}
33 changes: 23 additions & 10 deletions src/cli/base.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Argv, ArgumentsCamelCase} from "yargs";
import {Argv, ArgumentsCamelCase, CommandModule, MiddlewareFunction} from "yargs";
import path from "node:path";
import {lintProject} from "../linter/linter.js";
import {Text} from "../formatter/text.js";
Expand All @@ -10,13 +10,25 @@ import chalk from "chalk";
import {isLogLevelEnabled} from "@ui5/logger";
import ConsoleWriter from "@ui5/logger/writers/Console";

const lintCommand = {
export interface LinterArg {
coverage: boolean;
filePaths: string[];
details: boolean;
format: string;
}

// yargs type defition is missing the "middelwares" property for the CommandModule type
interface FixedCommandModule<T, U> extends CommandModule<T, U> {
middlewares: MiddlewareFunction<U>[];
}

const lintCommand: FixedCommandModule<object, LinterArg> = {
command: "$0",
describe: "Runs linter",
handler: handleLint,
middlewares: [baseMiddleware],
builder: function (cli: Argv) {
cli.usage("Usage: $0 [options]")
builder: function (args: Argv<object>): Argv<LinterArg> {
args.usage("Usage: $0 [options]")
.option("file-paths", {
describe: "",
type: "string",
Expand Down Expand Up @@ -62,7 +74,7 @@ const lintCommand = {
.coerce([
// base.js
"log-level",
], (arg) => {
], (arg: LinterArg[]) => {
// If an option is specified multiple times, yargs creates an array for all the values,
// independently of whether the option is of type "array" or "string".
// This is unexpected for options listed above, which should all only have only one
Expand All @@ -74,6 +86,7 @@ const lintCommand = {
// Note: This is not necessary for options of type "boolean"
if (Array.isArray(arg)) {
// If the option is specified multiple times, use the value of the last option
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return arg[arg.length - 1];
}
return arg;
Expand All @@ -83,17 +96,17 @@ const lintCommand = {
.example("ui5lint --file-paths /path/to/resources",
"Execute command with scope of file-paths");

return cli;
return args as Argv<LinterArg>;
},
};

async function handleLint(argv: ArgumentsCamelCase) {
async function handleLint(argv: ArgumentsCamelCase<LinterArg>) {
const {
coverage,
filePaths,
details,
format,
} = (argv as unknown) as {coverage: boolean; filePaths: string[]; details: boolean; format: string};
} = argv;

let profile;
if (process.env.UI5LINT_PROFILE) {
Expand All @@ -103,10 +116,10 @@ async function handleLint(argv: ArgumentsCamelCase) {

const res = await lintProject({
rootDir: path.join(process.cwd()),
filePaths: filePaths && filePaths.map((filePath) => path.resolve(process.cwd(), filePath)),
filePaths: filePaths?.map((filePath) => path.resolve(process.cwd(), filePath)),
});

if (process.env.UI5LINT_COVERAGE_REPORT || coverage) {
if (process.env.UI5LINT_COVERAGE_REPORT ?? coverage) {
const coverageFormatter = new Coverage();
await writeFile("ui5lint-report.html", await coverageFormatter.format(res));
}
Expand Down
7 changes: 2 additions & 5 deletions src/cli/middlewares/base.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import {initLogger} from "./logger.js";
import type {ArgumentsCamelCase} from "yargs";
import type {LinterArg} from "../base.ts";
/**
* Base middleware for CLI commands.
*
* This middleware should be executed for every CLI command to enable basic features (e.g. logging).
*
* @param {object} argv The CLI arguments
* @returns {object}
*/
export default async function (argv: ArgumentsCamelCase) {
export default async function (argv: ArgumentsCamelCase<LinterArg>) {
await initLogger(argv);
return {};
}
2 changes: 1 addition & 1 deletion src/cli/middlewares/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import type {ArgumentsCamelCase} from "yargs";
/**
* Logger middleware to enable logging capabilities
*
* @param {object} argv logger arguments
*/
// eslint-disable-next-line @typescript-eslint/require-await
export async function initLogger(argv: ArgumentsCamelCase) {
if (argv.silent) {
setLogLevel("silent");
Expand Down
3 changes: 2 additions & 1 deletion src/cli/utils/profile.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
import {writeFile} from "node:fs/promises";
import {Session, Profiler} from "node:inspector";
import {getLogger} from "@ui5/logger";
Expand Down Expand Up @@ -72,7 +73,7 @@ function registerSigHooks() {
function createListener(exitCode: number) {
return function () {
// Gracefully end profiling, then exit
stop().then(() => {
void stop().then(() => {
process.exit(exitCode);
});
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ function collectImports(
moduleSpecifier = nodeFactory.createStringLiteral(dep.text);
// Set pos to the original position to preserve source mapping capability
// (cast type to avoid TS error due to modifying a read only property)
(moduleSpecifier.pos) = dep.pos;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
(moduleSpecifier.pos as ts.Node["pos"]) = dep.pos;
} else {
moduleSpecifier = dep;
}
Expand Down
5 changes: 3 additions & 2 deletions src/detectors/transpilers/amd/parseModuleDeclaration.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */
import ts from "typescript";
import {getLogger} from "@ui5/logger";
import {UnsupportedModuleError} from "./util.js";
Expand Down Expand Up @@ -109,7 +110,7 @@ function assertSupportedTypes(args: (ts.Expression | ts.Declaration)[]): DefineC

const enum Param {
ModuleName = 0,
Dependencies = 1,
Dependencies = 1,
Factory = 2,
Export = 3,
}
Expand Down Expand Up @@ -201,7 +202,7 @@ export function _matchArgumentsToParameters(args: DefineCallArgument[]): ModuleD
// Compute which parameters the given argument could match with based on it's type
// For example an ArrayLiteralExpression could only be the dependencies or the factory parameter
function permute(arg: DefineCallArgument, startAt: Param): number[] {
const perm = Array(4).fill(0);
const perm = Array(4).fill(0) as number[];

if (startAt <= Param.ModuleName && canBeModuleName(arg)) {
perm[0] = 1;
Expand Down
2 changes: 1 addition & 1 deletion src/detectors/transpilers/amd/replaceNodeInParent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ function replaceInPropertyDeclaration(
node,
node.modifiers,
node.name,
node.questionToken || node.exclamationToken,
node.questionToken ?? node.exclamationToken,
node.type,
substitute);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ export function transformAsyncRequireCall(
moduleSpecifier = nodeFactory.createStringLiteral(dep.text);
// Set pos to the original position to preserve source mapping capability
// (cast type to avoid TS error due to modifying a read only property)
(moduleSpecifier.pos) = dep.pos;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
(moduleSpecifier.pos as ts.Node["pos"]) = dep.pos;
} else {
moduleSpecifier = dep;
}
Expand Down
2 changes: 1 addition & 1 deletion src/detectors/transpilers/xml/Parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ export default class Parser {
start: toPosition(tag.openStart),
end: toPosition(tag.openEnd),
};
if (customDataElements && customDataElements.length) {
if (customDataElements?.length) {
node.aggregations.set("customData", {
kind: NodeKind.Aggregation,
name: "customData",
Expand Down
2 changes: 1 addition & 1 deletion src/detectors/transpilers/xml/generator/Writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export default class Writer {

#addMapping(sourcePos: Position, targetPos?: Position) {
this.#mappings.add({
generated: targetPos || {
generated: targetPos ?? {
line: this.lineOffset,
column: this.columnOffset,
},
Expand Down
5 changes: 3 additions & 2 deletions src/detectors/transpilers/xml/transpiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export async function xmlToJs(resourceName: string, contentStream: ReadStream):

let initializing: Promise<void>;
async function init() {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
if (initializing) {
return initializing;
}
Expand All @@ -55,9 +56,9 @@ async function init() {
return initializing = Promise.all([
fs.readFile(saxPath),
fs.readFile(new URL("../../../../resources/api-extract.json", import.meta.url), {encoding: "utf-8"}),
]).then(async (results) => {
]).then((results) => {
saxWasmBuffer = results[0];
apiExtract = JSON.parse(results[1]);
apiExtract = JSON.parse(results[1]) as ApiExtract;
taskEnd();
});
}
Expand Down
7 changes: 4 additions & 3 deletions src/detectors/typeChecker/FileLinter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export default class FileLinter {
this.#boundVisitNode = this.visitNode.bind(this);
}

// eslint-disable-next-line @typescript-eslint/require-await
async getReport(): Promise<LintResult> {
try {
this.visitNode(this.#sourceFile);
Expand Down Expand Up @@ -96,7 +97,7 @@ export default class FileLinter {
node: prop,
severity: LintMessageSeverity.Error,
ruleId: "ui5-linter-no-deprecated-api",
message: `Use of deprecated property '${propertySymbol.escapedName}' ` +
message: `Use of deprecated property '${propertySymbol.escapedName as string}' ` +
`of class '${this.#checker.typeToString(nodeType)}'`,
messageDetails: this.extractDeprecatedMessage(propertySymbol),
});
Expand Down Expand Up @@ -196,7 +197,7 @@ export default class FileLinter {
ruleId: "ui5-linter-no-deprecated-api",
message:
`Call to deprecated function ` +
`'${symbol.escapedName}'${additionalMessage}`,
`'${symbol.escapedName as string}'${additionalMessage}`,
messageDetails: this.extractDeprecatedMessage(symbol),
});
}
Expand Down Expand Up @@ -234,7 +235,7 @@ export default class FileLinter {
ruleId: "ui5-linter-no-deprecated-property",
message:
`Access of deprecated property ` +
`'${symbol.escapedName}'`,
`'${symbol.escapedName as string}'`,
messageDetails: this.extractDeprecatedMessage(symbol),
});
}
Expand Down
10 changes: 7 additions & 3 deletions src/detectors/typeChecker/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import posixPath from "node:path/posix";
import {fileURLToPath} from "node:url";
import fs from "node:fs/promises";

interface PackageJson {
dependencies: Record<string, string>;
}

function notImplemented(methodName: string) {
throw new Error(`Not implemented: ${methodName}`);
}
Expand All @@ -15,7 +19,7 @@ function addPathMappingForPackage(pkgName: string, pathMapping: Map<string, stri

async function collectTransitiveDependencies(pkgName: string, deps: Set<string>): Promise<Set<string>> {
const pkgJsonPath = fileURLToPath(import.meta.resolve(`${pkgName}/package.json`));
const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, "utf8"));
const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, "utf8")) as PackageJson;
if (pkgJson.dependencies) {
await Promise.all(Object.keys(pkgJson.dependencies).map(async (depName) => {
deps.add(depName);
Expand Down Expand Up @@ -137,7 +141,7 @@ export async function createVirtualCompilerHost(
}
return false;
},
getCurrentDirectory: () => options.rootDir || "/",
getCurrentDirectory: () => options.rootDir ?? "/",
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getDirectories: (directory: string) => {
// This function seems to be called only if the "types" option is not set
Expand All @@ -152,7 +156,7 @@ export async function createVirtualCompilerHost(
// This function doesn't seem to be called during normal operations
// console.log(`readDirectory: ${dirPath}`);
return Array.from(files.keys()).filter((filePath) => {
if (include || exclude || depth || extensions) {
if (include ?? exclude ?? depth ?? extensions) {
notImplemented("readDirectory: Optional parameters");
}
return posixPath.dirname(filePath) === dirPath;
Expand Down
4 changes: 2 additions & 2 deletions src/detectors/typeChecker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export class TsProjectDetector extends ProjectBasedDetector {
try {
if (resourcePath.endsWith(".xml")) {
resourcePath = resourcePath.replace(/\.xml$/, ".js");
const resourceContent = await resource.getStream();
const resourceContent = resource.getStream();
({source, map, messages} =
await xmlToJs(path.basename(originalResourcePath), resourceContent));
} else if (resourcePath.endsWith(".js")) {
Expand Down Expand Up @@ -193,7 +193,7 @@ export class TsProjectDetector extends ProjectBasedDetector {
(and check the resulting path is within the projectPath)
*/
let resourcePaths: (string | undefined)[];
if (filePaths && filePaths.length) {
if (filePaths?.length) {
const absoluteFilePaths = filePaths.map((filePath) => {
if (!path.isAbsolute(filePath)) {
// Resolve relative filePaths
Expand Down
2 changes: 1 addition & 1 deletion src/formatter/coverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function formatSeverity(severity: LintMessageSeverity) {
} else if (severity === LintMessageSeverity.Warning) {
return "warning";
} else {
throw new Error(`Unknown severity: ${severity}`);
throw new Error(`Unknown severity: ${LintMessageSeverity[severity]}`);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/formatter/lib/resolveLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function JSDocUtil():
/(<pre>)|(<\/pre>)|(<h[\d+]>)|(<\/h[\d+]>)|\{@link\s+([^}\s]+)(?:\s+([^}]*))?\}|((?:\r\n|\r|\n)[ \t]*(?:\r\n|\r|\n))/gi;
let inpre = false;
src = src || "";
src = src.replace(r, function (match, pre, endpre, header, endheader, linkTarget, linkText) {
src = src.replace(r, function (match, pre, endpre, header, endheader, linkTarget: string, linkText: string) {
if (pre) {
inpre = true;
} else if (endpre) {
Expand Down Expand Up @@ -252,7 +252,7 @@ function _preProcessLinksInTextBlock(sText: string, ui5Url: string): string {
const aTarget = sTarget.split(".");
if (aTarget.length >= 3) {
const constructorName = aTarget.find((el) => el.toLowerCase() !== el);
let index = aTarget.indexOf(constructorName || "");
let index = aTarget.indexOf(constructorName ?? "");
index = (index === -1) ? aTarget.length : (index + 1);
// Lacking of complimentary information for the type, then construct the
// link to the class name, so the user could find the information on their own.
Expand Down
2 changes: 1 addition & 1 deletion src/formatter/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ function formatSeverity(severity: LintMessageSeverity) {
} else if (severity === LintMessageSeverity.Warning) {
return chalk.yellow("warning");
} else {
throw new Error(`Unknown severity: ${severity}`);
throw new Error(`Unknown severity: ${LintMessageSeverity[severity]}`);
}
}

Expand Down
Loading

0 comments on commit 87bf6c9

Please sign in to comment.