Skip to content

Check script extension for current file only #4231

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

Merged
merged 2 commits into from
Oct 26, 2022
Merged
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
6 changes: 6 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@
"error",
"always"
],
"@typescript-eslint/no-floating-promises": [
"error",
{
"ignoreVoid": true
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}
],
"@typescript-eslint/no-non-null-assertion": [
"off"
],
Expand Down
4 changes: 2 additions & 2 deletions src/features/Console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,13 @@ export class ConsoleFeature extends LanguageClientConsumer {
private commands: vscode.Disposable[];
private handlers: vscode.Disposable[] = [];

constructor(private log: Logger) {
constructor(private logger: Logger) {
super();
this.commands = [
vscode.commands.registerCommand("PowerShell.RunSelection", async () => {
if (vscode.window.activeTerminal &&
vscode.window.activeTerminal.name !== "PowerShell Extension") {
this.log.write("PowerShell Extension Terminal is not active! Running in current terminal using 'runSelectedText'");
this.logger.write("PowerShell Extension Terminal is not active! Running in current terminal using 'runSelectedText'");
await vscode.commands.executeCommand("workbench.action.terminal.runSelectedText");

// We need to honor the focusConsoleOnExecute setting here too. However, the boolean that `show`
Expand Down
6 changes: 2 additions & 4 deletions src/features/CustomViews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,8 @@ class PowerShellContentProvider implements vscode.TextDocumentContentProvider {

vscode.workspace.textDocuments.some((doc) => {
if (doc.uri.toString() === uriString) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
vscode.window.showTextDocument(doc);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
vscode.commands.executeCommand("workbench.action.closeActiveEditor");
void vscode.window.showTextDocument(doc);
void vscode.commands.executeCommand("workbench.action.closeActiveEditor");
return true;
}

Expand Down
67 changes: 27 additions & 40 deletions src/features/DebugSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ export class DebugSessionFeature extends LanguageClientConsumer
: this.sessionManager.getSessionDetails();

if (sessionDetails === undefined) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.logger.writeAndShowError(`No session details available for ${session.name}`);
void this.logger.writeAndShowError(`PowerShell session details not available for ${session.name}`);
return;
}

Expand All @@ -103,17 +102,15 @@ export class DebugSessionFeature extends LanguageClientConsumer
languageClient.onNotification(
StartDebuggerNotificationType,
// TODO: Use a named debug configuration.
// eslint-disable-next-line @typescript-eslint/no-misused-promises
() => vscode.debug.startDebugging(undefined, {
() => void vscode.debug.startDebugging(undefined, {
request: "launch",
type: "PowerShell",
name: "PowerShell: Interactive Session"
})),

languageClient.onNotification(
StopDebuggerNotificationType,
// eslint-disable-next-line @typescript-eslint/no-misused-promises
() => vscode.debug.stopDebugging(undefined))
() => void vscode.debug.stopDebugging(undefined))
];
}

Expand Down Expand Up @@ -192,7 +189,7 @@ export class DebugSessionFeature extends LanguageClientConsumer

if (config.script === "${file}" || config.script === "${relativeFile}") {
if (vscode.window.activeTextEditor === undefined) {
await vscode.window.showErrorMessage("To debug the 'Current File', you must first open a PowerShell script file in the editor.");
void this.logger.writeAndShowError("To debug the 'Current File', you must first open a PowerShell script file in the editor.");
return undefined;
}
config.current_document = true;
Expand All @@ -218,7 +215,7 @@ export class DebugSessionFeature extends LanguageClientConsumer
} else if (config.request === "launch") {
resolvedConfig = await this.resolveLaunchDebugConfiguration(config);
} else {
await vscode.window.showErrorMessage(`The request type was invalid: '${config.request}'`);
void this.logger.writeAndShowError(`PowerShell debug configuration's request type was invalid: '${config.request}'.`);
return null;
}

Expand All @@ -235,48 +232,45 @@ export class DebugSessionFeature extends LanguageClientConsumer
}

private async resolveLaunchDebugConfiguration(config: DebugConfiguration): Promise<DebugConfiguration | undefined> {
// Check the languageId only for current documents (which includes untitled documents).
// Check the languageId and file extension only for current documents
// (which includes untitled documents). This prevents accidentally
// running the debugger for an open non-PowerShell file.
if (config.current_document) {
const currentDocument = vscode.window.activeTextEditor?.document;
if (currentDocument?.languageId !== "powershell") {
await vscode.window.showErrorMessage("Please change the current document's language mode to PowerShell.");
void this.logger.writeAndShowError(`PowerShell does not support debugging this language mode: '${currentDocument?.languageId}'.`);
return undefined;
}
}

// Check the temporary console setting for untitled documents only, and
// check the document extension for if the script is an extant file (it
// could be inline).
if (config.untitled_document) {
if (config.createTemporaryIntegratedConsole) {
await vscode.window.showErrorMessage("Debugging untitled files in a temporary console is not supported.");
return undefined;
}
} else if (config.script) {
// TODO: Why even bother with this complexity?
if (await utils.checkIfFileExists(config.script)) {
const ext = path.extname(config.script).toLowerCase();
if (!(ext === ".ps1" || ext === ".psm1")) {
await vscode.window.showErrorMessage(`PowerShell does not support debugging this file type: '${path.basename(config.script)}'`);
void this.logger.writeAndShowError(`PowerShell does not support debugging this file type: '${path.basename(config.script)}'.`);
return undefined;
}
}
}

// Check the temporary console setting for untitled documents only.
if (config.untitled_document && config.createTemporaryIntegratedConsole) {
void this.logger.writeAndShowError("PowerShell does not support debugging untitled files in a temporary console.");
return undefined;
}

return config;
}

private async resolveAttachDebugConfiguration(config: DebugConfiguration): Promise<DebugConfiguration | undefined | null> {
const platformDetails = getPlatformDetails();
const versionDetails = this.sessionManager.getPowerShellVersionDetails();
if (versionDetails === undefined) {
await vscode.window.showErrorMessage(`Session version details were not found for ${config.name}`);
void this.logger.writeAndShowError(`PowerShell session version details were not found for '${config.name}'.`);
return null;
}

// Cross-platform attach to process was added in 6.2.0-preview.4.
if (versionDetails.version < "7.0.0" && platformDetails.operatingSystem !== OperatingSystem.Windows) {
await vscode.window.showErrorMessage(`Attaching to a PowerShell Host Process on ${OperatingSystem[platformDetails.operatingSystem]} requires PowerShell 7.0 or higher.`);
void this.logger.writeAndShowError(`Attaching to a PowerShell Host Process on ${OperatingSystem[platformDetails.operatingSystem]} requires PowerShell 7.0 or higher.`);
return undefined;
}

Expand Down Expand Up @@ -309,10 +303,9 @@ export class SpecifyScriptArgsFeature implements vscode.Disposable {
constructor(context: vscode.ExtensionContext) {
this.context = context;

this.command =
vscode.commands.registerCommand("PowerShell.SpecifyScriptArgs", () => {
return this.specifyScriptArguments();
});
this.command = vscode.commands.registerCommand("PowerShell.SpecifyScriptArgs", () => {
return this.specifyScriptArguments();
});
}

public dispose() {
Expand Down Expand Up @@ -366,7 +359,7 @@ export class PickPSHostProcessFeature extends LanguageClientConsumer {
private waitingForClientToken?: vscode.CancellationTokenSource;
private getLanguageClientResolve?: (value: LanguageClient) => void;

constructor() {
constructor(private logger: Logger) {
super();

this.command =
Expand Down Expand Up @@ -401,7 +394,6 @@ export class PickPSHostProcessFeature extends LanguageClientConsumer {
(resolve, reject) => {
this.getLanguageClientResolve = resolve;

// eslint-disable-next-line @typescript-eslint/no-floating-promises
vscode.window
.showQuickPick(
["Cancel"],
Expand All @@ -412,17 +404,15 @@ export class PickPSHostProcessFeature extends LanguageClientConsumer {
this.clearWaitingToken();
reject();
}
});
}, undefined);

// Cancel the loading prompt after 60 seconds
setTimeout(() => {
if (this.waitingForClientToken) {
this.clearWaitingToken();
reject();

// eslint-disable-next-line @typescript-eslint/no-floating-promises
vscode.window.showErrorMessage(
"Attach to PowerShell host process: PowerShell session took too long to start.");
void this.logger.writeAndShowError("Attach to PowerShell host process: PowerShell session took too long to start.");
}
}, 60000);
},
Expand Down Expand Up @@ -495,7 +485,7 @@ export class PickRunspaceFeature extends LanguageClientConsumer {
private waitingForClientToken?: vscode.CancellationTokenSource;
private getLanguageClientResolve?: (value: LanguageClient) => void;

constructor() {
constructor(private logger: Logger) {
super();
this.command =
vscode.commands.registerCommand("PowerShell.PickRunspace", (processId) => {
Expand Down Expand Up @@ -529,7 +519,6 @@ export class PickRunspaceFeature extends LanguageClientConsumer {
(resolve, reject) => {
this.getLanguageClientResolve = resolve;

// eslint-disable-next-line @typescript-eslint/no-floating-promises
vscode.window
.showQuickPick(
["Cancel"],
Expand All @@ -540,17 +529,15 @@ export class PickRunspaceFeature extends LanguageClientConsumer {
this.clearWaitingToken();
reject();
}
});
}, undefined);

// Cancel the loading prompt after 60 seconds
setTimeout(() => {
if (this.waitingForClientToken) {
this.clearWaitingToken();
reject();

// eslint-disable-next-line @typescript-eslint/no-floating-promises
vscode.window.showErrorMessage(
"Attach to PowerShell host process: PowerShell session took too long to start.");
void this.logger.writeAndShowError("Attach to PowerShell host process: PowerShell session took too long to start.");
}
}, 60000);
},
Expand Down
41 changes: 19 additions & 22 deletions src/features/ExtensionCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
private handlers: vscode.Disposable[] = [];
private extensionCommands: IExtensionCommand[] = [];

constructor(private log: Logger) {
constructor(private logger: Logger) {
super();
this.commands = [
vscode.commands.registerCommand("PowerShell.ShowAdditionalCommands", async () => {
Expand Down Expand Up @@ -216,7 +216,6 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {

this.languageClient.onRequest(
InsertTextRequestType,
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(details) => this.insertText(details)),

this.languageClient.onRequest(
Expand Down Expand Up @@ -262,8 +261,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
// We check to see if they have TrueClear on. If not, no-op because the
// overriden Clear-Host already calls [System.Console]::Clear()
if (Settings.load().integratedConsole.forceClearScrollbackBuffer) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
vscode.commands.executeCommand("workbench.action.terminal.clear");
void vscode.commands.executeCommand("workbench.action.terminal.clear");
}
})
];
Expand Down Expand Up @@ -292,7 +290,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
private async showExtensionCommands(client: LanguageClient): Promise<void> {
// If no extension commands are available, show a message
if (this.extensionCommands.length === 0) {
await vscode.window.showInformationMessage("No extension commands have been loaded into the current session.");
void this.logger.writeAndShowInformation("No extension commands have been loaded into the current session.");
return;
}

Expand Down Expand Up @@ -364,10 +362,10 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
};
}

private newFile(): Thenable<EditorOperationResponse> {
return vscode.workspace.openTextDocument({ content: "" })
.then((doc) => vscode.window.showTextDocument(doc))
.then((_) => EditorOperationResponse.Completed);
private async newFile(): Promise<EditorOperationResponse> {
const doc = await vscode.workspace.openTextDocument({ content: "" });
await vscode.window.showTextDocument(doc);
return EditorOperationResponse.Completed;
}

private openFile(openFileDetails: IOpenFileDetails): Thenable<EditorOperationResponse> {
Expand Down Expand Up @@ -416,7 +414,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))) {
await this.log.writeAndShowError(`File to save not found: ${currentFileUri.fsPath}.`);
void this.logger.writeAndShowError(`File to save not found: ${currentFileUri.fsPath}.`);
return EditorOperationResponse.Completed;
}

Expand All @@ -443,8 +441,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
if (!saveFileDetails.newPath) {
// TODO: Create a class handle vscode warnings and errors so we can warn easily
// without logging
await this.log.writeAndShowWarning(
"Cannot save untitled file. Try SaveAs(\"path/to/file.ps1\") instead.");
void this.logger.writeAndShowWarning("Cannot save untitled file. Try SaveAs(\"path/to/file.ps1\") instead.");
return EditorOperationResponse.Completed;
}

Expand All @@ -454,7 +451,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
} else {
// In fresh contexts, workspaceFolders is not defined...
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
await this.log.writeAndShowWarning("Cannot save file to relative path: no workspaces are open. " +
void this.logger.writeAndShowWarning("Cannot save file to relative path: no workspaces are open. " +
"Try saving to an absolute path, or open a workspace.");
return EditorOperationResponse.Completed;
}
Expand All @@ -463,7 +460,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
const workspaceRootUri = vscode.workspace.workspaceFolders[0].uri;
// We don't support saving to a non-file URI-schemed workspace
if (workspaceRootUri.scheme !== "file") {
await this.log.writeAndShowWarning(
void this.logger.writeAndShowWarning(
"Cannot save untitled file to a relative path in an untitled workspace. " +
"Try saving to an absolute path or opening a workspace folder.");
return EditorOperationResponse.Completed;
Expand All @@ -475,7 +472,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
default: {
// Other URI schemes are not supported
const msg = JSON.stringify(saveFileDetails);
this.log.writeVerbose(
this.logger.writeVerbose(
`<${ExtensionCommandsFeature.name}>: Saving a document with scheme '${currentFileUri.scheme}' ` +
`is currently unsupported. Message: '${msg}'`);
return EditorOperationResponse.Completed; }
Expand Down Expand Up @@ -503,7 +500,7 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
vscode.Uri.file(destinationAbsolutePath),
Buffer.from(oldDocument.getText()));
} catch (e) {
await this.log.writeAndShowWarning(`<${ExtensionCommandsFeature.name}>: ` +
void this.logger.writeAndShowWarning(`<${ExtensionCommandsFeature.name}>: ` +
`Unable to save file to path '${destinationAbsolutePath}': ${e}`);
return;
}
Expand Down Expand Up @@ -572,18 +569,18 @@ export class ExtensionCommandsFeature extends LanguageClientConsumer {
return EditorOperationResponse.Completed;
}

private async showInformationMessage(message: string): Promise<EditorOperationResponse> {
await vscode.window.showInformationMessage(message);
private showInformationMessage(message: string): EditorOperationResponse {
void this.logger.writeAndShowInformation(message);
return EditorOperationResponse.Completed;
}

private async showErrorMessage(message: string): Promise<EditorOperationResponse> {
await vscode.window.showErrorMessage(message);
private showErrorMessage(message: string): EditorOperationResponse {
void this.logger.writeAndShowError(message);
return EditorOperationResponse.Completed;
}

private async showWarningMessage(message: string): Promise<EditorOperationResponse> {
await vscode.window.showWarningMessage(message);
private showWarningMessage(message: string): EditorOperationResponse {
void this.logger.writeAndShowWarning(message);
return EditorOperationResponse.Completed;
}

Expand Down
Loading