Skip to content

Commit afc9fd1

Browse files
authoredMay 17, 2022
Merge pull request #1801 from PowerShell/andschwa/stdio
Re-enable stdio clients by fixing initialization sequence
2 parents 044c81e + c1dd1db commit afc9fd1

19 files changed

+106
-203
lines changed
 

‎src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs

+4-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
using System.Management.Automation;
1313
using System.Management.Automation.Runspaces;
1414

15-
#if DEBUG
15+
#if ASSEMBLY_LOAD_STACKTRACE
1616
using System.Diagnostics;
1717
#endif
1818

@@ -98,7 +98,7 @@ public static EditorServicesLoader Create(
9898

9999
AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext _, AssemblyName asmName) =>
100100
{
101-
#if DEBUG
101+
#if ASSEMBLY_LOAD_STACKTRACE
102102
logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {asmName}. Stacktrace:\n{new StackTrace()}");
103103
#else
104104
logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {asmName}");
@@ -138,7 +138,7 @@ public static EditorServicesLoader Create(
138138
// Unlike in .NET Core, we need to be look for all dependencies in .NET Framework, not just PSES.dll
139139
AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) =>
140140
{
141-
#if DEBUG
141+
#if ASSEMBLY_LOAD_STACKTRACE
142142
logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {args.Name}. Stacktrace:\n{new StackTrace()}");
143143
#else
144144
logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {args.Name}");
@@ -208,6 +208,7 @@ public Task LoadAndRunEditorServicesAsync()
208208
#endif
209209

210210
// Add the bundled modules to the PSModulePath
211+
// TODO: Why do we do this in addition to passing the bundled module path to the host?
211212
UpdatePSModulePath();
212213

213214
// Check to see if the configuration we have is valid

‎src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs

+1
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ public PsesDebugServer CreateDebugServerForTempSession(
152152
.AddSerilog()
153153
.SetMinimumLevel(LogLevel.Trace)) // TODO: Why randomly set to trace?
154154
.AddSingleton<ILanguageServerFacade>(_ => null)
155+
// TODO: Why add these for a debug server?!
155156
.AddPsesLanguageServices(hostStartupInfo)
156157
// For a Temp session, there is no LanguageServer so just set it to null
157158
.AddSingleton(

‎src/PowerShellEditorServices/Server/PsesDebugServer.cs

+6-13
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
using System;
55
using System.IO;
6-
using System.Threading;
76
using System.Threading.Tasks;
87
using Microsoft.Extensions.DependencyInjection;
98
using Microsoft.Extensions.Logging;
@@ -23,15 +22,10 @@ internal class PsesDebugServer : IDisposable
2322
private readonly Stream _inputStream;
2423
private readonly Stream _outputStream;
2524
private readonly TaskCompletionSource<bool> _serverStopped;
26-
2725
private DebugAdapterServer _debugAdapterServer;
28-
2926
private PsesInternalHost _psesHost;
30-
3127
private bool _startedPses;
32-
3328
private readonly bool _isTemp;
34-
3529
protected readonly ILoggerFactory _loggerFactory;
3630

3731
public PsesDebugServer(
@@ -91,10 +85,12 @@ public async Task StartAsync()
9185
.WithHandler<DebugEvaluateHandler>()
9286
// The OnInitialize delegate gets run when we first receive the _Initialize_ request:
9387
// https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Initialize
94-
.OnInitialize(async (server, _, _) =>
88+
.OnInitialize(async (server, _, cancellationToken) =>
9589
{
96-
// We need to make sure the host has been started
97-
_startedPses = !await _psesHost.TryStartAsync(new HostStartOptions(), CancellationToken.None).ConfigureAwait(false);
90+
// Start the host if not already started, and enable debug mode (required
91+
// for remote debugging).
92+
_startedPses = !await _psesHost.TryStartAsync(new HostStartOptions(), cancellationToken).ConfigureAwait(false);
93+
_psesHost.DebugContext.EnableDebugMode();
9894

9995
// We need to give the host a handle to the DAP so it can register
10096
// notifications (specifically for sendKeyPress).
@@ -103,11 +99,8 @@ public async Task StartAsync()
10399
_psesHost.DebugServer = server;
104100
}
105101

106-
// Ensure the debugger mode is set correctly - this is required for remote debugging to work
107-
_psesHost.DebugContext.EnableDebugMode();
108-
102+
// Clear any existing breakpoints before proceeding.
109103
BreakpointService breakpointService = server.GetService<BreakpointService>();
110-
// Clear any existing breakpoints before proceeding
111104
await breakpointService.RemoveAllBreakpointsAsync().ConfigureAwait(false);
112105
})
113106
// The OnInitialized delegate gets run right before the server responds to the _Initialize_ request:

‎src/PowerShellEditorServices/Server/PsesLanguageServer.cs

+19-23
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT License.
33

4-
using System;
54
using System.IO;
65
using System.Threading.Tasks;
76
using Microsoft.Extensions.DependencyInjection;
@@ -12,6 +11,8 @@
1211
using Microsoft.PowerShell.EditorServices.Services.Extension;
1312
using Microsoft.PowerShell.EditorServices.Services.PowerShell.Host;
1413
using Microsoft.PowerShell.EditorServices.Services.Template;
14+
using Newtonsoft.Json.Linq;
15+
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
1516
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
1617
using OmniSharp.Extensions.LanguageServer.Server;
1718
using Serilog;
@@ -24,15 +25,12 @@ namespace Microsoft.PowerShell.EditorServices.Server
2425
internal class PsesLanguageServer
2526
{
2627
internal ILoggerFactory LoggerFactory { get; }
27-
2828
internal ILanguageServer LanguageServer { get; private set; }
29-
3029
private readonly LogLevel _minimumLogLevel;
3130
private readonly Stream _inputStream;
3231
private readonly Stream _outputStream;
3332
private readonly HostStartupInfo _hostDetails;
3433
private readonly TaskCompletionSource<bool> _serverStart;
35-
3634
private PsesInternalHost _psesHost;
3735

3836
/// <summary>
@@ -117,33 +115,32 @@ public async Task StartAsync()
117115
// _Initialize_ request:
118116
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#initialize
119117
.OnInitialize(
120-
(languageServer, request, _) =>
118+
(languageServer, initializeParams, cancellationToken) =>
121119
{
122-
Log.Logger.Debug("Initializing OmniSharp Language Server");
123-
124-
IServiceProvider serviceProvider = languageServer.Services;
125-
126-
_psesHost = serviceProvider.GetService<PsesInternalHost>();
127-
128-
WorkspaceService workspaceService = serviceProvider.GetService<WorkspaceService>();
129-
130-
// Grab the workspace path from the parameters
131-
if (request.RootUri != null)
132-
{
133-
workspaceService.WorkspacePath = request.RootUri.GetFileSystemPath();
134-
}
135-
else if (request.WorkspaceFolders != null)
120+
// Set the workspace path from the parameters.
121+
WorkspaceService workspaceService = languageServer.Services.GetService<WorkspaceService>();
122+
if (initializeParams.WorkspaceFolders is not null)
136123
{
137-
// If RootUri isn't set, try to use the first WorkspaceFolder.
138124
// TODO: Support multi-workspace.
139-
foreach (OmniSharp.Extensions.LanguageServer.Protocol.Models.WorkspaceFolder workspaceFolder in request.WorkspaceFolders)
125+
foreach (WorkspaceFolder workspaceFolder in initializeParams.WorkspaceFolders)
140126
{
141127
workspaceService.WorkspacePath = workspaceFolder.Uri.GetFileSystemPath();
142128
break;
143129
}
144130
}
145131

146-
return Task.CompletedTask;
132+
// Parse initialization options.
133+
JObject initializationOptions = initializeParams.InitializationOptions as JObject;
134+
HostStartOptions hostStartOptions = new()
135+
{
136+
LoadProfiles = initializationOptions?.GetValue("EnableProfileLoading")?.Value<bool>() ?? false,
137+
// TODO: Consider deprecating the setting which sets this and
138+
// instead use WorkspacePath exclusively.
139+
InitialWorkingDirectory = initializationOptions?.GetValue("InitialWorkingDirectory")?.Value<string>() ?? workspaceService.WorkspacePath
140+
};
141+
142+
_psesHost = languageServer.Services.GetService<PsesInternalHost>();
143+
return _psesHost.TryStartAsync(hostStartOptions, cancellationToken);
147144
});
148145
}).ConfigureAwait(false);
149146

@@ -156,7 +153,6 @@ public async Task StartAsync()
156153
/// <returns>A task that completes when the server is shut down.</returns>
157154
public async Task WaitForShutdown()
158155
{
159-
Log.Logger.Debug("Shutting down OmniSharp Language Server");
160156
await _serverStart.Task.ConfigureAwait(false);
161157
await LanguageServer.WaitForExit.ConfigureAwait(false);
162158

‎src/PowerShellEditorServices/Server/PsesServiceCollectionExtensions.cs

+4-5
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,10 @@ public static IServiceCollection AddPsesLanguageServices(
4444
provider.GetService<EditorOperationsService>(),
4545
provider.GetService<IInternalPowerShellExecutionService>());
4646

47-
// This is where we create the $psEditor variable
48-
// so that when the console is ready, it will be available
49-
// TODO: Improve the sequencing here so that:
50-
// - The variable is guaranteed to be initialized when the console first appears
51-
// - Any errors that occur are handled rather than lost by the unawaited task
47+
// This is where we create the $psEditor variable so that when the console
48+
// is ready, it will be available. NOTE: We cannot await this because it
49+
// uses a lazy initialization to avoid a race with the dependency injection
50+
// framework, see the EditorObject class for that!
5251
extensionService.InitializeAsync();
5352

5453
return extensionService;

‎src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostRawUI.cs

+18-24
Original file line numberDiff line numberDiff line change
@@ -12,44 +12,38 @@ internal class NullPSHostRawUI : PSHostRawUserInterface
1212

1313
public NullPSHostRawUI() => _buffer = new BufferCell[0, 0];
1414

15-
public override ConsoleColor BackgroundColor { get; set; }
16-
public override Size BufferSize { get; set; }
17-
public override Coordinates CursorPosition { get; set; }
18-
public override int CursorSize { get; set; }
19-
public override ConsoleColor ForegroundColor { get; set; }
15+
public override Coordinates WindowPosition { get; set; }
2016

21-
public override bool KeyAvailable => false;
17+
public override Size MaxWindowSize => new() { Width = _buffer.GetLength(0), Height = _buffer.GetLength(1) };
2218

2319
public override Size MaxPhysicalWindowSize => MaxWindowSize;
2420

25-
public override Size MaxWindowSize => new() { Width = _buffer.GetLength(0), Height = _buffer.GetLength(1) };
21+
public override bool KeyAvailable => false;
22+
23+
public override ConsoleColor ForegroundColor { get; set; }
24+
25+
public override int CursorSize { get; set; }
26+
27+
public override Coordinates CursorPosition { get; set; }
28+
29+
public override Size BufferSize { get; set; }
30+
31+
public override ConsoleColor BackgroundColor { get; set; }
2632

27-
public override Coordinates WindowPosition { get; set; }
2833
public override Size WindowSize { get; set; }
34+
2935
public override string WindowTitle { get; set; }
3036

31-
public override void FlushInputBuffer()
32-
{
33-
// Do nothing
34-
}
37+
public override void FlushInputBuffer() { }
3538

3639
public override BufferCell[,] GetBufferContents(Rectangle rectangle) => _buffer;
3740

3841
public override KeyInfo ReadKey(ReadKeyOptions options) => default;
3942

40-
public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
41-
{
42-
// Do nothing
43-
}
43+
public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill) { }
4444

45-
public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
46-
{
47-
// Do nothing
48-
}
45+
public override void SetBufferContents(Coordinates origin, BufferCell[,] contents) { }
4946

50-
public override void SetBufferContents(Rectangle rectangle, BufferCell fill)
51-
{
52-
// Do nothing
53-
}
47+
public override void SetBufferContents(Rectangle rectangle, BufferCell fill) { }
5448
}
5549
}

‎src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostUI.cs

+23-39
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ internal class NullPSHostUI : PSHostUserInterface
1414
{
1515
public NullPSHostUI() => RawUI = new NullPSHostRawUI();
1616

17+
public override bool SupportsVirtualTerminal => false;
18+
1719
public override PSHostRawUserInterface RawUI { get; }
1820

1921
public override Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions) => new();
@@ -29,44 +31,26 @@ public override PSCredential PromptForCredential(string caption, string message,
2931

3032
public override SecureString ReadLineAsSecureString() => new();
3133

32-
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
33-
{
34-
// Do nothing
35-
}
36-
37-
public override void Write(string value)
38-
{
39-
// Do nothing
40-
}
41-
42-
public override void WriteDebugLine(string message)
43-
{
44-
// Do nothing
45-
}
46-
47-
public override void WriteErrorLine(string value)
48-
{
49-
// Do nothing
50-
}
51-
52-
public override void WriteLine(string value)
53-
{
54-
// Do nothing
55-
}
56-
57-
public override void WriteProgress(long sourceId, ProgressRecord record)
58-
{
59-
// Do nothing
60-
}
61-
62-
public override void WriteVerboseLine(string message)
63-
{
64-
// Do nothing
65-
}
66-
67-
public override void WriteWarningLine(string message)
68-
{
69-
// Do nothing
70-
}
34+
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { }
35+
36+
public override void Write(string value) { }
37+
38+
public override void WriteDebugLine(string message) { }
39+
40+
public override void WriteErrorLine(string value) { }
41+
42+
public override void WriteInformation(InformationRecord record) { }
43+
44+
public override void WriteLine() { }
45+
46+
public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { }
47+
48+
public override void WriteLine(string value) { }
49+
50+
public override void WriteProgress(long sourceId, ProgressRecord record) { }
51+
52+
public override void WriteVerboseLine(string message) { }
53+
54+
public override void WriteWarningLine(string message) { }
7155
}
7256
}

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

+9-9
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ public PsesInternalHost(
102102
// Respect a user provided bundled module path.
103103
if (Directory.Exists(hostInfo.BundledModulePath))
104104
{
105-
_logger.LogTrace("Using new bundled module path: {}", hostInfo.BundledModulePath);
105+
_logger.LogTrace($"Using new bundled module path: {hostInfo.BundledModulePath}");
106106
s_bundledModulePath = hostInfo.BundledModulePath;
107107
}
108108

@@ -169,8 +169,6 @@ public PsesInternalHost(
169169

170170
public bool IsRunning => _isRunningLatch.IsSignaled;
171171

172-
public string InitialWorkingDirectory { get; private set; }
173-
174172
public Task Shutdown => _stopped.Task;
175173

176174
IRunspaceInfo IRunspaceContext.CurrentRunspace => CurrentRunspace;
@@ -236,7 +234,7 @@ public override void SetShouldExit(int exitCode)
236234
/// <returns>A task that resolves when the host has finished startup, with the value true if the caller started the host, and false otherwise.</returns>
237235
public async Task<bool> TryStartAsync(HostStartOptions startOptions, CancellationToken cancellationToken)
238236
{
239-
_logger.LogInformation("Host starting");
237+
_logger.LogDebug("Starting host...");
240238
if (!_isRunningLatch.TryEnter())
241239
{
242240
_logger.LogDebug("Host start requested after already started.");
@@ -248,13 +246,16 @@ public async Task<bool> TryStartAsync(HostStartOptions startOptions, Cancellatio
248246

249247
if (startOptions.LoadProfiles)
250248
{
249+
_logger.LogDebug("Loading profiles...");
251250
await LoadHostProfilesAsync(cancellationToken).ConfigureAwait(false);
252-
_logger.LogInformation("Profiles loaded");
251+
_logger.LogDebug("Profiles loaded!");
253252
}
254253

255254
if (startOptions.InitialWorkingDirectory is not null)
256255
{
257-
await SetInitialWorkingDirectoryAsync(startOptions.InitialWorkingDirectory, CancellationToken.None).ConfigureAwait(false);
256+
_logger.LogDebug($"Setting InitialWorkingDirectory to {startOptions.InitialWorkingDirectory}...");
257+
await SetInitialWorkingDirectoryAsync(startOptions.InitialWorkingDirectory, cancellationToken).ConfigureAwait(false);
258+
_logger.LogDebug("InitialWorkingDirectory set!");
258259
}
259260

260261
await _started.Task.ConfigureAwait(false);
@@ -269,6 +270,7 @@ public Task StopAsync()
269270

270271
public void TriggerShutdown()
271272
{
273+
_logger.LogDebug("Shutting down host...");
272274
if (Interlocked.Exchange(ref _shuttingDown, 1) == 0)
273275
{
274276
_cancellationContext.CancelCurrentTaskStack();
@@ -438,8 +440,6 @@ internal Task LoadHostProfilesAsync(CancellationToken cancellationToken)
438440

439441
public Task SetInitialWorkingDirectoryAsync(string path, CancellationToken cancellationToken)
440442
{
441-
InitialWorkingDirectory = path;
442-
443443
return ExecutePSCommandAsync(
444444
new PSCommand().AddCommand("Set-Location").AddParameter("LiteralPath", path),
445445
cancellationToken);
@@ -680,7 +680,7 @@ private void RunTopLevelExecutionLoop()
680680
return;
681681
}
682682

683-
_logger.LogInformation("PSES pipeline thread loop shutting down");
683+
_logger.LogDebug("PSES pipeline thread loop shutting down");
684684
_stopped.SetResult(true);
685685
}
686686

‎src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs

+2-7
Original file line numberDiff line numberDiff line change
@@ -76,12 +76,7 @@ public static async Task<CommandCompletion> GetCompletionsAsync(
7676
{
7777
IScriptPosition cursorPosition = s_clonePositionWithNewOffset(scriptAst.Extent.StartScriptPosition, fileOffset);
7878

79-
logger.LogTrace(
80-
string.Format(
81-
"Getting completions at offset {0} (line: {1}, column: {2})",
82-
fileOffset,
83-
cursorPosition.LineNumber,
84-
cursorPosition.ColumnNumber));
79+
logger.LogTrace($"Getting completions at offset {fileOffset} (line: {cursorPosition.LineNumber}, column: {cursorPosition.ColumnNumber})");
8580

8681
Stopwatch stopwatch = new();
8782

@@ -103,7 +98,7 @@ await executionService.ExecuteDelegateAsync(
10398
.ConfigureAwait(false);
10499

105100
stopwatch.Stop();
106-
logger.LogTrace($"IntelliSense completed in {stopwatch.ElapsedMilliseconds}ms.");
101+
logger.LogTrace($"IntelliSense completed in {stopwatch.ElapsedMilliseconds}ms: {commandCompletion}");
107102

108103
return commandCompletion;
109104
}

‎src/PowerShellEditorServices/Services/TextDocument/Handlers/CodeLensHandlers.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public override Task<CodeLensContainer> Handle(CodeLensParams request, Cancellat
4747

4848
public override Task<CodeLens> Handle(CodeLens request, CancellationToken cancellationToken)
4949
{
50-
// TODO: Catch deserializtion exception on bad object
50+
// TODO: Catch deserialization exception on bad object
5151
CodeLensData codeLensData = request.Data.ToObject<CodeLensData>();
5252

5353
ICodeLensProvider originalProvider = _symbolsService

‎src/PowerShellEditorServices/Services/TextDocument/Handlers/CompletionHandler.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ internal async Task<IEnumerable<CompletionItem>> GetCompletionsInFileAsync(
144144
for (int i = 0; i < result.CompletionMatches.Count; i++)
145145
{
146146
completionItems[i] = CreateCompletionItem(result.CompletionMatches[i], replacedRange, i + 1);
147+
_logger.LogTrace("Created completion item: " + completionItems[i] + " with " + completionItems[i].TextEdit);
147148
}
148149
return completionItems;
149150
}
@@ -184,7 +185,10 @@ internal static CompletionItem CreateCompletionItem(
184185
// Retain PowerShell's sort order with the given index.
185186
SortText = $"{sortIndex:D4}{result.ListItemText}",
186187
FilterText = result.CompletionText,
187-
TextEdit = textEdit // Used instead of InsertText.
188+
// Used instead of Label when TextEdit is unsupported
189+
InsertText = result.CompletionText,
190+
// Used instead of InsertText when possible
191+
TextEdit = textEdit
188192
};
189193

190194
return result.ResultType switch

‎src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT License.
33

4+
using System.Collections.Generic;
5+
using System.Threading;
6+
using System.Threading.Tasks;
47
using Microsoft.Extensions.Logging;
58
using Microsoft.PowerShell.EditorServices.Services;
69
using Microsoft.PowerShell.EditorServices.Services.Symbols;
@@ -9,9 +12,6 @@
912
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
1013
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
1114
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
12-
using System.Collections.Generic;
13-
using System.Threading;
14-
using System.Threading.Tasks;
1515

1616
namespace Microsoft.PowerShell.EditorServices.Handlers
1717
{
@@ -27,7 +27,6 @@ public PsesDocumentHighlightHandler(
2727
{
2828
_logger = loggerFactory.CreateLogger<PsesDocumentHighlightHandler>();
2929
_workspaceService = workspaceService;
30-
_logger.LogInformation("highlight handler loaded");
3130
}
3231

3332
protected override DocumentHighlightRegistrationOptions CreateRegistrationOptions(DocumentHighlightCapability capability, ClientCapabilities clientCapabilities) => new()
@@ -46,7 +45,7 @@ public override Task<DocumentHighlightContainer> Handle(
4645
request.Position.Line + 1,
4746
request.Position.Character + 1);
4847

49-
if (symbolOccurrences == null)
48+
if (symbolOccurrences is null)
5049
{
5150
return Task.FromResult(s_emptyHighlightContainer);
5251
}
@@ -60,6 +59,7 @@ public override Task<DocumentHighlightContainer> Handle(
6059
Range = symbolOccurrences[i].ScriptRegion.ToRange()
6160
};
6261
}
62+
_logger.LogDebug("Highlights: " + highlights);
6363

6464
return Task.FromResult(new DocumentHighlightContainer(highlights));
6565
}

‎src/PowerShellEditorServices/Services/Workspace/Handlers/ConfigurationHandler.cs

+1-73
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,13 @@
33

44
using System;
55
using System.Collections.Generic;
6-
using System.IO;
76
using System.Threading;
87
using System.Threading.Tasks;
98
using MediatR;
109
using Microsoft.Extensions.Logging;
1110
using Microsoft.PowerShell.EditorServices.Logging;
1211
using Microsoft.PowerShell.EditorServices.Services;
1312
using Microsoft.PowerShell.EditorServices.Services.Configuration;
14-
using Microsoft.PowerShell.EditorServices.Services.Extension;
15-
using Microsoft.PowerShell.EditorServices.Services.PowerShell.Host;
1613
using Newtonsoft.Json.Linq;
1714
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
1815
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
@@ -26,27 +23,19 @@ internal class PsesConfigurationHandler : DidChangeConfigurationHandlerBase
2623
private readonly ILogger _logger;
2724
private readonly WorkspaceService _workspaceService;
2825
private readonly ConfigurationService _configurationService;
29-
private readonly ExtensionService _extensionService;
30-
private readonly PsesInternalHost _psesHost;
3126
private readonly ILanguageServerFacade _languageServer;
32-
private bool _profilesLoaded;
33-
private bool _cwdSet;
3427

3528
public PsesConfigurationHandler(
3629
ILoggerFactory factory,
3730
WorkspaceService workspaceService,
3831
AnalysisService analysisService,
3932
ConfigurationService configurationService,
40-
ILanguageServerFacade languageServer,
41-
ExtensionService extensionService,
42-
PsesInternalHost psesHost)
33+
ILanguageServerFacade languageServer)
4334
{
4435
_logger = factory.CreateLogger<PsesConfigurationHandler>();
4536
_workspaceService = workspaceService;
4637
_configurationService = configurationService;
4738
_languageServer = languageServer;
48-
_extensionService = extensionService;
49-
_psesHost = psesHost;
5039

5140
ConfigurationUpdated += analysisService.OnConfigurationUpdated;
5241
}
@@ -63,7 +52,6 @@ public override async Task<Unit> Handle(DidChangeConfigurationParams request, Ca
6352

6453
SendFeatureChangesTelemetry(incomingSettings);
6554

66-
bool profileLoadingPreviouslyEnabled = _configurationService.CurrentSettings.EnableProfileLoading;
6755
bool oldScriptAnalysisEnabled = _configurationService.CurrentSettings.ScriptAnalysis.Enable;
6856
string oldScriptAnalysisSettingsPath = _configurationService.CurrentSettings.ScriptAnalysis?.SettingsPath;
6957

@@ -72,66 +60,6 @@ public override async Task<Unit> Handle(DidChangeConfigurationParams request, Ca
7260
_workspaceService.WorkspacePath,
7361
_logger);
7462

75-
// We need to load the profiles if:
76-
// - Profile loading is configured, AND
77-
// - Profiles haven't been loaded before, OR
78-
// - The profile loading configuration just changed
79-
bool loadProfiles = _configurationService.CurrentSettings.EnableProfileLoading
80-
&& (!_profilesLoaded || !profileLoadingPreviouslyEnabled);
81-
82-
if (!_psesHost.IsRunning)
83-
{
84-
_logger.LogTrace("Starting command loop");
85-
86-
if (loadProfiles)
87-
{
88-
_logger.LogTrace("Loading profiles...");
89-
}
90-
91-
await _psesHost.TryStartAsync(new HostStartOptions { LoadProfiles = loadProfiles }, CancellationToken.None).ConfigureAwait(false);
92-
93-
if (loadProfiles)
94-
{
95-
_profilesLoaded = true;
96-
_logger.LogTrace("Loaded!");
97-
}
98-
}
99-
100-
// TODO: Load profiles when the host is already running? Note that this might mess up
101-
// the ordering and require the foreground.
102-
if (!_cwdSet)
103-
{
104-
if (!string.IsNullOrEmpty(_configurationService.CurrentSettings.Cwd)
105-
&& Directory.Exists(_configurationService.CurrentSettings.Cwd))
106-
{
107-
_logger.LogTrace($"Setting CWD (from config) to {_configurationService.CurrentSettings.Cwd}");
108-
await _psesHost.SetInitialWorkingDirectoryAsync(
109-
_configurationService.CurrentSettings.Cwd,
110-
CancellationToken.None).ConfigureAwait(false);
111-
}
112-
else if (_workspaceService.WorkspacePath is not null
113-
&& Directory.Exists(_workspaceService.WorkspacePath))
114-
{
115-
_logger.LogTrace($"Setting CWD (from workspace) to {_workspaceService.WorkspacePath}");
116-
await _psesHost.SetInitialWorkingDirectoryAsync(
117-
_workspaceService.WorkspacePath,
118-
CancellationToken.None).ConfigureAwait(false);
119-
}
120-
else
121-
{
122-
_logger.LogTrace("Tried to set CWD but in bad state");
123-
}
124-
125-
_cwdSet = true;
126-
}
127-
128-
// This is another place we call this to setup $psEditor, which really needs to be done
129-
// _before_ profiles. In current testing, this has already been done by the call to
130-
// InitializeAsync when the ExtensionService class is injected.
131-
//
132-
// TODO: Remove this.
133-
await _extensionService.InitializeAsync().ConfigureAwait(false);
134-
13563
// Run any events subscribed to configuration updates
13664
_logger.LogTrace("Running configuration update event handlers");
13765
ConfigurationUpdated?.Invoke(this, _configurationService.CurrentSettings);

‎test/PowerShellEditorServices.Test.Shared/Completion/CompleteAttributeValue.cs

+3
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ internal static class CompleteAttributeValue
2323
Kind = CompletionItemKind.Property,
2424
Detail = "System.Boolean ValueFromPipeline",
2525
FilterText = "ValueFromPipeline",
26+
InsertText = "ValueFromPipeline",
2627
Label = "ValueFromPipeline",
2728
SortText = "0001ValueFromPipeline",
2829
TextEdit = new TextEdit
@@ -41,6 +42,7 @@ internal static class CompleteAttributeValue
4142
Kind = CompletionItemKind.Property,
4243
Detail = "System.Boolean ValueFromPipelineByPropertyName",
4344
FilterText = "ValueFromPipelineByPropertyName",
45+
InsertText = "ValueFromPipelineByPropertyName",
4446
Label = "ValueFromPipelineByPropertyName",
4547
SortText = "0002ValueFromPipelineByPropertyName",
4648
TextEdit = new TextEdit
@@ -59,6 +61,7 @@ internal static class CompleteAttributeValue
5961
Kind = CompletionItemKind.Property,
6062
Detail = "System.Boolean ValueFromRemainingArguments",
6163
FilterText = "ValueFromRemainingArguments",
64+
InsertText = "ValueFromRemainingArguments",
6265
Label = "ValueFromRemainingArguments",
6366
SortText = "0003ValueFromRemainingArguments",
6467
TextEdit = new TextEdit

‎test/PowerShellEditorServices.Test.Shared/Completion/CompleteCommandFromModule.cs

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ internal static class CompleteCommandFromModule
2626
Kind = CompletionItemKind.Function,
2727
Detail = "", // OS-dependent, checked separately.
2828
FilterText = "Get-Random",
29+
InsertText = "Get-Random",
2930
Label = "Get-Random",
3031
SortText = "0001Get-Random",
3132
TextEdit = new TextEdit

‎test/PowerShellEditorServices.Test.Shared/Completion/CompleteCommandInFile.cs

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ internal static class CompleteCommandInFile
2323
Kind = CompletionItemKind.Function,
2424
Detail = "",
2525
FilterText = "Get-Something",
26+
InsertText = "Get-Something",
2627
Label = "Get-Something",
2728
SortText = "0001Get-Something",
2829
TextEdit = new TextEdit

‎test/PowerShellEditorServices.Test.Shared/Completion/CompleteNamespace.cs

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ internal static class CompleteNamespace
2323
Kind = CompletionItemKind.Module,
2424
Detail = "Namespace System.Collections",
2525
FilterText = "System.Collections",
26+
InsertText = "System.Collections",
2627
Label = "Collections",
2728
SortText = "0001Collections",
2829
TextEdit = new TextEdit

‎test/PowerShellEditorServices.Test.Shared/Completion/CompleteTypeName.cs

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ internal static class CompleteTypeName
2323
Kind = CompletionItemKind.TypeParameter,
2424
Detail = "System.Collections.ArrayList",
2525
FilterText = "System.Collections.ArrayList",
26+
InsertText = "System.Collections.ArrayList",
2627
Label = "ArrayList",
2728
SortText = "0001ArrayList",
2829
TextEdit = new TextEdit

‎test/PowerShellEditorServices.Test.Shared/Completion/CompleteVariableInFile.cs

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ internal static class CompleteVariableInFile
2323
Kind = CompletionItemKind.Variable,
2424
Detail = "", // Same as label, so not shown.
2525
FilterText = "$testVar1",
26+
InsertText = "$testVar1",
2627
Label = "testVar1",
2728
SortText = "0001testVar1",
2829
TextEdit = new TextEdit

0 commit comments

Comments
 (0)
Please sign in to comment.