Skip to content

Commit

Permalink
Enable eslint strict type checks (#1561)
Browse files Browse the repository at this point in the history
  • Loading branch information
tanwigeetika1618 authored Oct 9, 2024
1 parent 6e92107 commit c1671de
Show file tree
Hide file tree
Showing 52 changed files with 195 additions and 153 deletions.
27 changes: 24 additions & 3 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default tseslint.config(
{
extends: [
eslint.configs.recommended,
...tseslint.configs.recommended, // TODO: switch to strictTypeChecked
...tseslint.configs.strictTypeChecked,
prettierRecommendedConfig,
],
files: [
Expand Down Expand Up @@ -48,16 +48,37 @@ export default tseslint.config(
},
rules: {
eqeqeq: ["error", "smart"],
// Needed for tseslint.configs.strictTypeChecked
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unnecessary-condition": "off",
"@typescript-eslint/use-unknown-in-catch-callback-variable": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"@typescript-eslint/prefer-promise-reject-errors": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-base-to-string": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-redundant-type-constituents": "off",
"@typescript-eslint/no-confusing-void-expression": "off",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/require-await": "off",
"@typescript-eslint/restrict-plus-operands": "off",
"@typescript-eslint/no-dynamic-delete": "off",
"@typescript-eslint/no-unsafe-enum-comparison": "off",
"@typescript-eslint/prefer-literal-enum-member": "off",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/only-throw-error": "off",
"no-case-declarations": "error",
"no-constant-condition": "error",
"no-control-regex": "error",
"no-empty-function": "error",
"no-prototype-builtins": "error",
"tsdoc/syntax": "error",
// Needed for tseslint.configs.strictTypeChecked
// "@typescript-eslint/require-await": "error",
// "@typescript-eslint/await-thenable": "error",
"@typescript-eslint/unbound-method": "error",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,9 @@ export class AnsibleLanguageService {

this.connection.onDidChangeWatchedFiles((params) => {
try {
this.workspaceManager.forEachContext((context) =>
context.handleWatchedDocumentChange(params),
);
this.workspaceManager.forEachContext((context) => {
context.handleWatchedDocumentChange(params);
});
} catch (error) {
this.handleError(error, "onDidChangeWatchedFiles");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ export async function doCompletionResolve(
completionItem.data.firstElementOfList,
isAnsiblePlaybook,
)}`
: `${completionItem.label}`;
: completionItem.label;

if (completionItem.textEdit) {
completionItem.textEdit.newText = insertText;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ function parseInventoryHosts(hostObj: inventoryType): HostType[] {
);

const groupsHavingChildren = topLevelGroups.filter(
(item) => hostObj[`${item}`] && hostObj[`${item}`].children,
(item) => hostObj[item] && hostObj[item].children,
);

const otherGroups = getChildGroups(groupsHavingChildren, hostObj);
Expand Down Expand Up @@ -188,8 +188,8 @@ function parseInventoryHosts(hostObj: inventoryType): HostType[] {
let allHosts = [localhostObj, allHostObj, ...ungroupedHostsObjList];

for (const group of allGroups) {
if (hostObj[`${group.host}`] && hostObj[`${group.host}`].hosts) {
const hostsObj = hostObj[`${group.host}`].hosts.map((item) => {
if (hostObj[group.host] && hostObj[group.host].hosts) {
const hostsObj = hostObj[group.host].hosts.map((item) => {
return { host: item, priority: 4 };
});
allHosts = [...allHosts, ...hostsObj];
Expand All @@ -205,8 +205,8 @@ function getChildGroups(
res: string[] = [],
): string[] {
for (const host of groupList) {
if (hostObj[`${host}`].children) {
getChildGroups(hostObj[`${host}`].children, hostObj, res);
if (hostObj[host].children) {
getChildGroups(hostObj[host].children, hostObj, res);
} else {
res.push(host);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class ExecutionEnvironment {
this.settings.executionEnvironment.volumeMounts;

const setEngineSuccess = this.setContainerEngine();
if (setEngineSuccess === false) {
if (!setEngineSuccess) {
this.isServiceInitialized = false;
return;
}
Expand All @@ -61,7 +61,7 @@ export class ExecutionEnvironment {
this.settings.executionEnvironment.containerOptions;

const pullSuccess = await this.pullContainerImage();
if (pullSuccess === false) {
if (!pullSuccess) {
this.isServiceInitialized = false;
return;
}
Expand All @@ -85,10 +85,7 @@ export class ExecutionEnvironment {
);
return;
}
const containerName = `${this._container_image.replace(
/[^a-z0-9]/gi,
"_",
)}`;
const containerName = this._container_image.replace(/[^a-z0-9]/gi, "_");
let progressTracker;

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,14 @@ export class SettingsManager {
this.documentSettings = newDocumentSettings;

// fire handlers
handlersToFire.forEach((h) => h());
handlersToFire.forEach((h) => {
h();
});
} else {
if (params.settings.ansible) {
this.configurationChangeHandlers.forEach((h) => h());
this.configurationChangeHandlers.forEach((h) => {
h();
});
}
this.globalSettings = params.settings.ansible || this.defaultSettings;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,9 @@ export class ValidationManager {
public handleDocumentClosed(fileUri: string): void {
const referencedFiles = this.referencedFilesByOrigin.get(fileUri);
if (referencedFiles) {
referencedFiles.forEach((f) => this.handleFileUnreferenced(f));
referencedFiles.forEach((f) => {
this.handleFileUnreferenced(f);
});
// remove the diagnostics origin file from tracking
this.referencedFilesByOrigin.delete(fileUri);
}
Expand Down
8 changes: 4 additions & 4 deletions packages/ansible-language-server/src/utils/docsFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function formatModule(
sections.push("**DEPRECATED**");
if (route?.deprecation) {
if (route.deprecation.warningText) {
sections.push(`${route.deprecation.warningText}`);
sections.push(route.deprecation.warningText);
}
sections.push(
`Removal date: ${route.deprecation.removalDate}, removal version: ${route.deprecation.removalVersion}`,
Expand Down Expand Up @@ -50,16 +50,16 @@ export function formatModule(

export function formatTombstone(route: IPluginRoute): MarkupContent {
const sections: string[] = [];
if (route?.tombstone) {
if (route.tombstone) {
sections.push("**REMOVED**");
if (route.tombstone.warningText) {
sections.push(`${route.tombstone.warningText}`);
sections.push(route.tombstone.warningText);
}
sections.push(
`Removal date: ${route.tombstone.removalDate}, removal version: ${route.tombstone.removalVersion}`,
);
}
if (route?.redirect) {
if (route.redirect) {
sections.push(`Use *${route.redirect}* instead.`);
}
return {
Expand Down
14 changes: 7 additions & 7 deletions packages/ansible-language-server/src/utils/getAnsibleMetaData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,17 +146,17 @@ async function getPythonInfo() {
return pythonInfo;
}

pythonInfo["version"] = pythonVersionResult?.stdout
?.trim()
?.split(" ")
?.pop()
pythonInfo["version"] = pythonVersionResult.stdout
.trim()
.split(" ")
.pop()
?.trim();

const pythonPathResult = await getResultsThroughCommandRunner(
"python3",
'-c "import sys; print(sys.executable)"',
);
pythonInfo["location"] = pythonPathResult?.stdout?.trim();
pythonInfo["location"] = pythonPathResult?.stdout.trim();

return pythonInfo;
}
Expand Down Expand Up @@ -192,11 +192,11 @@ async function getAnsibleLintInfo() {
}

ansibleLintInfo["version"] =
ansibleLintVersion?.split("using")[0]?.trim()?.split(" ")?.pop()?.trim() ||
ansibleLintVersion.split("using")[0]?.trim()?.split(" ")?.pop()?.trim() ||
undefined;

ansibleLintInfo["location"] =
ansibleLintPathResult?.stdout?.trim() || undefined;
ansibleLintPathResult?.stdout.trim() || undefined;

ansibleLintInfo["config file path"] =
context.ansibleLint.ansibleLintConfigFilePath;
Expand Down
4 changes: 2 additions & 2 deletions packages/ansible-language-server/src/utils/yaml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ export function isCursorInsideJinjaBrackets(
position: Position,
path: Node[],
): boolean {
const node = path?.[path?.length - 1];
const node = path[path.length - 1];
let nodeObject: string | string[];

try {
Expand Down Expand Up @@ -641,7 +641,7 @@ export function isCursorInsideJinjaBrackets(
// this is a safety check in case of multiple jinja inline brackets in a single line
let jinjaInlineBracketEndIndex = lineAfterCursor.indexOf(" }}");
if (
lineAfterCursor.indexOf("{{ ") !== -1 &&
lineAfterCursor.includes("{{ ") &&
lineAfterCursor.indexOf("{{ ") < jinjaInlineBracketEndIndex
) {
jinjaInlineBracketEndIndex = -1;
Expand Down
2 changes: 1 addition & 1 deletion packages/ansible-language-server/test/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export function smartFilter(

// Sort completion list based on `sortText` property of the completion item
completionList.sort((a: CompletionItem, b: CompletionItem) =>
a.sortText && b.sortText ? a.sortText.localeCompare(b?.sortText) : 0,
a.sortText && b.sortText ? a.sortText.localeCompare(b.sortText) : 0,
);

// Construct a new Fuse object to do fuzzy search with key as `filterText` property of the completion item
Expand Down
2 changes: 1 addition & 1 deletion packages/ansible-language-server/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const SKIP_PODMAN = (process.env.SKIP_PODMAN ?? "0") === "1";
const SKIP_DOCKER = (process.env.SKIP_DOCKER ?? "0") === "1";
let EE_VERSION = "N/A";
const DEFAULT_CONTAINER =
pkg?.contributes?.configuration[6]?.properties[
pkg.contributes.configuration[6]?.properties[
"ansible.executionEnvironment.image"
]?.default ?? "";

Expand Down
2 changes: 1 addition & 1 deletion packages/ansible-language-server/test/rootMochaHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const mochaHooks = (): Mocha.RootHookObject => {
beforeEach(this: Mocha.Context) {
if (skipEE() && this.currentTest?.fullTitle().includes("@ee")) {
console.warn(
`Skipped test due to environment conditions: ${this.currentTest?.title}`,
`Skipped test due to environment conditions: ${this.currentTest.title}`,
);
this.skip();
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,7 @@ describe("withInterpreter", () => {
if (!actualCommand[1] || typeof expectedEnv === "string") {
expect(false);
} else {
expect(actualCommand[1][key]).to.include(
expectedEnv[key] as string,
);
expect(actualCommand[1][key]).to.include(expectedEnv[key]);
}
});
}
Expand Down
6 changes: 3 additions & 3 deletions src/features/ansibleTox/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ export class AnsibleToxController {
watcher.onDidChange((uri) =>
this.parseTestsInFileContents(this.getOrCreateFile(uri)),
);
watcher.onDidDelete((uri) =>
this.controller.items.delete(uri.toString()),
);
watcher.onDidDelete((uri) => {
this.controller.items.delete(uri.toString());
});
const files = await vscode.workspace.findFiles(pattern);
files.forEach(this.getOrCreateFile);
watchers.push(watcher);
Expand Down
2 changes: 1 addition & 1 deletion src/features/ansibleTox/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export async function getToxEnvs(
channel.appendLine(stderr);
channel.show(true);
}
return stdout?.trim().split(os.EOL);
return stdout.trim().split(os.EOL);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
const channel = getOutputChannel();
Expand Down
8 changes: 7 additions & 1 deletion src/features/contentCreator/createAnsibleCollectionPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ export class CreateAnsibleCollection {
extensionUri,
);
this._setWebviewMessageListener(this._panel.webview);
this._panel.onDidDispose(() => this.dispose(), null, this._disposables);
this._panel.onDidDispose(
() => {
this.dispose();
},
null,
this._disposables,
);
}

public static render(extensionUri: vscode.Uri) {
Expand Down
8 changes: 7 additions & 1 deletion src/features/contentCreator/createAnsibleProjectPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ export class CreateAnsibleProject {
extensionUri,
);
this._setWebviewMessageListener(this._panel.webview);
this._panel.onDidDispose(() => this.dispose(), null, this._disposables);
this._panel.onDidDispose(
() => {
this.dispose();
},
null,
this._disposables,
);
}

public static render(extensionUri: vscode.Uri) {
Expand Down
9 changes: 5 additions & 4 deletions src/features/lightspeed/contentMatchesWebview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { SettingsManager } from "../../settings";
import {
ContentMatchesRequestParams,
ContentMatchesResponseParams,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
IContentMatch,
IContentMatchParams,
ISuggestionDetails,
Expand Down Expand Up @@ -156,7 +157,7 @@ export class ContentMatchesWebview implements vscode.WebviewViewProvider {
private async getErrorWebviewContent(error: IError) {
let detail: unknown = error.detail;
if (typeof error.detail === "string") {
detail = error.detail as string;
detail = error.detail;
} else if (typeof error.detail === "object") {
detail = JSON.stringify(error.detail, undefined, " ");
}
Expand Down Expand Up @@ -246,7 +247,7 @@ export class ContentMatchesWebview implements vscode.WebviewViewProvider {

const contentMatchValue = contentMatchResponses.contentmatches[taskIndex];
contentMatchesHtml += this.renderContentMatchWithTasKDescription(
<IContentMatchParams[]>(<IContentMatch>contentMatchValue).contentmatch,
contentMatchValue.contentmatch,
taskNameDescription || "",
rhUserHasSeat === true,
);
Expand Down Expand Up @@ -289,10 +290,10 @@ export class ContentMatchesWebview implements vscode.WebviewViewProvider {
): string {
let taskContentMatch = "";
for (let index = 0; index < contentMatchesResponse.length; index++) {
taskContentMatch += `${this.renderContentMatches(
taskContentMatch += this.renderContentMatches(
contentMatchesResponse[index],
rhUserHasSeat,
)}`;
);
}

return `
Expand Down
Loading

0 comments on commit c1671de

Please sign in to comment.