Skip to content

Commit b30934e

Browse files
Add Directory.Exists() check to SetInitialWorkingDirectoryAsync() (#1851)
There was an edge case where, after setting and un-setting the `powershell.cwd` property in the VS Code client, instead of being `null` the setting would be the empty string `""`. The client did not care about this, and so left the server to silently crash on startup. We previously assumed that by the time the server started, the directory would be validated by the client, but this was wrong. So now we check its existence first.
1 parent 4e4fdc3 commit b30934e

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/PowerShellEditorServices/Services/PowerShell/Host/PsesInternalHost.cs

+5-3
Original file line numberDiff line numberDiff line change
@@ -475,9 +475,11 @@ internal Task LoadHostProfilesAsync(CancellationToken cancellationToken)
475475

476476
public Task SetInitialWorkingDirectoryAsync(string path, CancellationToken cancellationToken)
477477
{
478-
return ExecutePSCommandAsync(
479-
new PSCommand().AddCommand("Set-Location").AddParameter("LiteralPath", path),
480-
cancellationToken);
478+
return Directory.Exists(path)
479+
? ExecutePSCommandAsync(
480+
new PSCommand().AddCommand("Set-Location").AddParameter("LiteralPath", path),
481+
cancellationToken)
482+
: Task.CompletedTask;
481483
}
482484

483485
private void Run()

test/PowerShellEditorServices.Test/Session/PsesInternalHostTests.cs

+15
Original file line numberDiff line numberDiff line change
@@ -186,5 +186,20 @@ await psesHost.ExecutePSCommandAsync(
186186
new PSCommand().AddScript("\"protocol=https`nhost=myhost.com`nusername=john`npassword=doe`n`n\" | git.exe credential approve; if ($LastExitCode) { throw }"),
187187
CancellationToken.None).ConfigureAwait(true);
188188
}
189+
190+
[Theory]
191+
[InlineData("")] // Regression test for "unset" path.
192+
[InlineData("C:\\Some\\Bad\\Directory")] // Non-existent directory.
193+
[InlineData("testhost.dll")] // Existent file.
194+
public async Task CanHandleBadInitialWorkingDirectory(string path)
195+
{
196+
string cwd = Environment.CurrentDirectory;
197+
await psesHost.SetInitialWorkingDirectoryAsync(path, CancellationToken.None).ConfigureAwait(true);
198+
199+
IReadOnlyList<string> getLocation = await psesHost.ExecutePSCommandAsync<string>(
200+
new PSCommand().AddCommand("Get-Location"),
201+
CancellationToken.None).ConfigureAwait(true);
202+
Assert.Collection(getLocation, (d) => Assert.Equal(cwd, d, ignoreCase: true));
203+
}
189204
}
190205
}

0 commit comments

Comments
 (0)