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 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
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -798,10 +798,11 @@
"Verbose",
"Normal",
"Warning",
"Error"
"Error",
"None"
],
"default": "Normal",
"description": "Sets the logging verbosity level for the PowerShell Editor Services host executable. Valid values are 'Diagnostic', 'Verbose', 'Normal', 'Warning', and 'Error'"
"description": "Sets the logging verbosity level for the PowerShell Editor Services host executable. Valid values are 'Diagnostic', 'Verbose', 'Normal', 'Warning', 'Error', and 'None'"
},
"powershell.developer.editorServicesWaitForDebugger": {
"type": "boolean",
Expand Down
5 changes: 5 additions & 0 deletions src/features/ExternalApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface IPowerShellExtensionClient {
unregisterExternalExtension(uuid: string): boolean;
getPowerShellVersionDetails(uuid: string): Promise<IExternalPowerShellDetails>;
waitUntilStarted(uuid: string): Promise<void>;
getStorageUri(): vscode.Uri;
}

/*
Expand Down Expand Up @@ -166,6 +167,10 @@ export class ExternalApiFeature extends LanguageClientConsumer implements IPower
return this.sessionManager.waitUntilStarted();
}

public getStorageUri(): vscode.Uri {
return this.extensionContext.storageUri;
}

public dispose() {
// Nothing to dispose.
}
Expand Down
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
39 changes: 21 additions & 18 deletions src/logging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export enum LogLevel {
Normal,
Warning,
Error,
None,
}

/** Interface for logging operations. New features should use this interface for the "type" of logger.
Expand All @@ -29,19 +30,24 @@ export interface ILogger {

export class Logger implements ILogger {

public logBasePath: string;
public logSessionPath: string;
public logBasePath: vscode.Uri;
public logSessionPath: vscode.Uri;
public MinimumLogLevel: LogLevel = LogLevel.Normal;

private commands: vscode.Disposable[];
private logChannel: vscode.OutputChannel;
private logFilePath: string;
private logFilePath: vscode.Uri;

constructor() {
constructor(logBasePath: vscode.Uri) {
this.logChannel = vscode.window.createOutputChannel("PowerShell Extension Logs");

this.logBasePath = path.resolve(__dirname, "../logs");
utils.ensurePathExists(this.logBasePath);
if (logBasePath === undefined) {
// No workspace, we have to use another folder.
this.logBasePath = vscode.Uri.file(path.resolve(__dirname, "../logs"));
utils.ensurePathExists(this.logBasePath.fsPath);
} else {
this.logBasePath = vscode.Uri.joinPath(logBasePath, "logs");
}

this.commands = [
vscode.commands.registerCommand(
Expand All @@ -59,8 +65,8 @@ export class Logger implements ILogger {
this.logChannel.dispose();
}

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

public writeAtLevel(logLevel: LogLevel, message: string, ...additionalMessages: string[]) {
Expand Down Expand Up @@ -136,17 +142,16 @@ export class Logger implements ILogger {
}
}

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

this.logSessionPath =
path.resolve(
vscode.Uri.joinPath(
this.logBasePath,
`${Math.floor(Date.now() / 1000)}-${vscode.env.sessionId}`);

this.logFilePath = this.getLogFilePath("vscode-powershell");

utils.ensurePathExists(this.logSessionPath);
await vscode.workspace.fs.createDirectory(this.logSessionPath);
}

private logLevelNameToValue(logLevelName: string): LogLevel {
Expand All @@ -156,6 +161,7 @@ export class Logger implements ILogger {
case "normal": return LogLevel.Normal;
case "warning": return LogLevel.Warning;
case "error": return LogLevel.Error;
case "none": return LogLevel.None;
default: return LogLevel.Normal;
}
}
Expand All @@ -168,10 +174,7 @@ export class Logger implements ILogger {
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",
vscode.Uri.file(this.logSessionPath),
true);
vscode.commands.executeCommand("vscode.openFolder", this.logSessionPath, true);
}
}

Expand All @@ -181,9 +184,9 @@ export class Logger implements ILogger {
`${now.toLocaleDateString()} ${now.toLocaleTimeString()} [${LogLevel[level].toUpperCase()}] - ${message}`;

this.logChannel.appendLine(timestampedMessage);
if (this.logFilePath) {
if (this.logFilePath && this.MinimumLogLevel !== LogLevel.None) {
fs.appendFile(
this.logFilePath,
this.logFilePath.fsPath,
timestampedMessage + os.EOL,
(err) => {
if (err) {
Expand Down
22 changes: 13 additions & 9 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
logger = new Logger();

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

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

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

return {
registerExternalExtension: (id: string, apiVersion: string = 'v1') => externalApi.registerExternalExtension(id, apiVersion),
unregisterExternalExtension: uuid => externalApi.unregisterExternalExtension(uuid),
getPowerShellVersionDetails: uuid => externalApi.getPowerShellVersionDetails(uuid),
waitUntilStarted: uuid => externalApi.waitUntilStarted(uuid),
getStorageUri: () => externalApi.getStorageUri(),
};
}

Expand Down
2 changes: 1 addition & 1 deletion src/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class PowerShellProcess {
: "";

this.startPsesArgs +=
`-LogPath '${PowerShellProcess.escapeSingleQuotes(editorServicesLogPath)}' ` +
`-LogPath '${PowerShellProcess.escapeSingleQuotes(editorServicesLogPath.fsPath)}' ` +
`-SessionDetailsPath '${PowerShellProcess.escapeSingleQuotes(this.sessionFilePath)}' ` +
`-FeatureFlags @(${featureFlags}) `;

Expand Down
48 changes: 27 additions & 21 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,15 @@ 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;
}

this.log.startNewLog(this.sessionSettings.developer.editorServicesLogLevel);
await this.log.startNewLog(this.sessionSettings.developer.editorServicesLogLevel);

// Create the PowerShell executable finder now
this.powershellExeFinder = new PowerShellExeFinder(
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
Loading