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

eslint: no-unsafe-member-access (partial) #1245

Closed
wants to merge 1 commit into from
Closed
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: 1 addition & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export default tseslint.config(
// "@typescript-eslint/require-await": "error",
// "@typescript-eslint/await-thenable": "error",
// "@typescript-eslint/unbound-method": "error",
// "@typescript-eslint/no-unsafe-member-access": "error",
"@typescript-eslint/no-unsafe-member-access": "warn",
// "@typescript-eslint/no-floating-promises": "error",
// "@typescript-eslint/restrict-template-expressions": "error",
// "@typescript-eslint/no-unsafe-argument": "error",
Expand Down
75 changes: 43 additions & 32 deletions packages/ansible-language-server/src/ansibleLanguageService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
CompletionItem,
Connection,
DidChangeConfigurationNotification,
DidChangeWatchedFilesNotification,
Expand Down Expand Up @@ -26,6 +27,11 @@ import { getAnsibleMetaData } from "./utils/getAnsibleMetaData";
import axios from "axios";
import { getBaseUri } from "./utils/webUtils";

export type PlaybookExplanation = {
accessToken: string;
URL: string;
content: string;
};
/**
* Initializes the connection and registers all lifecycle event handlers.
*
Expand Down Expand Up @@ -281,21 +287,23 @@ export class AnsibleLanguageService {
return null;
});

this.connection.onCompletionResolve(async (completionItem) => {
try {
if (completionItem.data?.documentUri) {
const context = this.workspaceManager.getContext(
completionItem.data?.documentUri,
);
if (context) {
return await doCompletionResolve(completionItem, context);
this.connection.onCompletionResolve(
async (completionItem: CompletionItem) => {
try {
if (completionItem.data?.documentUri) {
const context = this.workspaceManager.getContext(
completionItem.data?.documentUri,
);
if (context) {
return await doCompletionResolve(completionItem, context);
}
}
} catch (error) {
this.handleError(error, "onCompletionResolve");
}
} catch (error) {
this.handleError(error, "onCompletionResolve");
}
return completionItem;
});
return completionItem;
},
);

this.connection.onDefinition(async (params) => {
try {
Expand Down Expand Up @@ -352,29 +360,32 @@ export class AnsibleLanguageService {
},
);

this.connection.onRequest("playbook/explanation", async (params) => {
const accessToken: string = params["accessToken"];
const URL: string = params["URL"];
const content: string = params["content"];
this.connection.onRequest(
"playbook/explanation",
async (params: PlaybookExplanation) => {
const accessToken: string = params["accessToken"];
const URL: string = params["URL"];
const content: string = params["content"];

const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
};

const axiosInstance = axios.create({
baseURL: `${getBaseUri(URL)}/api/v0`,
headers: headers,
});
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
};

const explanation: string = await axiosInstance
.post("/ai/explanations/", { content: content })
.then((response) => {
return response.data.content;
const axiosInstance = axios.create({
baseURL: `${getBaseUri(URL)}/api/v0`,
headers: headers,
});

return explanation;
});
const explanation: string = await axiosInstance
.post("/ai/explanations/", { content: content })
.then((response) => {
return response.data.content;
});

return explanation;
},
);

this.connection.onRequest("playbook/summary", async (params) => {
const accessToken: string = params["accessToken"];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ export async function doCompletion(
.map((option, index) => {
// translate option documentation to CompletionItem
const details = getDetails(option.specs);
let priority;
let priority: number;
if (isAlias(option)) {
priority = priorityMap.aliasOption;
} else if (option.specs.required) {
Expand Down Expand Up @@ -363,7 +363,7 @@ export async function doCompletion(
choices.push(defaultChoice);
}
return choices.map((choice, index) => {
let priority;
let priority: number;
if (choice === defaultChoice) {
priority = priorityMap.defaultChoice;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function doValidate(
context?: WorkspaceFolderContext,
connection?: Connection,
): Promise<Map<string, Diagnostic[]>> {
let diagnosticsByFile;
let diagnosticsByFile: Map<string, Diagnostic[]> | undefined;
if (quick || !context) {
// get validation from cache
diagnosticsByFile =
Expand All @@ -34,6 +34,7 @@ export async function doValidate(
} else {
// full validation with ansible-lint or ansible syntax-check (if ansible-lint is not installed or disabled)

let diagnosticsByFile: Map<string, Diagnostic[]>;
const settings = await context.documentSettings.get(textDocument.uri);
if (!settings.validation.enabled) {
connection?.console.log("Validation disabled");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@ import { WorkspaceFolderContext } from "./workspaceManager";
import { CommandRunner } from "../utils/commandRunner";
import { URI } from "vscode-uri";

type AnsibleHost = {
host: string;
priority: number;
};

type AnsibleHostObject = {
[name: string]: {
hosts?: string[];
children?: string[];
};
_meta: object;
};
// & { _meta?: never };
/**
* Class to extend ansible-inventory executable as a service
*/
Expand Down Expand Up @@ -41,9 +54,11 @@ export class AnsibleInventory {
defaultHostListPath,
);

let inventoryHostsObject = [];
let inventoryHostsObject: AnsibleHostObject;
try {
inventoryHostsObject = JSON.parse(ansibleInventoryResult.stdout);
inventoryHostsObject = JSON.parse(
ansibleInventoryResult.stdout,
) as AnsibleHostObject;
} catch (error) {
this.connection.console.error(
`Exception in AnsibleInventory service: ${JSON.stringify(error)}`,
Expand All @@ -64,7 +79,7 @@ export class AnsibleInventory {
* @param hostObj - nested object of hosts
* @returns an array of object with host and priority as keys
*/
function parseInventoryHosts(hostObj) {
function parseInventoryHosts(hostObj: AnsibleHostObject) {
const topLevelGroups = hostObj.all.children.filter(
(item: string) => item !== "ungrouped",
);
Expand All @@ -77,32 +92,32 @@ function parseInventoryHosts(hostObj) {

// Set priorities: top level groups (1), other groups (2), ungrouped (3), hosts for groups (4), localhost (5)
const topLevelGroupsObjList = topLevelGroups.map((item) => {
return { host: item, priority: 1 };
return { host: item, priority: 1 } as AnsibleHost;
});

const otherGroupsObjList = otherGroups.map((item) => {
return { host: item, priority: 2 };
return { host: item, priority: 2 } as AnsibleHost;
});

const allGroups = [...topLevelGroupsObjList, ...otherGroupsObjList];

let ungroupedHostsObjList = [];
let ungroupedHostsObjList: AnsibleHost[] = [];
if (hostObj.ungrouped) {
ungroupedHostsObjList = hostObj.ungrouped.hosts.map((item) => {
return { host: item, priority: 3 };
});
}

// Add 'localhost' and 'all' to the inventory list
const localhostObj = { host: "localhost", priority: 5 };
const allHostObj = { host: "all", priority: 6 };
const localhostObj = { host: "localhost", priority: 5 } as AnsibleHost;
const allHostObj = { host: "all", priority: 6 } as AnsibleHost;

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) => {
return { host: item, priority: 4 };
return { host: item, priority: 4 } as AnsibleHost;
});
allHosts = [...allHosts, ...hostsObj];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export class DocsLibrary {
);

// check routing
let moduleRoute;
let moduleRoute: IPluginRoute | undefined;
for (const fqcn of candidateFqcns) {
moduleRoute = this.getModuleRoute(fqcn);
if (moduleRoute) {
Expand All @@ -137,7 +137,7 @@ export class DocsLibrary {
}

// find module
let module;
let module: IModuleMetadata;
if (moduleRoute && moduleRoute.redirect) {
module = this.modules.get(moduleRoute.redirect);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import * as child_process from "child_process";
import * as fs from "fs";
import * as path from "path";
import { URI } from "vscode-uri";
import { Connection } from "vscode-languageserver";
import {
Connection,
WorkDoneProgressServerReporter,
} from "vscode-languageserver";
import { v4 as uuidv4 } from "uuid";
import { AnsibleConfig } from "./ansibleConfig";
import { ImagePuller } from "../utils/imagePuller";
Expand Down Expand Up @@ -88,7 +91,7 @@ export class ExecutionEnvironment {
/[^a-z0-9]/gi,
"_",
)}`;
let progressTracker;
let progressTracker: WorkDoneProgressServerReporter;

try {
const containerImageIdCommand = `${this._container_engine} images ${this._container_image} --format="{{.ID}}" | head -n 1`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ export class SettingsManager {
*/
private _settingsAdjustment(settingsObject) {
for (const key in settingsObject) {
const value = settingsObject[key];
const value: any = settingsObject[key];

if (value && typeof value === "object") {
if (value.default !== undefined) {
Expand Down
4 changes: 2 additions & 2 deletions packages/ansible-language-server/src/utils/docsFinder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export async function findDocumentation(
if (!fs.existsSync(dir) || fs.lstatSync(dir).isFile()) {
return [];
}
let files;
let files: string[];
switch (kind) {
case "builtin":
files = await globArray([`${dir}/**/*.py`, "!/**/_*.py"]);
Expand Down Expand Up @@ -90,7 +90,7 @@ export async function findPluginRouting(
if (!fs.existsSync(dir) || fs.lstatSync(dir).isFile()) {
return pluginRouting;
}
let files;
let files: string[];
switch (kind) {
case "builtin":
files = await globArray([`${dir}/config/ansible_builtin_runtime.yml`]);
Expand Down
2 changes: 1 addition & 1 deletion packages/ansible-language-server/src/utils/docsParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ export class LazyModuleDocumentation implements IModuleMetadata {
if (!this._contents) {
this._contents = new Map<string, Record<string, unknown>>();
const contents = fs.readFileSync(this.source, { encoding: "utf8" });
let m;
let m: RegExpExecArray | null;
while ((m = LazyModuleDocumentation.docsRegex.exec(contents)) !== null) {
if (m && m.groups && m.groups.name && m.groups.doc && m.groups.pre) {
if (m.groups.name === DOCUMENTATION) {
Expand Down
Loading
Loading