Skip to content

Add multi-root choice experience to powershell.cwd #4064

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 6 commits into from
Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 2 additions & 2 deletions src/features/UpdatePowerShell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,9 @@ export async function InvokePowerShellUpdateCheck(
// Invoke the MSI via cmd.
const msi = spawn("msiexec", ["/i", msiDownloadPath]);

msi.on("close", (code) => {
msi.on("close", async () => {
// Now that the MSI is finished, start the Integrated Console session.
sessionManager.start();
await sessionManager.start();
fs.unlinkSync(msiDownloadPath);
});

Expand Down
19 changes: 11 additions & 8 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,25 @@ const documentSelector: DocumentSelector = [
{ language: "powershell", scheme: "untitled" },
];

export function activate(context: vscode.ExtensionContext): IPowerShellExtensionClient {
// create telemetry reporter on extension activation
// NOTE: Now that this is async, we can probably improve a lot!
export async function activate(context: vscode.ExtensionContext): Promise<IPowerShellExtensionClient> {
telemetryReporter = new TelemetryReporter(PackageJSON.name, PackageJSON.version, AI_KEY);

// If both extensions are enabled, this will cause unexpected behavior since both register the same commands
// If both extensions are enabled, this will cause unexpected behavior since both register the same commands.
// TODO: Merge extensions and use preview channel in marketplace instead.
if (PackageJSON.name.toLowerCase() === "powershell-preview"
&& vscode.extensions.getExtension("ms-vscode.powershell")) {
vscode.window.showWarningMessage(
"'PowerShell' and 'PowerShell Preview' are both enabled. Please disable one for best performance.");
}

// This displays a popup and a changelog after an update.
checkForUpdatedVersion(context, PackageJSON.version);

// Load and validate settings (will prompt for 'cwd' if necessary).
await Settings.validateCwdSetting();
const extensionSettings = Settings.load();

vscode.languages.setLanguageConfiguration(
PowerShellLanguageId,
{
Expand Down Expand Up @@ -118,11 +124,8 @@ export function activate(context: vscode.ExtensionContext): IPowerShellExtension
],
});

// Create the logger
// Setup the logger.
logger = new Logger();

// Set the log level
const extensionSettings = Settings.load();
logger.MinimumLogLevel = LogLevel[extensionSettings.developer.editorServicesLogLevel];

sessionManager =
Expand Down Expand Up @@ -169,7 +172,7 @@ export function activate(context: vscode.ExtensionContext): IPowerShellExtension
sessionManager.setLanguageClientConsumers(languageClientConsumers);

if (extensionSettings.startAutomatically) {
sessionManager.start();
await sessionManager.start();
}

return {
Expand Down
46 changes: 26 additions & 20 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,10 @@ export class SessionManager implements Middleware {
this.languageClientConsumers = languageClientConsumers;
}

public start(exeNameOverride?: string) {
public async start(exeNameOverride?: string) {
await Settings.validateCwdSetting();
this.sessionSettings = Settings.load();

if (exeNameOverride) {
this.sessionSettings.powerShellDefaultVersion = exeNameOverride;
}
Expand Down Expand Up @@ -240,9 +242,9 @@ export class SessionManager implements Middleware {
this.sessionStatus = SessionStatus.NotStarted;
}

public restartSession(exeNameOverride?: string) {
public async restartSession(exeNameOverride?: string) {
this.stop();
this.start(exeNameOverride);
await this.start(exeNameOverride);
}

public getSessionDetails(): utils.IEditorServicesSessionDetails {
Expand Down Expand Up @@ -387,14 +389,16 @@ export class SessionManager implements Middleware {
}
}

private onConfigurationUpdated() {
private async onConfigurationUpdated() {
const settings = Settings.load();

this.focusConsoleOnExecute = settings.integratedConsole.focusConsoleOnExecute;

// Detect any setting changes that would affect the session
if (!this.suppressRestartPrompt &&
(settings.powerShellDefaultVersion.toLowerCase() !==
(settings.cwd.toLowerCase() !==
this.sessionSettings.cwd.toLowerCase() ||
settings.powerShellDefaultVersion.toLowerCase() !==
this.sessionSettings.powerShellDefaultVersion.toLowerCase() ||
settings.developer.editorServicesLogLevel.toLowerCase() !==
this.sessionSettings.developer.editorServicesLogLevel.toLowerCase() ||
Expand All @@ -403,14 +407,13 @@ export class SessionManager implements Middleware {
settings.integratedConsole.useLegacyReadLine !==
this.sessionSettings.integratedConsole.useLegacyReadLine)) {

vscode.window.showInformationMessage(
const response: string = await vscode.window.showInformationMessage(
"The PowerShell runtime configuration has changed, would you like to start a new session?",
"Yes", "No")
.then((response) => {
"Yes", "No");

if (response === "Yes") {
this.restartSession();
await this.restartSession();
}
});
}
}

Expand All @@ -433,7 +436,7 @@ export class SessionManager implements Middleware {
this.registeredCommands = [
vscode.commands.registerCommand("PowerShell.RestartSession", () => { this.restartSession(); }),
vscode.commands.registerCommand(this.ShowSessionMenuCommandName, () => { this.showSessionMenu(); }),
vscode.workspace.onDidChangeConfiguration(() => this.onConfigurationUpdated()),
vscode.workspace.onDidChangeConfiguration(async () => { await this.onConfigurationUpdated(); }),
vscode.commands.registerCommand(
"PowerShell.ShowSessionConsole", (isExecute?: boolean) => { this.showSessionConsole(isExecute); }),
];
Expand All @@ -457,10 +460,10 @@ export class SessionManager implements Middleware {
this.sessionSettings);

this.languageServerProcess.onExited(
() => {
async () => {
if (this.sessionStatus === SessionStatus.Running) {
this.setSessionStatus("Session Exited", SessionStatus.Failed);
this.promptForRestart();
await this.promptForRestart();
}
});

Expand Down Expand Up @@ -503,11 +506,14 @@ export class SessionManager implements Middleware {
});
}

private promptForRestart() {
vscode.window.showErrorMessage(
private async promptForRestart() {
const response: string = await vscode.window.showErrorMessage(
"The PowerShell Integrated Console (PSIC) has stopped, would you like to restart it? (IntelliSense will not work unless the PSIC is active and unblocked.)",
"Yes", "No")
.then((answer) => { if (answer === "Yes") { this.restartSession(); }});
"Yes", "No");

if (response === "Yes") {
await this.restartSession();
}
}

private startLanguageClient(sessionDetails: utils.IEditorServicesSessionDetails) {
Expand Down Expand Up @@ -756,7 +762,7 @@ export class SessionManager implements Middleware {
// rather than pull from the settings. The issue we prevent here is when a
// workspace setting is defined which gets priority over user settings which
// is what the change above sets.
this.restartSession(exePath.displayName);
await this.restartSession(exePath.displayName);
}

private showSessionConsole(isExecute?: boolean) {
Expand Down Expand Up @@ -817,10 +823,10 @@ export class SessionManager implements Middleware {

new SessionMenuItem(
"Restart Current Session",
() => {
async () => {
// We pass in the display name so we guarantee that the session
// will be the same PowerShell.
this.restartSession(this.PowerShellExeDetails.displayName);
await this.restartSession(this.PowerShellExeDetails.displayName);
}),

new SessionMenuItem(
Expand Down
39 changes: 33 additions & 6 deletions src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import vscode = require("vscode");
import utils = require("./utils");
import os = require("os");

enum CodeFormattingPreset {
Custom,
Expand Down Expand Up @@ -134,10 +135,10 @@ export interface INotebooksSettings {
saveMarkdownCellsAs?: CommentType;
}

// TODO: This could probably be async, and call `validateCwdSetting()` directly.
export function load(): ISettings {
const configuration: vscode.WorkspaceConfiguration =
vscode.workspace.getConfiguration(
utils.PowerShellLanguageId);
vscode.workspace.getConfiguration(utils.PowerShellLanguageId);

const defaultBugReportingSettings: IBugReportingSettings = {
project: "https://github.com/PowerShell/vscode-powershell",
Expand Down Expand Up @@ -265,17 +266,17 @@ export function load(): ISettings {
// is the reason terminals on macOS typically run login shells by default which set up
// the environment. See http://unix.stackexchange.com/a/119675/115410"
configuration.get<IStartAsLoginShellSettings>("startAsLoginShell", defaultStartAsLoginShellSettings),
cwd: // TODO: Should we resolve this path and/or default to a workspace folder?
configuration.get<string>("cwd", null),
cwd: // NOTE: This must be validated at startup via `validateCwdSetting()`. There's probably a better way to do this.
configuration.get<string>("cwd", undefined),
};
}

// Get the ConfigurationTarget (read: scope) of where the *effective* setting value comes from
export async function getEffectiveConfigurationTarget(settingName: string): Promise<vscode.ConfigurationTarget> {
const configuration = vscode.workspace.getConfiguration(utils.PowerShellLanguageId);

const detail = configuration.inspect(settingName);
let configurationTarget = null;

if (typeof detail.workspaceFolderValue !== "undefined") {
configurationTarget = vscode.ConfigurationTarget.WorkspaceFolder;
}
Expand All @@ -294,7 +295,6 @@ export async function change(
configurationTarget?: vscode.ConfigurationTarget | boolean): Promise<void> {

const configuration = vscode.workspace.getConfiguration(utils.PowerShellLanguageId);

await configuration.update(settingName, newValue, configurationTarget);
}

Expand All @@ -312,3 +312,30 @@ function getWorkspaceSettingsWithDefaults<TSettings>(
}
return defaultSettings;
}

export async function validateCwdSetting(): Promise<string> {
let cwd: string = vscode.workspace.getConfiguration(utils.PowerShellLanguageId).get<string>("cwd", null);

// Only use the cwd setting if it exists.
if (utils.checkIfDirectoryExists(cwd)) {
return cwd;
} else {
// Otherwise use a workspace folder, prompting if necessary.
if (vscode.workspace.workspaceFolders?.length > 1) {
const options: vscode.WorkspaceFolderPickOptions = {
placeHolder: "Select a folder to use as the PowerShell extension's working directory.",
}
cwd = (await vscode.window.showWorkspaceFolderPick(options))?.uri.fsPath;
// Save the picked 'cwd' to the workspace settings.
await change("cwd", cwd);
} else {
cwd = vscode.workspace.workspaceFolders?.[0].uri.fsPath;
}
// If there were no workspace folders, or somehow they don't exist, use
// the home directory.
if (cwd === undefined || !utils.checkIfDirectoryExists(cwd)) {
return os.homedir();
}
return cwd;
}
}
10 changes: 10 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ export function checkIfFileExists(filePath: string): boolean {
}
}

export function checkIfDirectoryExists(directoryPath: string): boolean {
try {
// tslint:disable-next-line:no-bitwise
fs.accessSync(directoryPath, fs.constants.R_OK | fs.constants.O_DIRECTORY);
return true;
} catch (e) {
return false;
}
}

export function getTimestampString() {
const time = new Date();
return `[${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}]`;
Expand Down