Skip to content

Commit

Permalink
Replace forEach(...) for for (_ of ...)
Browse files Browse the repository at this point in the history
It's faster...it reads better.
  • Loading branch information
andyleejordan committed Aug 12, 2022
1 parent 27a5b8e commit aeb44a4
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 70 deletions.
9 changes: 5 additions & 4 deletions src/controls/checkboxQuickPick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,12 @@ function getQuickPickItems(items: ICheckboxQuickPickItem[]): vscode.QuickPickIte
const quickPickItems: vscode.QuickPickItem[] = [];
quickPickItems.push({ label: confirmItemLabel, description: "" });

items.forEach((item) =>
for (const item of items) {
quickPickItems.push({
label: convertToCheckBox(item),
description: item.description,
}));
label: convertToCheckBox(item),
description: item.description,
});
}

return quickPickItems;
}
Expand Down
6 changes: 3 additions & 3 deletions src/features/Console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,9 @@ function showChoicePrompt(
});

// Select the defaults
promptDetails.defaultChoices.forEach((choiceIndex) => {
checkboxQuickPickItems[choiceIndex].isSelected = true;
});
for (const choice of promptDetails.defaultChoices) {
checkboxQuickPickItems[choice].isSelected = true;
};

resultThenable =
showCheckboxQuickPick(
Expand Down
22 changes: 9 additions & 13 deletions src/features/CustomViews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ export class CustomViewsFeature extends LanguageClientConsumer {
}

public dispose() {
this.commands.forEach((d) => d.dispose());
for (const command of this.commands) {
command.dispose();
}
}

public setLanguageClient(languageClient: LanguageClient) {
Expand Down Expand Up @@ -177,23 +179,17 @@ class HtmlContentView extends CustomView {
let styleTags = "";
if (this.htmlContent.styleSheetPaths &&
this.htmlContent.styleSheetPaths.length > 0) {
this.htmlContent.styleSheetPaths.forEach(
(styleSheetPath) => {
styleTags += `<link rel="stylesheet" href="${
styleSheetPath.toString().replace("file://", "vscode-resource://")
}">\n`;
});
for (const styleSheetPath of this.htmlContent.styleSheetPaths) {
styleTags += `<link rel="stylesheet" href="${styleSheetPath.toString().replace("file://", "vscode-resource://")}">\n`;
}
}

let scriptTags = "";
if (this.htmlContent.javaScriptPaths &&
this.htmlContent.javaScriptPaths.length > 0) {
this.htmlContent.javaScriptPaths.forEach(
(javaScriptPath) => {
scriptTags += `<script src="${
javaScriptPath.toString().replace("file://", "vscode-resource://")
}"></script>\n`;
});
for (const javaScriptPath of this.htmlContent.javaScriptPaths) {
scriptTags += `<script src="${javaScriptPath.toString().replace("file://", "vscode-resource://")}"></script>\n`;
}
}

// Return an HTML page with the specified content
Expand Down
2 changes: 1 addition & 1 deletion src/features/ExtensionCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
case "file":
// If the file to save can't be found, just complete the request
if (!this.findTextDocument(this.normalizeFilePath(currentFileUri.fsPath))) {
this.log.writeAndShowError(`File to save not found: ${currentFileUri.fsPath}.`);
await this.log.writeAndShowError(`File to save not found: ${currentFileUri.fsPath}.`);
return EditorOperationResponse.Completed;
}

Expand Down
66 changes: 33 additions & 33 deletions src/logging.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

"use strict";

import fs = require("fs");
import os = require("os");
import path = require("path");
import vscode = require("vscode");

export enum LogLevel {
Expand All @@ -19,16 +20,15 @@ export enum LogLevel {
* This will allow for easy mocking of the logger during unit tests.
*/
export interface ILogger {
write(message: string, ...additionalMessages: string[]);
writeDiagnostic(message: string, ...additionalMessages: string[]);
writeVerbose(message: string, ...additionalMessages: string[]);
writeWarning(message: string, ...additionalMessages: string[]);
writeAndShowWarning(message: string, ...additionalMessages: string[]);
writeError(message: string, ...additionalMessages: string[]);
write(message: string, ...additionalMessages: string[]): void;
writeDiagnostic(message: string, ...additionalMessages: string[]): void;
writeVerbose(message: string, ...additionalMessages: string[]): void;
writeWarning(message: string, ...additionalMessages: string[]): void;
writeAndShowWarning(message: string, ...additionalMessages: string[]): void;
writeError(message: string, ...additionalMessages: string[]): void;
}

export class Logger implements ILogger {

public logBasePath: vscode.Uri;
public logSessionPath: vscode.Uri;
public MinimumLogLevel: LogLevel = LogLevel.Normal;
Expand All @@ -40,54 +40,55 @@ export class Logger implements ILogger {
constructor(logBasePath: vscode.Uri) {
this.logChannel = vscode.window.createOutputChannel("PowerShell Extension Logs");
this.logBasePath = vscode.Uri.joinPath(logBasePath, "logs");

this.commands = [
vscode.commands.registerCommand(
"PowerShell.ShowLogs",
() => { this.showLogPanel(); }),

vscode.commands.registerCommand(
"PowerShell.OpenLogFolder",
() => { this.openLogFolder(); }),
async () => { await this.openLogFolder(); }),
];
}

public dispose() {
this.commands.forEach((command) => { command.dispose(); });
this.logChannel.dispose();
for (const command of this.commands) {
command.dispose();
}
}

public getLogFilePath(baseName: string): vscode.Uri {
return vscode.Uri.joinPath(this.logSessionPath, `${baseName}.log`);
}

public writeAtLevel(logLevel: LogLevel, message: string, ...additionalMessages: string[]) {
public writeAtLevel(logLevel: LogLevel, message: string, ...additionalMessages: string[]): void {
if (logLevel >= this.MinimumLogLevel) {
this.writeLine(message, logLevel);

additionalMessages.forEach((line) => {
this.writeLine(line, logLevel);
});
for (const additionalMessage of additionalMessages) {
this.writeLine(additionalMessage, logLevel);
};
}
}

public write(message: string, ...additionalMessages: string[]) {
public write(message: string, ...additionalMessages: string[]): void {
this.writeAtLevel(LogLevel.Normal, message, ...additionalMessages);
}

public writeDiagnostic(message: string, ...additionalMessages: string[]) {
public writeDiagnostic(message: string, ...additionalMessages: string[]): void {
this.writeAtLevel(LogLevel.Diagnostic, message, ...additionalMessages);
}

public writeVerbose(message: string, ...additionalMessages: string[]) {
public writeVerbose(message: string, ...additionalMessages: string[]): void {
this.writeAtLevel(LogLevel.Verbose, message, ...additionalMessages);
}

public writeWarning(message: string, ...additionalMessages: string[]) {
public writeWarning(message: string, ...additionalMessages: string[]): void {
this.writeAtLevel(LogLevel.Warning, message, ...additionalMessages);
}

public writeAndShowWarning(message: string, ...additionalMessages: string[]) {
public writeAndShowWarning(message: string, ...additionalMessages: string[]): void {
this.writeWarning(message, ...additionalMessages);

vscode.window.showWarningMessage(message, "Show Logs").then((selection) => {
Expand All @@ -97,23 +98,22 @@ export class Logger implements ILogger {
});
}

public writeError(message: string, ...additionalMessages: string[]) {
public writeError(message: string, ...additionalMessages: string[]): void {
this.writeAtLevel(LogLevel.Error, message, ...additionalMessages);
}

public writeAndShowError(message: string, ...additionalMessages: string[]) {
public async writeAndShowError(message: string, ...additionalMessages: string[]): Promise<void> {
this.writeError(message, ...additionalMessages);

vscode.window.showErrorMessage(message, "Show Logs").then((selection) => {
if (selection !== undefined) {
this.showLogPanel();
}
});
const choice = await vscode.window.showErrorMessage(message, "Show Logs");
if (choice !== undefined) {
this.showLogPanel();
}
}

public async writeAndShowErrorWithActions(
message: string,
actions: { prompt: string; action: () => Promise<void> }[]) {
actions: { prompt: string; action: () => Promise<void> }[]): Promise<void> {
this.writeError(message);

const fullActions = [
Expand All @@ -134,7 +134,7 @@ export class Logger implements ILogger {
}
}

public async startNewLog(minimumLogLevel: string = "Normal") {
public async startNewLog(minimumLogLevel: string = "Normal"): Promise<void> {
this.MinimumLogLevel = this.logLevelNameToValue(minimumLogLevel.trim());

this.logSessionPath =
Expand All @@ -158,19 +158,19 @@ export class Logger implements ILogger {
}
}

private showLogPanel() {
private showLogPanel(): void {
this.logChannel.show();
}

private openLogFolder() {
private async openLogFolder(): Promise<void> {
if (this.logSessionPath) {
// Open the folder in VS Code since there isn't an easy way to
// open the folder in the platform's file browser
vscode.commands.executeCommand("vscode.openFolder", this.logSessionPath, true);
await vscode.commands.executeCommand("vscode.openFolder", this.logSessionPath, true);
}
}

private writeLine(message: string, level: LogLevel = LogLevel.Normal) {
private writeLine(message: string, level: LogLevel = LogLevel.Normal): void {
const now = new Date();
const timestampedMessage =
`${now.toLocaleDateString()} ${now.toLocaleTimeString()} [${LogLevel[level].toUpperCase()}] - ${message}`;
Expand Down
8 changes: 4 additions & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,13 @@ export async function activate(context: vscode.ExtensionContext): Promise<IPower

export function deactivate(): void {
// Clean up all extension features
languageClientConsumers.forEach((languageClientConsumer) => {
for (const languageClientConsumer of languageClientConsumers) {
languageClientConsumer.dispose();
});
};

commandRegistrations.forEach((commandRegistration) => {
for (const commandRegistration of commandRegistrations) {
commandRegistration.dispose();
});
};

// Dispose of the current session
sessionManager.dispose();
Expand Down
17 changes: 8 additions & 9 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@ export class SessionManager implements Middleware {
private debugSessionProcess: PowerShellProcess;
private debugEventHandler: vscode.Disposable;
private versionDetails: IPowerShellVersionDetails;
// TODO: Perhaps consumers should also register their handler disposables.
private registeredHandlers: vscode.Disposable[] = [];
private registeredCommands: vscode.Disposable[] = [];
private languageClient: LanguageClient = undefined;
Expand Down Expand Up @@ -535,27 +534,27 @@ Type 'help' to get help.
this.sessionDetails = await this.languageServerProcess.start("EditorServices");
} catch (error) {
this.log.write("PowerShell process failed to start.");
this.setSessionFailure("PowerShell process failed to start: ", error);
await this.setSessionFailure("PowerShell process failed to start: ", error);
}

if (this.sessionDetails.status === "started") {
this.log.write("Language server started.");
try {
await this.startLanguageClient(this.sessionDetails);
} catch (error) {
this.setSessionFailure("Language client failed to start: ", error);
await this.setSessionFailure("Language client failed to start: ", error);
}
} else if (this.sessionDetails.status === "failed") {
if (this.sessionDetails.reason === "unsupported") {
this.setSessionFailure(
await this.setSessionFailure(
"PowerShell language features are only supported on PowerShell version 5.1 and 7+. " +
`The current version is ${this.sessionDetails.powerShellVersion}.`);
} else if (this.sessionDetails.reason === "languageMode") {
this.setSessionFailure(
await this.setSessionFailure(
"PowerShell language features are disabled due to an unsupported LanguageMode: " +
`${this.sessionDetails.detail}`);
} else {
this.setSessionFailure(
await this.setSessionFailure(
`PowerShell could not be started for an unknown reason '${this.sessionDetails.reason}'`);
}
} else {
Expand Down Expand Up @@ -658,7 +657,7 @@ Type 'help' to get help.
await this.languageClient.start();
this.started = true;
} catch (error) {
this.setSessionFailure("Could not start language service: ", error);
await this.setSessionFailure("Could not start language service: ", error);
return;
}

Expand Down Expand Up @@ -795,9 +794,9 @@ Type 'help' to get help.
this.setSessionStatus(version, SessionStatus.Running);
}

private setSessionFailure(message: string, ...additionalMessages: string[]) {
this.log.writeAndShowError(message, ...additionalMessages);
private async setSessionFailure(message: string, ...additionalMessages: string[]) {
this.setSessionStatus("Initialization Error", SessionStatus.Failed);
await this.log.writeAndShowError(message, ...additionalMessages);
}

private async changePowerShellDefaultVersion(exePath: IPowerShellExeDetails) {
Expand Down
8 changes: 6 additions & 2 deletions test/features/CustomViews.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,12 @@ hello
try {
assert.strictEqual(htmlContentView.getContent(), testCase.expectedHtmlString);
} finally {
jsPaths.forEach((jsPath) => fs.unlinkSync(vscode.Uri.parse(jsPath).fsPath));
cssPaths.forEach((cssPath) => fs.unlinkSync(vscode.Uri.parse(cssPath).fsPath));
for (const jsPath of jsPaths) {
vscode.workspace.fs.delete(vscode.Uri.parse(jsPath));
}
for (const cssPath of cssPaths) {
vscode.workspace.fs.delete(vscode.Uri.parse(cssPath));
}
}
});
}
Expand Down
4 changes: 3 additions & 1 deletion test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ export function run(): Promise<void> {
}

// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(__dirname, f)));
for (const file of files) {
mocha.addFile(path.resolve(__dirname, file));
}

try {
// Run the mocha test
Expand Down

0 comments on commit aeb44a4

Please sign in to comment.