From 5eb74fec764caa7e8d33202db0acefd7f4a3d68f Mon Sep 17 00:00:00 2001 From: Andrew Schwartzmeyer Date: Wed, 13 Apr 2022 11:29:32 -0700 Subject: [PATCH] Apply automatic fixes (manually) These were available in code lens style "click to fix" but were not applied by the CLI tools. It was slow, but not horrible. Also silence two annoying suggestions around comments and naming. --- .editorconfig | 4 +- PowerShellEditorServices.build.ps1 | 3 ++ .../BuildInfo.cs | 3 ++ .../Commands/StartEditorServicesCommand.cs | 3 +- .../Configuration/HostLogger.cs | 7 +--- .../Configuration/TransportConfig.cs | 1 - .../EditorServicesLoader.cs | 3 +- .../Internal/EditorServicesRunner.cs | 23 +++++------ .../Internal/NamedPipeUtils.cs | 8 +--- .../Internal/PsesLoadContext.cs | 5 +-- .../Cmdlets/VSCodeHtmlContentViewCommands.cs | 13 +++--- .../CustomViews/CustomViewBase.cs | 4 +- .../CustomViews/IHtmlContentView.cs | 1 - .../CustomViews/IHtmlContentViews.cs | 1 - .../CustomViews/ViewColumn.cs | 3 -- .../Api/EditorExtensionServiceProvider.cs | 1 - .../Extensions/EditorCommand.cs | 9 ++-- .../Extensions/EditorCommandAttribute.cs | 1 - .../Extensions/EditorContext.cs | 6 +-- .../Extensions/EditorFileRanges.cs | 2 - .../Extensions/EditorObject.cs | 4 +- .../Extensions/EditorRequests.cs | 2 - .../Extensions/EditorWindow.cs | 2 +- .../Extensions/FileContext.cs | 2 +- .../Hosting/EditorServicesServerFactory.cs | 41 +++++++------------ .../Server/PsesDebugServer.cs | 10 ++--- .../Server/PsesLanguageServer.cs | 4 +- .../Services/Analysis/AnalysisService.cs | 8 ++-- .../Analysis/PssaCmdletAnalysisEngine.cs | 1 - .../Services/DebugAdapter/DebugService.cs | 19 ++++----- .../Debugging/BreakpointDetails.cs | 2 +- .../Debugging/CommandBreakpointDetails.cs | 14 ++----- .../Debugging/DebuggerStoppedEventArgs.cs | 9 ++-- .../DebugAdapter/Debugging/VariableDetails.cs | 38 ++++++----------- .../DebugAdapter/Debugging/VariableScope.cs | 4 +- .../Handlers/BreakpointHandlers.cs | 5 +-- .../DebugAdapter/Handlers/ScopesHandler.cs | 10 +---- .../Handlers/StackTraceHandler.cs | 10 +---- .../DebugAdapter/Handlers/VariablesHandler.cs | 10 +---- .../Extension/EditorOperationsService.cs | 27 +++++------- .../IInvokeExtensionCommandHandler.cs | 1 - .../Services/Extension/PromptEvents.cs | 1 - .../Context/PowerShellVersionDetails.cs | 12 +++--- .../Debugging/DscBreakpointCapability.cs | 9 ++-- .../Execution/BlockingConcurrentDeque.cs | 1 - .../PowerShell/Handlers/EvaluateHandler.cs | 11 +---- .../PowerShell/Handlers/ExpandAliasHandler.cs | 9 +--- .../PowerShell/Handlers/GetCommandHandler.cs | 8 +--- .../Handlers/GetCommentHelpHandler.cs | 12 +----- .../PowerShell/Handlers/GetVersionHandler.cs | 28 ------------- .../PowerShell/Handlers/ShowHelpHandler.cs | 8 +--- .../PowerShell/Runspace/RunspaceInfo.cs | 7 +--- .../PowerShell/Utility/CommandHelpers.cs | 3 +- .../Utility/PowerShellExtensions.cs | 11 +++-- .../Symbols/PesterDocumentSymbolProvider.cs | 6 +-- .../Symbols/PsdDocumentSymbolProvider.cs | 5 +-- .../Symbols/ScriptDocumentSymbolProvider.cs | 8 +--- .../Services/Symbols/SymbolReference.cs | 6 +-- .../Services/Symbols/SymbolsService.cs | 20 ++++----- .../Services/Symbols/Vistors/AstOperations.cs | 17 ++++---- .../Symbols/Vistors/FindDotSourcedVisitor.cs | 4 +- .../Symbols/Vistors/FindSymbolVisitor.cs | 2 +- .../Symbols/Vistors/FindSymbolsVisitor.cs | 14 ++----- .../Symbols/Vistors/FindSymbolsVisitor2.cs | 1 - .../Template/Handlers/TemplateHandlers.cs | 1 - .../Services/Template/TemplateService.cs | 4 +- .../Services/TextDocument/BufferPosition.cs | 5 +-- .../Services/TextDocument/BufferRange.cs | 5 +-- .../Services/TextDocument/FilePosition.cs | 1 - .../Handlers/CodeActionHandler.cs | 2 +- .../Handlers/DefinitionHandler.cs | 4 -- .../Handlers/DocumentHighlightHandler.cs | 5 +-- .../Handlers/DocumentSymbolHandler.cs | 3 +- .../Handlers/FoldingRangeHandler.cs | 6 +-- .../TextDocument/Handlers/HoverHandler.cs | 8 ++-- .../Handlers/PsesSemanticTokensHandler.cs | 10 +---- .../Handlers/ReferencesHandler.cs | 5 +-- .../Handlers/SignatureHelpHandler.cs | 8 +--- .../Services/TextDocument/ScriptFile.cs | 15 +++---- .../Services/TextDocument/ScriptFileMarker.cs | 3 +- .../Services/TextDocument/TokenOperations.cs | 5 +-- .../Workspace/LanguageServerSettings.cs | 6 +-- .../Workspace/RemoteFileManagerService.cs | 9 ++-- .../Workspace/WorkspaceFileSystemWrapper.cs | 1 - .../Services/Workspace/WorkspaceService.cs | 4 +- .../Utility/Extensions.cs | 1 - .../Utility/PathUtils.cs | 13 +++--- .../Utility/Validate.cs | 2 +- .../Utility/VersionUtils.cs | 1 - .../DebugAdapterProtocolMessageTests.cs | 7 ++-- .../LSPTestsFixures.cs | 1 - .../LanguageServerProtocolMessageTests.cs | 1 - .../Processes/StdioServerProcess.cs | 2 +- .../Completion/CompleteCommandFromModule.cs | 1 - .../Symbols/FindSymbolsInMultiSymbolFile.cs | 2 +- .../Symbols/FindSymbolsInNoSymbolsFile.cs | 2 +- .../Symbols/FindSymbolsInPSDFile.cs | 2 +- .../Symbols/FindSymbolsInPesterFile.cs | 2 +- .../Language/SemanticTokenTest.cs | 13 +++--- .../Language/TokenOperationsTests.cs | 26 ++++++------ .../Session/ScriptFileTests.cs | 7 ++-- .../Session/WorkspaceTests.cs | 10 ++--- 102 files changed, 251 insertions(+), 479 deletions(-) diff --git a/.editorconfig b/.editorconfig index 7fd7d40b1..b9414dbf0 100644 --- a/.editorconfig +++ b/.editorconfig @@ -65,7 +65,7 @@ dotnet_diagnostic.CS4014.severity = suggestion # RCS1102: Make class static dotnet_diagnostic.RCS1102.severity = warning # RCS1139: Add summary element to documentation comment -dotnet_diagnostic.RCS1139.severity = suggestion +dotnet_diagnostic.RCS1139.severity = silent # RCS1194: Implement exception constructors dotnet_diagnostic.RCS1194.severity = suggestion # RCS1210: Return completed task instead of returning null @@ -92,7 +92,7 @@ dotnet_diagnostic.VSTHRD110.severity = suggestion # VSTHRD114: Avoid returning a null Task dotnet_diagnostic.VSTHRD114.severity = suggestion # VSTHRD200: Use "Async" suffix for awaitable methods -dotnet_diagnostic.VSTHRD200.severity = suggestion +dotnet_diagnostic.VSTHRD200.severity = silent # xUnit2013: Do not use equality check to check for collection size dotnet_diagnostic.xUnit2013.severity = warning diff --git a/PowerShellEditorServices.build.ps1 b/PowerShellEditorServices.build.ps1 index 716441da3..474457b97 100644 --- a/PowerShellEditorServices.build.ps1 +++ b/PowerShellEditorServices.build.ps1 @@ -128,6 +128,9 @@ task CreateBuildInfo { [string]$buildTime = [datetime]::Today.ToString("s", [System.Globalization.CultureInfo]::InvariantCulture) $buildInfoContents = @" +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + using System.Globalization; namespace Microsoft.PowerShell.EditorServices.Hosting diff --git a/src/PowerShellEditorServices.Hosting/BuildInfo.cs b/src/PowerShellEditorServices.Hosting/BuildInfo.cs index 78953ca18..23eeb7bf1 100644 --- a/src/PowerShellEditorServices.Hosting/BuildInfo.cs +++ b/src/PowerShellEditorServices.Hosting/BuildInfo.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + using System.Globalization; namespace Microsoft.PowerShell.EditorServices.Hosting diff --git a/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs b/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs index c05d30b7a..5501ac2ce 100644 --- a/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs +++ b/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Management.Automation; using System.Reflection; using SMA = System.Management.Automation; @@ -304,7 +303,7 @@ private void RemovePSReadLineForStartup() bool hasPSReadLine = pwsh.AddCommand(new CmdletInfo("Microsoft.PowerShell.Core\\Get-Module", typeof(GetModuleCommand))) .AddParameter("Name", "PSReadLine") .Invoke() - .Any(); + .Count > 0; if (hasPSReadLine) { diff --git a/src/PowerShellEditorServices.Hosting/Configuration/HostLogger.cs b/src/PowerShellEditorServices.Hosting/Configuration/HostLogger.cs index 10ea4d401..73de784a9 100644 --- a/src/PowerShellEditorServices.Hosting/Configuration/HostLogger.cs +++ b/src/PowerShellEditorServices.Hosting/Configuration/HostLogger.cs @@ -8,7 +8,6 @@ using System.Runtime.CompilerServices; using System.Text; using System.Threading; -using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Hosting { @@ -67,7 +66,6 @@ private class Unsubscriber : IDisposable private readonly IObserver<(PsesLogLevel, string)> _thisSubscriber; - public Unsubscriber(ConcurrentDictionary, bool> subscribedObservers, IObserver<(PsesLogLevel, string)> thisSubscriber) { _subscribedObservers = subscribedObservers; @@ -161,7 +159,7 @@ public void Log(PsesLogLevel logLevel, string message) /// Convenience method for logging exceptions. /// /// The human-directed message to accompany the exception. - /// The actual execption to log. + /// The actual exception to log. /// The name of the calling method. /// The name of the file where this is logged. /// The line in the file where this is logged. @@ -171,7 +169,6 @@ public void LogException( [CallerMemberName] string callerName = null, [CallerFilePath] string callerSourceFile = null, [CallerLineNumber] int callerLineNumber = -1) => Log(PsesLogLevel.Error, $"{message}. Exception logged in {callerSourceFile} on line {callerLineNumber} in {callerName}:\n{exception}"); - } /// @@ -323,7 +320,7 @@ public void OnNext((PsesLogLevel logLevel, string message) value) case PsesLogLevel.Error: message = $"[ERR]: {value.message}"; break; - }; + } _messageQueue.Add(message); } diff --git a/src/PowerShellEditorServices.Hosting/Configuration/TransportConfig.cs b/src/PowerShellEditorServices.Hosting/Configuration/TransportConfig.cs index 041d1a9df..f3a703341 100644 --- a/src/PowerShellEditorServices.Hosting/Configuration/TransportConfig.cs +++ b/src/PowerShellEditorServices.Hosting/Configuration/TransportConfig.cs @@ -67,7 +67,6 @@ public sealed class DuplexNamedPipeTransportConfig : ITransportConfig /// Create a duplex named pipe transport config with an automatically generated pipe name. /// /// A new duplex named pipe transport configuration. - public static DuplexNamedPipeTransportConfig Create(HostLogger logger) => new(logger, NamedPipeUtils.GenerateValidNamedPipeName()); /// diff --git a/src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs b/src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs index b83a8ac84..f082975a1 100644 --- a/src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs +++ b/src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs @@ -28,7 +28,6 @@ namespace Microsoft.PowerShell.EditorServices.Hosting /// public sealed class EditorServicesLoader : IDisposable { - #if !CoreCLR private const int Net461Version = 394254; @@ -92,7 +91,7 @@ public static EditorServicesLoader Create( }; } - AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext defaultLoadContext, AssemblyName asmName) => + AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext _, AssemblyName asmName) => { #if DEBUG logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {asmName}. Stacktrace:\n{new StackTrace()}"); diff --git a/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs b/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs index 2cb1b0e73..3e6626f20 100644 --- a/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs +++ b/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs @@ -68,13 +68,13 @@ public Task RunUntilShutdown() return runAndAwaitShutdown; } - /// + /// /// TODO: This class probably should not be as the primary /// intention of that interface is to provide cleanup of unmanaged resources, which the /// logger certainly is not. Nor is this class used with a . It is /// only because of the use of that this class is also /// disposable, and instead that class should be fixed. - /// + /// public void Dispose() => _serverFactory.Dispose(); /// @@ -165,7 +165,7 @@ private async Task CreateEditorServicesAndRunUntilShutdown() Task debugServerCreation = null; if (creatingDebugServer) { - debugServerCreation = CreateDebugServerWithLanguageServerAsync(languageServer, usePSReadLine: _config.ConsoleRepl == ConsoleReplKind.PSReadLine); + debugServerCreation = CreateDebugServerWithLanguageServerAsync(languageServer); } Task languageServerStart = languageServer.StartAsync(); @@ -219,10 +219,10 @@ private async Task StartDebugServer(Task debugServerCreation) await debugServer.StartAsync().ConfigureAwait(false); } - private Task RestartDebugServerAsync(PsesDebugServer debugServer, bool usePSReadLine) + private Task RestartDebugServerAsync(PsesDebugServer debugServer) { _logger.Log(PsesLogLevel.Diagnostic, "Restarting debug server"); - Task debugServerCreation = RecreateDebugServerAsync(debugServer, usePSReadLine); + Task debugServerCreation = RecreateDebugServerAsync(debugServer); return StartDebugServer(debugServerCreation); } @@ -235,22 +235,22 @@ private async Task CreateLanguageServerAsync(HostStartupInfo return _serverFactory.CreateLanguageServer(inStream, outStream, hostDetails); } - private async Task CreateDebugServerWithLanguageServerAsync(PsesLanguageServer languageServer, bool usePSReadLine) + private async Task CreateDebugServerWithLanguageServerAsync(PsesLanguageServer languageServer) { _logger.Log(PsesLogLevel.Verbose, $"Creating debug adapter transport with endpoint {_config.DebugServiceTransport.EndpointDetails}"); (Stream inStream, Stream outStream) = await _config.DebugServiceTransport.ConnectStreamsAsync().ConfigureAwait(false); _logger.Log(PsesLogLevel.Diagnostic, "Creating debug adapter"); - return _serverFactory.CreateDebugServerWithLanguageServer(inStream, outStream, languageServer, usePSReadLine); + return _serverFactory.CreateDebugServerWithLanguageServer(inStream, outStream, languageServer); } - private async Task RecreateDebugServerAsync(PsesDebugServer debugServer, bool usePSReadLine) + private async Task RecreateDebugServerAsync(PsesDebugServer debugServer) { _logger.Log(PsesLogLevel.Diagnostic, "Recreating debug adapter transport"); (Stream inStream, Stream outStream) = await _config.DebugServiceTransport.ConnectStreamsAsync().ConfigureAwait(false); _logger.Log(PsesLogLevel.Diagnostic, "Recreating debug adapter"); - return _serverFactory.RecreateDebugServer(inStream, outStream, debugServer, usePSReadLine); + return _serverFactory.RecreateDebugServer(inStream, outStream, debugServer); } private async Task CreateDebugServerForTempSessionAsync(HostStartupInfo hostDetails) @@ -309,10 +309,7 @@ private void DebugServer_OnSessionEnded(object sender, EventArgs args) PsesDebugServer oldServer = (PsesDebugServer)sender; oldServer.Dispose(); _alreadySubscribedDebug = false; - Task.Run(() => - { - RestartDebugServerAsync(oldServer, usePSReadLine: _config.ConsoleRepl == ConsoleReplKind.PSReadLine); - }); + Task.Run(() => RestartDebugServerAsync(oldServer)); } } } diff --git a/src/PowerShellEditorServices.Hosting/Internal/NamedPipeUtils.cs b/src/PowerShellEditorServices.Hosting/Internal/NamedPipeUtils.cs index 4df8c38fa..31f8d8414 100644 --- a/src/PowerShellEditorServices.Hosting/Internal/NamedPipeUtils.cs +++ b/src/PowerShellEditorServices.Hosting/Internal/NamedPipeUtils.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections.Generic; using System.IO; using System.IO.Pipes; @@ -79,8 +78,7 @@ internal static NamedPipeServerStream CreateNamedPipe( /// A named pipe name or name suffix that is safe to you. public static string GenerateValidNamedPipeName(IReadOnlyCollection prefixes = null) { - int tries = 0; - do + for (int i = 0; i < 10; i++) { string pipeName = $"PSES_{Path.GetRandomFileName()}"; @@ -111,8 +109,7 @@ public static string GenerateValidNamedPipeName(IReadOnlyCollection pref { return pipeName; } - - } while (tries < 10); + } throw new IOException("Unable to create named pipe; no available names"); } @@ -146,7 +143,6 @@ public static string GetNamedPipePath(string pipeName) return Path.Combine(Path.GetTempPath(), $"CoreFxPipe_{pipeName}"); } #endif - return $@"\\.\pipe\{pipeName}"; } } diff --git a/src/PowerShellEditorServices.Hosting/Internal/PsesLoadContext.cs b/src/PowerShellEditorServices.Hosting/Internal/PsesLoadContext.cs index bf0d0da16..da6588f7e 100644 --- a/src/PowerShellEditorServices.Hosting/Internal/PsesLoadContext.cs +++ b/src/PowerShellEditorServices.Hosting/Internal/PsesLoadContext.cs @@ -61,10 +61,7 @@ private void TrySetName(string name) "_name", BindingFlags.NonPublic | BindingFlags.Instance); - if (nameBackingField != null) - { - nameBackingField.SetValue(this, name); - } + nameBackingField?.SetValue(this, name); } catch { diff --git a/src/PowerShellEditorServices.VSCode/Cmdlets/VSCodeHtmlContentViewCommands.cs b/src/PowerShellEditorServices.VSCode/Cmdlets/VSCodeHtmlContentViewCommands.cs index f7d090ff8..4e68c4ff7 100644 --- a/src/PowerShellEditorServices.VSCode/Cmdlets/VSCodeHtmlContentViewCommands.cs +++ b/src/PowerShellEditorServices.VSCode/Cmdlets/VSCodeHtmlContentViewCommands.cs @@ -3,11 +3,8 @@ using System; using System.Management.Automation; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Extensions; using Microsoft.PowerShell.EditorServices.VSCode.CustomViews; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace Microsoft.PowerShell.EditorServices.VSCode { @@ -109,10 +106,12 @@ public class SetVSCodeHtmlContentViewCommand : PSCmdlet /// protected override void BeginProcessing() { - HtmlContent htmlContent = new(); - htmlContent.BodyContent = HtmlBodyContent; - htmlContent.JavaScriptPaths = JavaScriptPaths; - htmlContent.StyleSheetPaths = StyleSheetPaths; + HtmlContent htmlContent = new() + { + BodyContent = HtmlBodyContent, + JavaScriptPaths = JavaScriptPaths, + StyleSheetPaths = StyleSheetPaths + }; try { HtmlContentView.SetContentAsync(htmlContent).GetAwaiter().GetResult(); diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs index aa49f3607..f4bbb6372 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs @@ -13,9 +13,9 @@ internal abstract class CustomViewBase : ICustomView public Guid Id { get; private set; } - public string Title { get; private set; } + public string Title { get; } - protected CustomViewType ViewType { get; private set; } + protected CustomViewType ViewType { get; } public CustomViewBase( string viewTitle, diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentView.cs b/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentView.cs index 92fa8be0e..c9c9a70bc 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentView.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentView.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.VSCode.CustomViews diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentViews.cs b/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentViews.cs index 15c1e7df3..a0be1b79e 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentViews.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentViews.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.VSCode.CustomViews diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/ViewColumn.cs b/src/PowerShellEditorServices.VSCode/CustomViews/ViewColumn.cs index 8d43794ea..66fce06b6 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/ViewColumn.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/ViewColumn.cs @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; -using System.Threading.Tasks; - namespace Microsoft.PowerShell.EditorServices.VSCode.CustomViews { /// diff --git a/src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs b/src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs index 38e5df692..cd5cc2924 100644 --- a/src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs +++ b/src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs @@ -141,7 +141,6 @@ public object GetServiceByAssemblyQualifiedName(string asmQualifiedTypeName) /// /// This method is intended as a trapdoor and should not be used in the first instance. /// Consider using the public extension services if possible. - /// /// Also note that services in PSES may live in a separate assembly load context, /// meaning that a type of the seemingly correct name may fail to fetch to a service /// that is known under a type of the same name but loaded in a different context. diff --git a/src/PowerShellEditorServices/Extensions/EditorCommand.cs b/src/PowerShellEditorServices/Extensions/EditorCommand.cs index 966adff27..f330b4ae9 100644 --- a/src/PowerShellEditorServices/Extensions/EditorCommand.cs +++ b/src/PowerShellEditorServices/Extensions/EditorCommand.cs @@ -16,23 +16,23 @@ public sealed class EditorCommand /// /// Gets the name which uniquely identifies the command. /// - public string Name { get; private set; } + public string Name { get; } /// /// Gets the display name for the command. /// - public string DisplayName { get; private set; } + public string DisplayName { get; } /// /// Gets the boolean which determines whether this command's /// output should be suppressed. /// - public bool SuppressOutput { get; private set; } + public bool SuppressOutput { get; } /// /// Gets the ScriptBlock which can be used to execute the command. /// - public ScriptBlock ScriptBlock { get; private set; } + public ScriptBlock ScriptBlock { get; } #endregion @@ -84,4 +84,3 @@ public EditorCommand( #endregion } } - diff --git a/src/PowerShellEditorServices/Extensions/EditorCommandAttribute.cs b/src/PowerShellEditorServices/Extensions/EditorCommandAttribute.cs index fffca9ee1..ad1cc953b 100644 --- a/src/PowerShellEditorServices/Extensions/EditorCommandAttribute.cs +++ b/src/PowerShellEditorServices/Extensions/EditorCommandAttribute.cs @@ -12,7 +12,6 @@ namespace Microsoft.PowerShell.EditorServices.Extensions [AttributeUsage(AttributeTargets.Class)] public sealed class EditorCommandAttribute : Attribute { - #region Properties /// diff --git a/src/PowerShellEditorServices/Extensions/EditorContext.cs b/src/PowerShellEditorServices/Extensions/EditorContext.cs index d223dcf6a..fef641a28 100644 --- a/src/PowerShellEditorServices/Extensions/EditorContext.cs +++ b/src/PowerShellEditorServices/Extensions/EditorContext.cs @@ -21,17 +21,17 @@ public sealed class EditorContext /// /// Gets the FileContext for the active file. /// - public FileContext CurrentFile { get; private set; } + public FileContext CurrentFile { get; } /// /// Gets the BufferRange representing the current selection in the file. /// - public IFileRange SelectedRange { get; private set; } + public IFileRange SelectedRange { get; } /// /// Gets the FilePosition representing the current cursor position. /// - public IFilePosition CursorPosition { get; private set; } + public IFilePosition CursorPosition { get; } #endregion diff --git a/src/PowerShellEditorServices/Extensions/EditorFileRanges.cs b/src/PowerShellEditorServices/Extensions/EditorFileRanges.cs index cbefa4277..281e3411e 100644 --- a/src/PowerShellEditorServices/Extensions/EditorFileRanges.cs +++ b/src/PowerShellEditorServices/Extensions/EditorFileRanges.cs @@ -31,7 +31,6 @@ public static FileScriptPosition FromPosition(FileContext file, int lineNumber, public static FileScriptPosition FromOffset(FileContext file, int offset) { - int line = 1; string fileText = file.Ast.Extent.Text; @@ -407,7 +406,6 @@ public LspCurrentFileContext(ClientEditorContext editorContext) /// public static class FileObjectExtensionMethods { - /// /// Convert a 1-based file position to a 0-based file position. /// diff --git a/src/PowerShellEditorServices/Extensions/EditorObject.cs b/src/PowerShellEditorServices/Extensions/EditorObject.cs index 64585a139..f1bcd0b8b 100644 --- a/src/PowerShellEditorServices/Extensions/EditorObject.cs +++ b/src/PowerShellEditorServices/Extensions/EditorObject.cs @@ -61,12 +61,12 @@ public class EditorObject /// /// Gets the workspace interface for the editor API. /// - public EditorWorkspace Workspace { get; private set; } + public EditorWorkspace Workspace { get; } /// /// Gets the window interface for the editor API. /// - public EditorWindow Window { get; private set; } + public EditorWindow Window { get; } #endregion diff --git a/src/PowerShellEditorServices/Extensions/EditorRequests.cs b/src/PowerShellEditorServices/Extensions/EditorRequests.cs index 47cc691e5..446cd2dfc 100644 --- a/src/PowerShellEditorServices/Extensions/EditorRequests.cs +++ b/src/PowerShellEditorServices/Extensions/EditorRequests.cs @@ -22,7 +22,6 @@ internal class ExtensionCommandRemovedNotification public string Name { get; set; } } - internal class GetEditorContextRequest { } @@ -72,4 +71,3 @@ internal class StatusBarMessageDetails public int? Timeout { get; set; } } } - diff --git a/src/PowerShellEditorServices/Extensions/EditorWindow.cs b/src/PowerShellEditorServices/Extensions/EditorWindow.cs index 072b76f99..ac986308a 100644 --- a/src/PowerShellEditorServices/Extensions/EditorWindow.cs +++ b/src/PowerShellEditorServices/Extensions/EditorWindow.cs @@ -20,7 +20,7 @@ public sealed class EditorWindow /// /// Gets the terminal interface for the editor API. /// - public EditorTerminal Terminal { get; private set; } + public EditorTerminal Terminal { get; } #endregion diff --git a/src/PowerShellEditorServices/Extensions/FileContext.cs b/src/PowerShellEditorServices/Extensions/FileContext.cs index ecf78e14f..0841f0cc3 100644 --- a/src/PowerShellEditorServices/Extensions/FileContext.cs +++ b/src/PowerShellEditorServices/Extensions/FileContext.cs @@ -38,7 +38,7 @@ public sealed class FileContext /// /// Gets the language of the file. /// - public string Language { get; private set; } + public string Language { get; } /// /// Gets the filesystem path of the file. diff --git a/src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs b/src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs index 2d21c0bda..d764d2155 100644 --- a/src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs +++ b/src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs @@ -28,17 +28,20 @@ namespace Microsoft.PowerShell.EditorServices.Hosting /// cref="Microsoft.Extensions.Logging"/> and . /// - internal class EditorServicesServerFactory : IDisposable + internal sealed class EditorServicesServerFactory : IDisposable { /// /// Create a new Editor Services factory. This method will instantiate logging. /// /// + /// /// This can only be called once because it sets global state (the logger) and that call is /// in . - /// + /// + /// /// TODO: Why is this a static function wrapping a constructor instead of just a /// constructor? In the end it returns an instance (albeit a "singleton"). + /// /// /// The path of the log file to use. /// The minimum log level to use. @@ -60,7 +63,7 @@ public static EditorServicesServerFactory Create(string logPath, int minimumLogL // Hook up logging from the host so that its recorded in the log file hostLogger.Subscribe(new HostLoggerAdapter(loggerFactory)); - return new EditorServicesServerFactory(loggerFactory, (LogLevel)minimumLogLevel); + return new EditorServicesServerFactory(loggerFactory); } // TODO: Can we somehow refactor this member so the language and debug servers can be @@ -68,16 +71,7 @@ public static EditorServicesServerFactory Create(string logPath, int minimumLogL // methods? private readonly ILoggerFactory _loggerFactory; - private readonly Microsoft.Extensions.Logging.ILogger _logger; - - private readonly LogLevel _minimumLogLevel; - - private EditorServicesServerFactory(ILoggerFactory loggerFactory, LogLevel minimumLogLevel) - { - _loggerFactory = loggerFactory; - _logger = loggerFactory.CreateLogger(); - _minimumLogLevel = minimumLogLevel; - } + private EditorServicesServerFactory(ILoggerFactory loggerFactory) => _loggerFactory = loggerFactory; /// /// Create the LSP server. @@ -108,15 +102,13 @@ public PsesLanguageServer CreateLanguageServer( public PsesDebugServer CreateDebugServerWithLanguageServer( Stream inputStream, Stream outputStream, - PsesLanguageServer languageServer, - bool usePSReadLine) + PsesLanguageServer languageServer) { return new PsesDebugServer( _loggerFactory, inputStream, outputStream, - languageServer.LanguageServer.Services, - usePSReadLine); + languageServer.LanguageServer.Services); } /// @@ -132,15 +124,13 @@ public PsesDebugServer CreateDebugServerWithLanguageServer( public PsesDebugServer RecreateDebugServer( Stream inputStream, Stream outputStream, - PsesDebugServer debugServer, - bool usePSReadLine) + PsesDebugServer debugServer) { return new PsesDebugServer( _loggerFactory, inputStream, outputStream, - debugServer.ServiceProvider, - usePSReadLine); + debugServer.ServiceProvider); } /// @@ -160,7 +150,7 @@ public PsesDebugServer CreateDebugServerForTempSession( .ClearProviders() .AddSerilog() .SetMinimumLevel(LogLevel.Trace)) // TODO: Why randomly set to trace? - .AddSingleton(provider => null) + .AddSingleton(_ => null) .AddPsesLanguageServices(hostStartupInfo) // For a Temp session, there is no LanguageServer so just set it to null .AddSingleton( @@ -178,18 +168,17 @@ public PsesDebugServer CreateDebugServerForTempSession( _loggerFactory, inputStream, outputStream, - serviceProvider, - usePSReadLine: hostStartupInfo.ConsoleReplEnabled && !hostStartupInfo.UsesLegacyReadLine); + serviceProvider); } - /// + /// /// TODO: This class probably should not be as the primary /// intention of that interface is to provide cleanup of unmanaged resources, which the /// logger certainly is not. Nor is this class used with a . Instead, /// this class should call in a finalizer. This /// could potentially even be done with by passing dispose=true. - /// + /// public void Dispose() { Log.CloseAndFlush(); diff --git a/src/PowerShellEditorServices/Server/PsesDebugServer.cs b/src/PowerShellEditorServices/Server/PsesDebugServer.cs index a5b7fe298..8d7ebf22c 100644 --- a/src/PowerShellEditorServices/Server/PsesDebugServer.cs +++ b/src/PowerShellEditorServices/Server/PsesDebugServer.cs @@ -9,7 +9,6 @@ using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Handlers; using Microsoft.PowerShell.EditorServices.Services; -using Microsoft.PowerShell.EditorServices.Services.PowerShell.Debugging; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Host; using OmniSharp.Extensions.DebugAdapter.Server; using OmniSharp.Extensions.LanguageServer.Server; @@ -23,7 +22,6 @@ internal class PsesDebugServer : IDisposable { private readonly Stream _inputStream; private readonly Stream _outputStream; - private readonly bool _usePSReadLine; private readonly TaskCompletionSource _serverStopped; private DebugAdapterServer _debugAdapterServer; @@ -38,15 +36,13 @@ public PsesDebugServer( ILoggerFactory factory, Stream inputStream, Stream outputStream, - IServiceProvider serviceProvider, - bool usePSReadLine) + IServiceProvider serviceProvider) { _loggerFactory = factory; _inputStream = inputStream; _outputStream = outputStream; ServiceProvider = serviceProvider; _serverStopped = new TaskCompletionSource(); - _usePSReadLine = usePSReadLine; } internal IServiceProvider ServiceProvider { get; } @@ -91,7 +87,7 @@ public async Task StartAsync() .WithHandler() // The OnInitialize delegate gets run when we first receive the _Initialize_ request: // https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Initialize - .OnInitialize(async (server, request, cancellationToken) => + .OnInitialize(async (server, _, _) => { // We need to make sure the host has been started _startedPses = !await _psesHost.TryStartAsync(new HostStartOptions(), CancellationToken.None).ConfigureAwait(false); @@ -105,7 +101,7 @@ public async Task StartAsync() }) // The OnInitialized delegate gets run right before the server responds to the _Initialize_ request: // https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Initialize - .OnInitialized((server, request, response, cancellationToken) => + .OnInitialized((_, _, response, _) => { response.SupportsConditionalBreakpoints = true; response.SupportsConfigurationDoneRequest = true; diff --git a/src/PowerShellEditorServices/Server/PsesLanguageServer.cs b/src/PowerShellEditorServices/Server/PsesLanguageServer.cs index 63072e72d..204ae88d9 100644 --- a/src/PowerShellEditorServices/Server/PsesLanguageServer.cs +++ b/src/PowerShellEditorServices/Server/PsesLanguageServer.cs @@ -23,7 +23,7 @@ namespace Microsoft.PowerShell.EditorServices.Server /// internal class PsesLanguageServer { - internal ILoggerFactory LoggerFactory { get; private set; } + internal ILoggerFactory LoggerFactory { get; } internal ILanguageServer LanguageServer { get; private set; } @@ -117,7 +117,7 @@ public async Task StartAsync() // _Initialize_ request: // https://microsoft.github.io/language-server-protocol/specifications/specification-current/#initialize .OnInitialize( - (languageServer, request, cancellationToken) => + (languageServer, request, _) => { Log.Logger.Debug("Initializing OmniSharp Language Server"); diff --git a/src/PowerShellEditorServices/Services/Analysis/AnalysisService.cs b/src/PowerShellEditorServices/Services/Analysis/AnalysisService.cs index 728891e65..e29063f19 100644 --- a/src/PowerShellEditorServices/Services/Analysis/AnalysisService.cs +++ b/src/PowerShellEditorServices/Services/Analysis/AnalysisService.cs @@ -247,7 +247,7 @@ public async Task>> Ge /// /// The sender of the configuration update event. /// The new language server settings. - public void OnConfigurationUpdated(object sender, LanguageServerSettings settings) + public void OnConfigurationUpdated(object _, LanguageServerSettings settings) { if (settings.ScriptAnalysis.Enable ?? true) { @@ -451,7 +451,6 @@ private static DiagnosticSeverity MapDiagnosticSeverity(ScriptFileMarkerLevel ma ScriptFileMarkerLevel.Information => DiagnosticSeverity.Information, _ => DiagnosticSeverity.Error, }; - ; } private static Hashtable GetCommentHelpRuleSettings(string helpLocation, bool forBlockComment) @@ -477,8 +476,7 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - if (_analysisEngineLazy != null - && _analysisEngineLazy.IsValueCreated) + if (_analysisEngineLazy?.IsValueCreated == true) { _analysisEngineLazy.Value.Dispose(); } @@ -505,7 +503,7 @@ public void Dispose() => /// private class CorrectionTableEntry { - public static CorrectionTableEntry CreateForFile(ScriptFile file) => new(); + public static CorrectionTableEntry CreateForFile(ScriptFile _) => new(); public CorrectionTableEntry() { diff --git a/src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs b/src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs index dc416d49b..b6d5ed7d4 100644 --- a/src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs +++ b/src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs @@ -217,7 +217,6 @@ public async Task FormatAsync(string scriptDefinition, Hashtable formatS /// An array of markers indicating script analysis diagnostics. public Task AnalyzeScriptAsync(string scriptContent) => AnalyzeScriptAsync(scriptContent, settings: null); - /// /// Analyze a given script using PSScriptAnalyzer. /// diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs b/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs index e14c0bf0f..e0854cb2b 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs @@ -368,21 +368,18 @@ public async Task SetVariableAsync(int variableContainerReferenceId, str throw new InvalidPowerShellExpressionException(errorRecord.ToString()); } - // OK, now we have a PS object from the supplied value string (expression) to assign to a variable. - // Get the variable referenced by variableContainerReferenceId and variable name. - VariableContainerDetails variableContainer = null; await debugInfoHandle.WaitAsync().ConfigureAwait(false); try { - variableContainer = (VariableContainerDetails)variables[variableContainerReferenceId]; + // OK, now we have a PS object from the supplied value string (expression) to assign to a variable. + // Get the variable referenced by variableContainerReferenceId and variable name. + VariableContainerDetails variableContainer = (VariableContainerDetails)variables[variableContainerReferenceId]; } finally { debugInfoHandle.Release(); } - VariableDetailsBase variable = variableContainer.Children[name]; - // Determine scope in which the variable lives so we can pass it to `Get-Variable // -Scope`. The default is scope 0 which is safe because if a user is able to see a // variable in the debugger and so change it through this interface, it's either in the @@ -790,7 +787,7 @@ private async Task FetchStackFramesAsync(string scriptNameOverride) IReadOnlyList results = await _executionService.ExecutePSCommandAsync(psCommand, CancellationToken.None).ConfigureAwait(false); IEnumerable callStack = isOnRemoteMachine - ? (PSSerializer.Deserialize(results[0].BaseObject as string) as PSObject).BaseObject as IList + ? (PSSerializer.Deserialize(results[0].BaseObject as string) as PSObject)?.BaseObject as IList : results; List stackFrameDetailList = new(); @@ -798,10 +795,10 @@ private async Task FetchStackFramesAsync(string scriptNameOverride) foreach (object callStackFrameItem in callStack) { // We have to use reflection to get the variable dictionary. - IList callStackFrameComponents = (callStackFrameItem as PSObject).BaseObject as IList; + IList callStackFrameComponents = (callStackFrameItem as PSObject)?.BaseObject as IList; PSObject callStackFrame = callStackFrameComponents[0] as PSObject; IDictionary callStackVariables = isOnRemoteMachine - ? (callStackFrameComponents[1] as PSObject).BaseObject as IDictionary + ? (callStackFrameComponents[1] as PSObject)?.BaseObject as IDictionary : callStackFrameComponents[1] as IDictionary; VariableContainerDetails autoVariables = new( @@ -821,7 +818,7 @@ private async Task FetchStackFramesAsync(string scriptNameOverride) VariableInfo psVarInfo = TryVariableInfo(new PSObject(entry.Value)); if (psVarInfo is null) { - _logger.LogError($"A object was received that is not a PSVariable object"); + _logger.LogError("A object was received that is not a PSVariable object"); continue; } @@ -840,7 +837,7 @@ private async Task FetchStackFramesAsync(string scriptNameOverride) // the "Auto" container (not to be confused with Automatic PowerShell variables). // // TODO: We can potentially use `Get-Variable -Scope x` to add relevant local - // variables to other frames but frames and scopes are not perfectly analagous and + // variables to other frames but frames and scopes are not perfectly analogous and // we'd need a way to detect things such as module borders and dot-sourced files. if (isTopStackFrame) { diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointDetails.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointDetails.cs index 6fa667462..4317b0ad3 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointDetails.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointDetails.cs @@ -11,7 +11,7 @@ namespace Microsoft.PowerShell.EditorServices.Services.DebugAdapter /// Provides details about a breakpoint that is set in the /// PowerShell debugger. /// - internal class BreakpointDetails : BreakpointDetailsBase + internal sealed class BreakpointDetails : BreakpointDetailsBase { /// /// Gets the unique ID of the breakpoint. diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/CommandBreakpointDetails.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/CommandBreakpointDetails.cs index fdef14a15..09dd16809 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/CommandBreakpointDetails.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/CommandBreakpointDetails.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell.EditorServices.Services.DebugAdapter /// /// Provides details about a command breakpoint that is set in the PowerShell debugger. /// - internal class CommandBreakpointDetails : BreakpointDetailsBase + internal sealed class CommandBreakpointDetails : BreakpointDetailsBase { /// /// Gets the name of the command on which the command breakpoint has been set. @@ -27,12 +27,8 @@ private CommandBreakpointDetails() /// /// The name of the command to break on. /// Condition string that would be applied to the breakpoint Action parameter. - /// Hit condition string that would be applied to the breakpoint Action parameter. /// - internal static CommandBreakpointDetails Create( - string name, - string condition = null, - string hitCondition = null) + internal static CommandBreakpointDetails Create(string name, string condition = null) { Validate.IsNotNull(nameof(name), name); @@ -51,7 +47,7 @@ internal static CommandBreakpointDetails Create( /// A new instance of the BreakpointDetails class. internal static CommandBreakpointDetails Create(Breakpoint breakpoint) { - Validate.IsNotNull("breakpoint", breakpoint); + Validate.IsNotNull(nameof(breakpoint), breakpoint); if (breakpoint is not CommandBreakpoint commandBreakpoint) { @@ -59,14 +55,12 @@ internal static CommandBreakpointDetails Create(Breakpoint breakpoint) "Unexpected breakpoint type: " + breakpoint.GetType().Name); } - CommandBreakpointDetails breakpointDetails = new() + return new() { Verified = true, Name = commandBreakpoint.Command, Condition = commandBreakpoint.Action?.ToString() }; - - return breakpointDetails; } } } diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/DebuggerStoppedEventArgs.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/DebuggerStoppedEventArgs.cs index fa83e5dba..0b2d47c30 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/DebuggerStoppedEventArgs.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/DebuggerStoppedEventArgs.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using System.Management.Automation; -using System.Security.Cryptography; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Runspace; using Microsoft.PowerShell.EditorServices.Utility; @@ -20,7 +19,7 @@ internal class DebuggerStoppedEventArgs /// If 'IsRemoteSession' returns true, this path will be a local filesystem /// path containing the contents of the script that is executing remotely. /// - public string ScriptPath { get; private set; } + public string ScriptPath { get; } /// /// Returns true if the breakpoint was raised from a remote debugging session. @@ -30,12 +29,12 @@ internal class DebuggerStoppedEventArgs /// /// Gets the original script path if 'IsRemoteSession' returns true. /// - public string RemoteScriptPath { get; private set; } + public string RemoteScriptPath { get; } /// /// Gets the RunspaceDetails for the current runspace. /// - public IRunspaceInfo RunspaceInfo { get; private set; } + public IRunspaceInfo RunspaceInfo { get; } /// /// Gets the line number at which the debugger stopped execution. @@ -50,7 +49,7 @@ internal class DebuggerStoppedEventArgs /// /// Gets the original DebuggerStopEventArgs from the PowerShell engine. /// - public DebuggerStopEventArgs OriginalEvent { get; private set; } + public DebuggerStopEventArgs OriginalEvent { get; } #endregion diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableDetails.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableDetails.cs index b0ff245ed..96a6b2b99 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableDetails.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableDetails.cs @@ -101,8 +101,6 @@ public VariableDetails(string name, object value) /// public override VariableDetailsBase[] GetChildren(ILogger logger) { - VariableDetails[] childVariables = null; - if (IsExpandable) { if (cachedChildren == null) @@ -112,12 +110,8 @@ public override VariableDetailsBase[] GetChildren(ILogger logger) return cachedChildren; } - else - { - childVariables = Array.Empty(); - } - return childVariables; + return Array.Empty(); } #endregion @@ -153,7 +147,6 @@ valueObject is not decimal && private static string GetValueStringAndType(object value, bool isExpandable, out string typeName) { - string valueString = null; typeName = null; if (value == null) @@ -167,13 +160,14 @@ private static string GetValueStringAndType(object value, bool isExpandable, out // This is the type format PowerShell users expect and will appear when you hover a variable name typeName = '[' + objType.FullName + ']'; - if (value is bool) + string valueString; + if (value is bool x) { // Set to identifier recognized by PowerShell to make setVariable from the debug UI more natural. - valueString = (bool)value ? "$true" : "$false"; + valueString = x ? "$true" : "$false"; // We need to use this "magic value" to highlight in vscode properly - // These "magic values" are analagous to TypeScript and are visible in VSCode here: + // These "magic values" are analogous to TypeScript and are visible in VSCode here: // https://github.com/microsoft/vscode/blob/57ca9b99d5b6a59f2d2e0f082ae186559f45f1d8/src/vs/workbench/contrib/debug/browser/baseDebugView.ts#L68-L78 // NOTE: we don't do numbers and strings since they (so far) seem to get detected properly by // serialization, and the original .NET type can be preserved so it shows up in the variable name @@ -191,7 +185,7 @@ private static string GetValueStringAndType(object value, bool isExpandable, out else { string valueToString = value.SafeToString(); - if (valueToString == null || valueToString.Equals(objType.ToString())) + if (valueToString?.Equals(objType.ToString()) != false) { // If the ToString() matches the type name or is null, then display the type // name in PowerShell format. @@ -230,24 +224,16 @@ private static string GetValueStringAndType(object value, bool isExpandable, out private static string InsertDimensionSize(string value, int dimensionSize) { - string result = value; - int indexLastRBracket = value.LastIndexOf("]"); if (indexLastRBracket > 0) { - result = - value.Substring(0, indexLastRBracket) + + return value.Substring(0, indexLastRBracket) + dimensionSize + value.Substring(indexLastRBracket); } - else - { - // Types like ArrayList don't use [] in type name so - // display value like so - [ArrayList: 5] - result = value + ": " + dimensionSize; - } - - return result; + // Types like ArrayList don't use [] in type name so + // display value like so - [ArrayList: 5] + return value + ": " + dimensionSize; } private VariableDetails[] GetChildren(object obj, ILogger logger) @@ -277,7 +263,7 @@ private VariableDetails[] GetChildren(object obj, ILogger logger) // If a PSObject other than a PSCustomObject, unwrap it. if (psObject != null) { - // First add the PSObject's ETS propeties + // First add the PSObject's ETS properties childVariables.AddRange( psObject .Properties @@ -303,7 +289,7 @@ private VariableDetails[] GetChildren(object obj, ILogger logger) // It turns out that iteration via C#'s foreach loop, operates on the variable's // type which in this case is IDictionary. IDictionary was designed to always // return DictionaryEntry objects upon iteration and the Dictionary<,> implementation - // honors that when the object is reintepreted as an IDictionary object. + // honors that when the object is reinterpreted as an IDictionary object. // FYI, a test case for this is to open $PSBoundParameters when debugging a // function that defines parameters and has been passed parameters. // If you open the $PSBoundParameters variable node in this scenario and see nothing, diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableScope.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableScope.cs index d5faee6cc..bda463dc2 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableScope.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableScope.cs @@ -13,12 +13,12 @@ internal class VariableScope /// Gets a numeric ID that can be used in future operations /// relating to this scope. /// - public int Id { get; private set; } + public int Id { get; } /// /// Gets a name that describes the variable scope. /// - public string Name { get; private set; } + public string Name { get; } /// /// Initializes a new instance of the VariableScope class with diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/BreakpointHandlers.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/BreakpointHandlers.cs index c40cb1e3a..03f2841f2 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/BreakpointHandlers.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/BreakpointHandlers.cs @@ -128,8 +128,7 @@ public async Task Handle(SetFunctionBreakpointsA CommandBreakpointDetails[] breakpointDetails = request.Breakpoints .Select((funcBreakpoint) => CommandBreakpointDetails.Create( funcBreakpoint.Name, - funcBreakpoint.Condition, - funcBreakpoint.HitCondition)) + funcBreakpoint.Condition)) .ToArray(); // If this is a "run without debugging (Ctrl+F5)" session ignore requests to set breakpoints. @@ -147,7 +146,7 @@ await _debugService.SetCommandBreakpointsAsync( catch (Exception e) { // Log whatever the error is - _logger.LogException($"Caught error while setting command breakpoints", e); + _logger.LogException("Caught error while setting command breakpoints", e); } finally { diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs index d140ba2dc..04adf185e 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.DebugAdapter; using Microsoft.PowerShell.EditorServices.Utility; @@ -15,16 +14,9 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class ScopesHandler : IScopesHandler { - private readonly ILogger _logger; private readonly DebugService _debugService; - public ScopesHandler( - ILoggerFactory loggerFactory, - DebugService debugService) - { - _logger = loggerFactory.CreateLogger(); - _debugService = debugService; - } + public ScopesHandler(DebugService debugService) => _debugService = debugService; public Task Handle(ScopesArguments request, CancellationToken cancellationToken) { diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs index 5f9c8242e..fb3b5e17e 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.DebugAdapter; using Microsoft.PowerShell.EditorServices.Utility; @@ -16,16 +15,9 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class StackTraceHandler : IStackTraceHandler { - private readonly ILogger _logger; private readonly DebugService _debugService; - public StackTraceHandler( - ILoggerFactory loggerFactory, - DebugService debugService) - { - _logger = loggerFactory.CreateLogger(); - _debugService = debugService; - } + public StackTraceHandler(DebugService debugService) => _debugService = debugService; public Task Handle(StackTraceArguments request, CancellationToken cancellationToken) { diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/VariablesHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/VariablesHandler.cs index a97232c06..a4f5259ed 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/VariablesHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/VariablesHandler.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.DebugAdapter; using Microsoft.PowerShell.EditorServices.Utility; @@ -15,16 +14,9 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class VariablesHandler : IVariablesHandler { - private readonly ILogger _logger; private readonly DebugService _debugService; - public VariablesHandler( - ILoggerFactory loggerFactory, - DebugService debugService) - { - _logger = loggerFactory.CreateLogger(); - _debugService = debugService; - } + public VariablesHandler(DebugService debugService) => _debugService = debugService; public Task Handle(VariablesArguments request, CancellationToken cancellationToken) { diff --git a/src/PowerShellEditorServices/Services/Extension/EditorOperationsService.cs b/src/PowerShellEditorServices/Services/Extension/EditorOperationsService.cs index 6812cb81c..0f0f2a01a 100644 --- a/src/PowerShellEditorServices/Services/Extension/EditorOperationsService.cs +++ b/src/PowerShellEditorServices/Services/Extension/EditorOperationsService.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using Microsoft.PowerShell.EditorServices.Extensions; -using Microsoft.PowerShell.EditorServices.Services.PowerShell; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Host; using Microsoft.PowerShell.EditorServices.Services.TextDocument; using OmniSharp.Extensions.LanguageServer.Protocol.Models; @@ -21,17 +20,13 @@ internal class EditorOperationsService : IEditorOperations private readonly ILanguageServerFacade _languageServer; - private readonly IInternalPowerShellExecutionService _executionService; - public EditorOperationsService( PsesInternalHost psesHost, WorkspaceService workspaceService, - IInternalPowerShellExecutionService executionService, ILanguageServerFacade languageServer) { _psesHost = psesHost; _workspaceService = workspaceService; - _executionService = executionService; _languageServer = languageServer; } @@ -40,7 +35,7 @@ public async Task GetEditorContextAsync() if (!TestHasLanguageServer()) { return null; - }; + } ClientEditorContext clientContext = await _languageServer.SendRequest( @@ -57,7 +52,7 @@ public async Task InsertTextAsync(string filePath, string text, BufferRange inse if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/insertText", new InsertTextRequest { @@ -85,7 +80,7 @@ public async Task SetSelectionAsync(BufferRange selectionRange) if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/setSelection", new SetSelectionRequest { @@ -133,7 +128,7 @@ public async Task NewFileAsync() if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/newFile", null) .ReturningVoid(CancellationToken.None) @@ -145,7 +140,7 @@ public async Task OpenFileAsync(string filePath) if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/openFile", new OpenFileDetails { @@ -159,7 +154,7 @@ public async Task OpenFileAsync(string filePath, bool preview) if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/openFile", new OpenFileDetails { @@ -173,7 +168,7 @@ public async Task CloseFileAsync(string filePath) if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/closeFile", filePath) .ReturningVoid(CancellationToken.None) @@ -187,7 +182,7 @@ public async Task SaveFileAsync(string currentPath, string newSavePath) if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/saveFile", new SaveFileDetails { @@ -205,7 +200,7 @@ public async Task ShowInformationMessageAsync(string message) if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/showInformationMessage", message) .ReturningVoid(CancellationToken.None) @@ -217,7 +212,7 @@ public async Task ShowErrorMessageAsync(string message) if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/showErrorMessage", message) .ReturningVoid(CancellationToken.None) @@ -229,7 +224,7 @@ public async Task ShowWarningMessageAsync(string message) if (!TestHasLanguageServer()) { return; - }; + } await _languageServer.SendRequest("editor/showWarningMessage", message) .ReturningVoid(CancellationToken.None) diff --git a/src/PowerShellEditorServices/Services/Extension/Handlers/IInvokeExtensionCommandHandler.cs b/src/PowerShellEditorServices/Services/Extension/Handlers/IInvokeExtensionCommandHandler.cs index 325b74073..fb0ac5002 100644 --- a/src/PowerShellEditorServices/Services/Extension/Handlers/IInvokeExtensionCommandHandler.cs +++ b/src/PowerShellEditorServices/Services/Extension/Handlers/IInvokeExtensionCommandHandler.cs @@ -28,6 +28,5 @@ internal class ClientEditorContext public Position CursorPosition { get; set; } public Range SelectionRange { get; set; } - } } diff --git a/src/PowerShellEditorServices/Services/Extension/PromptEvents.cs b/src/PowerShellEditorServices/Services/Extension/PromptEvents.cs index 9b59e0ba6..ebe595ed1 100644 --- a/src/PowerShellEditorServices/Services/Extension/PromptEvents.cs +++ b/src/PowerShellEditorServices/Services/Extension/PromptEvents.cs @@ -43,4 +43,3 @@ internal class ShowInputPromptResponse public string ResponseText { get; set; } } } - diff --git a/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellVersionDetails.cs b/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellVersionDetails.cs index 157fe865c..14e924c3a 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellVersionDetails.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellVersionDetails.cs @@ -42,23 +42,23 @@ internal class PowerShellVersionDetails /// /// Gets the version of the PowerShell runtime. /// - public Version Version { get; private set; } + public Version Version { get; } /// /// Gets the full version string, either the ToString of the Version /// property or the GitCommitId for open-source PowerShell releases. /// - public string VersionString { get; private set; } + public string VersionString { get; } /// /// Gets the PowerShell edition (generally Desktop or Core). /// - public string Edition { get; private set; } + public string Edition { get; } /// /// Gets the architecture of the PowerShell process. /// - public PowerShellProcessArchitecture Architecture { get; private set; } + public PowerShellProcessArchitecture Architecture { get; } #endregion @@ -117,9 +117,9 @@ public static PowerShellVersionDetails GetVersionDetails(ILogger logger, PowerSh // In the former case, take the value directly. In the latter case, // generate a Version from its string representation. object version = psVersionTable["PSVersion"]; - if (version is Version) + if (version is Version version2) { - powerShellVersion = (Version)version; + powerShellVersion = version2; } else if (version != null) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Debugging/DscBreakpointCapability.cs b/src/PowerShellEditorServices/Services/PowerShell/Debugging/DscBreakpointCapability.cs index 1579c00a6..3f6f05b24 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Debugging/DscBreakpointCapability.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Debugging/DscBreakpointCapability.cs @@ -10,7 +10,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; -using Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution; using System.Threading; using SMA = System.Management.Automation; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility; @@ -95,10 +94,10 @@ public static Task GetDscCapabilityAsync( if ((currentRunspace.PowerShellVersionDetails.Version.Major >= 6) && (currentRunspace.RunspaceOrigin != RunspaceOrigin.DebuggedRunspace)) { - return null; + return Task.FromResult(null); } - Func getDscBreakpointCapabilityFunc = (pwsh, cancellationToken) => + Func getDscBreakpointCapabilityFunc = (pwsh, _) => { PSInvocationSettings invocationSettings = new() { @@ -122,7 +121,7 @@ public static Task GetDscCapabilityAsync( if (dscModule == null) { - logger.LogTrace($"Side-by-side DSC module was not found."); + logger.LogTrace("Side-by-side DSC module was not found."); return null; } @@ -151,7 +150,7 @@ public static Task GetDscCapabilityAsync( if (resourcePaths == null) { - logger.LogTrace($"No DSC resources found."); + logger.LogTrace("No DSC resources found."); return null; } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Execution/BlockingConcurrentDeque.cs b/src/PowerShellEditorServices/Services/PowerShell/Execution/BlockingConcurrentDeque.cs index 197a8bede..035437dd3 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Execution/BlockingConcurrentDeque.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Execution/BlockingConcurrentDeque.cs @@ -83,4 +83,3 @@ public static PriorityQueueBlockLifetime StartBlocking(ManualResetEventSlim bloc } } } - diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/EvaluateHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/EvaluateHandler.cs index 97fd00f5e..ac617b094 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/EvaluateHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/EvaluateHandler.cs @@ -4,10 +4,8 @@ using System.Management.Automation; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services.PowerShell; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution; -using Microsoft.PowerShell.EditorServices.Utility; namespace Microsoft.PowerShell.EditorServices.Handlers { @@ -17,16 +15,9 @@ namespace Microsoft.PowerShell.EditorServices.Handlers /// internal class EvaluateHandler : IEvaluateHandler { - private readonly ILogger _logger; private readonly IInternalPowerShellExecutionService _executionService; - public EvaluateHandler( - ILoggerFactory factory, - IInternalPowerShellExecutionService executionService) - { - _logger = factory.CreateLogger(); - _executionService = executionService; - } + public EvaluateHandler(IInternalPowerShellExecutionService executionService) => _executionService = executionService; public async Task Handle(EvaluateRequestArguments request, CancellationToken cancellationToken) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/ExpandAliasHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/ExpandAliasHandler.cs index 92141cc89..69c39450d 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/ExpandAliasHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/ExpandAliasHandler.cs @@ -1,11 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System.Linq; using System.Management.Automation; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using MediatR; using OmniSharp.Extensions.JsonRpc; using Microsoft.PowerShell.EditorServices.Services.PowerShell; @@ -27,14 +25,9 @@ internal class ExpandAliasResult internal class ExpandAliasHandler : IExpandAliasHandler { - private readonly ILogger _logger; private readonly IInternalPowerShellExecutionService _executionService; - public ExpandAliasHandler(ILoggerFactory factory, IInternalPowerShellExecutionService executionService) - { - _logger = factory.CreateLogger(); - _executionService = executionService; - } + public ExpandAliasHandler(IInternalPowerShellExecutionService executionService) => _executionService = executionService; public async Task Handle(ExpandAliasParams request, CancellationToken cancellationToken) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommandHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommandHandler.cs index 12b8b797e..12df83713 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommandHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommandHandler.cs @@ -5,7 +5,6 @@ using System.Management.Automation; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using MediatR; using OmniSharp.Extensions.JsonRpc; using Microsoft.PowerShell.EditorServices.Services.PowerShell; @@ -32,14 +31,9 @@ internal class PSCommandMessage internal class GetCommandHandler : IGetCommandHandler { - private readonly ILogger _logger; private readonly IInternalPowerShellExecutionService _executionService; - public GetCommandHandler(ILoggerFactory factory, IInternalPowerShellExecutionService executionService) - { - _logger = factory.CreateLogger(); - _executionService = executionService; - } + public GetCommandHandler(IInternalPowerShellExecutionService executionService) => _executionService = executionService; public async Task> Handle(GetCommandParams request, CancellationToken cancellationToken) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommentHelpHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommentHelpHandler.cs index 782d8e989..27288ce90 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommentHelpHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommentHelpHandler.cs @@ -6,7 +6,6 @@ using System.Management.Automation.Language; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.TextDocument; @@ -14,21 +13,15 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class GetCommentHelpHandler : IGetCommentHelpHandler { - private readonly ILogger _logger; private readonly WorkspaceService _workspaceService; private readonly AnalysisService _analysisService; - private readonly SymbolsService _symbolsService; public GetCommentHelpHandler( - ILoggerFactory factory, WorkspaceService workspaceService, - AnalysisService analysisService, - SymbolsService symbolsService) + AnalysisService analysisService) { - _logger = factory.CreateLogger(); _workspaceService = workspaceService; _analysisService = analysisService; - _symbolsService = symbolsService; } public async Task Handle(CommentHelpRequestParams request, CancellationToken cancellationToken) @@ -77,8 +70,7 @@ public async Task Handle(CommentHelpRequestParams requ List helpLines = ScriptFile.GetLinesInternal(helpText); - if (helpLocation != null && - !helpLocation.Equals("before", StringComparison.OrdinalIgnoreCase)) + if (helpLocation?.Equals("before", StringComparison.OrdinalIgnoreCase) == false) { // we need to trim the leading `{` and newline when helpLocation=="begin" helpLines.RemoveAt(helpLines.Count - 1); diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetVersionHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetVersionHandler.cs index 58b0f5d89..b500b7c1e 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetVersionHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetVersionHandler.cs @@ -2,43 +2,15 @@ // Licensed under the MIT License. using System; -using System.Management.Automation; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.PowerShell; -using Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution; -using Microsoft.PowerShell.EditorServices.Services.PowerShell.Runspace; using Microsoft.PowerShell.EditorServices.Utility; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using OmniSharp.Extensions.LanguageServer.Protocol.Window; namespace Microsoft.PowerShell.EditorServices.Handlers { internal class GetVersionHandler : IGetVersionHandler { - private readonly ILogger _logger; - private readonly IRunspaceContext _runspaceContext; - private readonly IInternalPowerShellExecutionService _executionService; - private readonly ILanguageServerFacade _languageServer; - private readonly ConfigurationService _configurationService; - - public GetVersionHandler( - ILoggerFactory factory, - IRunspaceContext runspaceContext, - IInternalPowerShellExecutionService executionService, - ILanguageServerFacade languageServer, - ConfigurationService configurationService) - { - _logger = factory.CreateLogger(); - _runspaceContext = runspaceContext; - _executionService = executionService; - _languageServer = languageServer; - _configurationService = configurationService; - } - public async Task Handle(GetVersionParams request, CancellationToken cancellationToken) { PowerShellProcessArchitecture architecture = PowerShellProcessArchitecture.Unknown; diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/ShowHelpHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/ShowHelpHandler.cs index 5e13a5f8b..d2f84b01b 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/ShowHelpHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/ShowHelpHandler.cs @@ -4,7 +4,6 @@ using System.Management.Automation; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using MediatR; using OmniSharp.Extensions.JsonRpc; using Microsoft.PowerShell.EditorServices.Services.PowerShell; @@ -22,14 +21,9 @@ internal class ShowHelpParams : IRequest internal class ShowHelpHandler : IShowHelpHandler { - private readonly ILogger _logger; private readonly IInternalPowerShellExecutionService _executionService; - public ShowHelpHandler(ILoggerFactory factory, IInternalPowerShellExecutionService executionService) - { - _logger = factory.CreateLogger(); - _executionService = executionService; - } + public ShowHelpHandler(IInternalPowerShellExecutionService executionService) => _executionService = executionService; public async Task Handle(ShowHelpParams request, CancellationToken cancellationToken) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceInfo.cs b/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceInfo.cs index 60b542b55..d35d0f8a7 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceInfo.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceInfo.cs @@ -89,17 +89,12 @@ public async Task GetDscBreakpointCapabilityAsync( PsesInternalHost psesHost, CancellationToken cancellationToken) { - if (_dscBreakpointCapability is not null) - { - _dscBreakpointCapability = await DscBreakpointCapability.GetDscCapabilityAsync( + return _dscBreakpointCapability ??= await DscBreakpointCapability.GetDscCapabilityAsync( logger, this, psesHost, cancellationToken) .ConfigureAwait(false); - } - - return _dscBreakpointCapability; } } } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Utility/CommandHelpers.cs b/src/PowerShellEditorServices/Services/PowerShell/Utility/CommandHelpers.cs index 4495ebf63..c5963ef78 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Utility/CommandHelpers.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Utility/CommandHelpers.cs @@ -3,7 +3,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; using System.Management.Automation; using System.Threading; using System.Threading.Tasks; @@ -117,7 +116,7 @@ public static async Task GetCommandInfoAsync( /// Gets the command's "Synopsis" documentation section. /// /// The CommandInfo instance for the command. - /// The exeuction service to use for getting command documentation. + /// The execution service to use for getting command documentation. /// The synopsis. public static async Task GetCommandSynopsisAsync( CommandInfo commandInfo, diff --git a/src/PowerShellEditorServices/Services/PowerShell/Utility/PowerShellExtensions.cs b/src/PowerShellEditorServices/Services/PowerShell/Utility/PowerShellExtensions.cs index a34032a89..78748a91f 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Utility/PowerShellExtensions.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Utility/PowerShellExtensions.cs @@ -192,8 +192,7 @@ public static void ImportModule(this PowerShell pwsh, string moduleNameOrPath) public static string GetErrorString(this PowerShell pwsh) { StringBuilder sb = new StringBuilder(capacity: 1024) - .Append("Execution of the following command(s) completed with errors:") - .AppendLine() + .AppendLine("Execution of the following command(s) completed with errors:") .AppendLine() .Append(pwsh.Commands.GetInvocationText()); @@ -211,15 +210,15 @@ private static StringBuilder AddErrorString(this StringBuilder sb, ErrorRecord e { sb.Append("Error #").Append(errorIndex).Append(':').AppendLine() .Append(error).AppendLine() - .Append("ScriptStackTrace:").AppendLine() - .Append(error.ScriptStackTrace ?? "").AppendLine() - .Append("Exception:").AppendLine() + .AppendLine("ScriptStackTrace:") + .AppendLine(error.ScriptStackTrace ?? "") + .AppendLine("Exception:") .Append(" ").Append(error.Exception.ToString() ?? ""); Exception innerException = error.Exception?.InnerException; while (innerException != null) { - sb.Append("InnerException:").AppendLine() + sb.AppendLine("InnerException:") .Append(" ").Append(innerException); innerException = innerException.InnerException; } diff --git a/src/PowerShellEditorServices/Services/Symbols/PesterDocumentSymbolProvider.cs b/src/PowerShellEditorServices/Services/Symbols/PesterDocumentSymbolProvider.cs index 3b1e8a87a..12aa7f68a 100644 --- a/src/PowerShellEditorServices/Services/Symbols/PesterDocumentSymbolProvider.cs +++ b/src/PowerShellEditorServices/Services/Symbols/PesterDocumentSymbolProvider.cs @@ -100,7 +100,7 @@ private static PesterSymbolReference ConvertPesterAstToSymbolReference(ScriptFil CommandElementAst currentCommandElement = pesterCommandAst.CommandElements[i]; // Check for an explicit "-Name" parameter - if (currentCommandElement is CommandParameterAst parameterAst) + if (currentCommandElement is CommandParameterAst) { // Found -Name parameter, move to next element which is the argument for -TestName i++; @@ -184,12 +184,12 @@ internal class PesterSymbolReference : SymbolReference /// /// Gets the name of the test /// - public string TestName { get; private set; } + public string TestName { get; } /// /// Gets the test's command type. /// - public PesterCommandType Command { get; private set; } + public PesterCommandType Command { get; } internal PesterSymbolReference( ScriptFile scriptFile, diff --git a/src/PowerShellEditorServices/Services/Symbols/PsdDocumentSymbolProvider.cs b/src/PowerShellEditorServices/Services/Symbols/PsdDocumentSymbolProvider.cs index fb2c3351c..ff3ffe47b 100644 --- a/src/PowerShellEditorServices/Services/Symbols/PsdDocumentSymbolProvider.cs +++ b/src/PowerShellEditorServices/Services/Symbols/PsdDocumentSymbolProvider.cs @@ -20,8 +20,7 @@ internal class PsdDocumentSymbolProvider : IDocumentSymbolProvider IEnumerable IDocumentSymbolProvider.ProvideDocumentSymbols( ScriptFile scriptFile) { - if ((scriptFile.FilePath != null && - scriptFile.FilePath.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase)) || + if ((scriptFile.FilePath?.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase) == true) || IsPowerShellDataFileAst(scriptFile.ScriptAst)) { FindHashtableSymbolsVisitor findHashtableSymbolsVisitor = new(); @@ -66,7 +65,7 @@ private static bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap return levelAstTypeMatch; } - IEnumerable astsFound = (node.Item as Ast).FindAll(a => a is Ast, false); + IEnumerable astsFound = (node.Item as Ast)?.FindAll(a => a is not null, false); if (astsFound != null) { foreach (Ast astFound in astsFound) diff --git a/src/PowerShellEditorServices/Services/Symbols/ScriptDocumentSymbolProvider.cs b/src/PowerShellEditorServices/Services/Symbols/ScriptDocumentSymbolProvider.cs index b721ee284..9c17f17d5 100644 --- a/src/PowerShellEditorServices/Services/Symbols/ScriptDocumentSymbolProvider.cs +++ b/src/PowerShellEditorServices/Services/Symbols/ScriptDocumentSymbolProvider.cs @@ -34,24 +34,20 @@ IEnumerable IDocumentSymbolProvider.ProvideDocumentSymbols( /// A collection of SymbolReference objects public static IEnumerable FindSymbolsInDocument(Ast scriptAst) { - IEnumerable symbolReferences = null; - // TODO: Restore this when we figure out how to support multiple // PS versions in the new PSES-as-a-module world (issue #276) // if (powerShellVersion >= new Version(5,0)) // { - //#if PowerShellv5 + //#if PowerShell v5 // FindSymbolsVisitor2 findSymbolsVisitor = new FindSymbolsVisitor2(); // scriptAst.Visit(findSymbolsVisitor); // symbolReferences = findSymbolsVisitor.SymbolReferences; //#endif // } // else - FindSymbolsVisitor findSymbolsVisitor = new(); scriptAst.Visit(findSymbolsVisitor); - symbolReferences = findSymbolsVisitor.SymbolReferences; - return symbolReferences; + return findSymbolsVisitor.SymbolReferences; } } } diff --git a/src/PowerShellEditorServices/Services/Symbols/SymbolReference.cs b/src/PowerShellEditorServices/Services/Symbols/SymbolReference.cs index ddaef21e0..25cb15cc1 100644 --- a/src/PowerShellEditorServices/Services/Symbols/SymbolReference.cs +++ b/src/PowerShellEditorServices/Services/Symbols/SymbolReference.cs @@ -46,17 +46,17 @@ internal class SymbolReference : ISymbolReference /// /// Gets the symbol's type /// - public SymbolType SymbolType { get; private set; } + public SymbolType SymbolType { get; } /// /// Gets the name of the symbol /// - public string SymbolName { get; private set; } + public string SymbolName { get; } /// /// Gets the script extent of the symbol /// - public ScriptRegion ScriptRegion { get; private set; } + public ScriptRegion ScriptRegion { get; } /// /// Gets the contents of the line the given symbol is on diff --git a/src/PowerShellEditorServices/Services/Symbols/SymbolsService.cs b/src/PowerShellEditorServices/Services/Symbols/SymbolsService.cs index 96a997a17..f80570b1c 100644 --- a/src/PowerShellEditorServices/Services/Symbols/SymbolsService.cs +++ b/src/PowerShellEditorServices/Services/Symbols/SymbolsService.cs @@ -91,7 +91,7 @@ public SymbolsService( #endregion - public bool TryResgisterCodeLensProvider(ICodeLensProvider codeLensProvider) => _codeLensProviders.TryAdd(codeLensProvider.ProviderId, codeLensProvider); + public bool TryRegisterCodeLensProvider(ICodeLensProvider codeLensProvider) => _codeLensProviders.TryAdd(codeLensProvider.ProviderId, codeLensProvider); public bool DeregisterCodeLensProvider(string providerId) => _codeLensProviders.TryRemove(providerId, out _); @@ -131,7 +131,7 @@ public List FindSymbolsInFile(ScriptFile scriptFile) /// /// The details and contents of a open script file /// The line number of the cursor for the given script - /// The coulumn number of the cursor for the given script + /// The column number of the cursor for the given script /// A SymbolReference of the symbol found at the given location /// or null if there is no symbol at that location /// @@ -229,11 +229,11 @@ public async Task> FindReferencesOfSymbol( } /// - /// Finds all the occurences of a symbol in the script given a file location + /// Finds all the occurrences of a symbol in the script given a file location /// /// The details and contents of a open script file /// The line number of the cursor for the given script - /// The coulumn number of the cursor for the given script + /// The column number of the cursor for the given script /// FindOccurrencesResult public static IReadOnlyList FindOccurrencesInFile( ScriptFile file, @@ -258,7 +258,7 @@ public static IReadOnlyList FindOccurrencesInFile( /// /// The details and contents of a open script file /// The line number of the cursor for the given script - /// The coulumn number of the cursor for the given script + /// The column number of the cursor for the given script /// A SymbolReference of the symbol found at the given location /// or null if there is no symbol at that location /// @@ -317,7 +317,7 @@ public Task FindSymbolDetailsAtLocationAsync( /// /// The details and contents of a open script file /// The line number of the cursor for the given script - /// The coulumn number of the cursor for the given script + /// The column number of the cursor for the given script /// ParameterSetSignatures public async Task FindParameterSetsInFileAsync( ScriptFile file, @@ -542,8 +542,8 @@ private ScriptFile[] GetBuiltinCommandScriptFiles( // find any files where the moduleInfo's path ends with ps1 or psm1 // and add it to allowed script files - if (modPath.EndsWith(@".ps1", StringComparison.OrdinalIgnoreCase) || - modPath.EndsWith(@".psm1", StringComparison.OrdinalIgnoreCase)) + if (modPath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase) || + modPath.EndsWith(".psm1", StringComparison.OrdinalIgnoreCase)) { newFile = _workspaceService.GetFile(modPath); newFile.IsAnalysisEnabled = false; @@ -555,8 +555,8 @@ private ScriptFile[] GetBuiltinCommandScriptFiles( foreach (PSModuleInfo nestedInfo in moduleInfo.NestedModules) { string nestedModPath = nestedInfo.Path; - if (nestedModPath.EndsWith(@".ps1", StringComparison.OrdinalIgnoreCase) || - nestedModPath.EndsWith(@".psm1", StringComparison.OrdinalIgnoreCase)) + if (nestedModPath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase) || + nestedModPath.EndsWith(".psm1", StringComparison.OrdinalIgnoreCase)) { newFile = _workspaceService.GetFile(nestedModPath); newFile.IsAnalysisEnabled = false; diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs index 13e5aee97..1bdcb0ec0 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs @@ -89,7 +89,7 @@ public static async Task GetCompletionsAsync( await executionService.ExecuteDelegateAsync( representation: "CompleteInput", new ExecutionOptions { Priority = ExecutionPriority.Next }, - (pwsh, cancellationToken) => + (pwsh, _) => { stopwatch.Start(); commandCompletion = CommandCompletion.CompleteInput( @@ -113,7 +113,7 @@ await executionService.ExecuteDelegateAsync( /// /// The abstract syntax tree of the given script /// The line number of the cursor for the given script - /// The coulumn number of the cursor for the given script + /// The column number of the cursor for the given script /// Includes full function definition ranges in the search. /// SymbolReference of found symbol public static SymbolReference FindSymbolAtPosition( @@ -152,7 +152,7 @@ public static SymbolReference FindCommandAtPosition(Ast scriptAst, int lineNumbe /// Finds all references (including aliases) in a script for the given symbol /// /// The abstract syntax tree of the given script - /// The symbol that we are looking for referneces of + /// The symbol that we are looking for references of /// Dictionary maping cmdlets to aliases for finding alias references /// Dictionary maping aliases to cmdlets for finding alias references /// @@ -197,15 +197,13 @@ public static SymbolReference FindDefinitionOfSymbol( /// The abstract syntax tree of the given script /// The PowerShell version the Ast was generated from /// A collection of SymbolReference objects - public static IEnumerable FindSymbolsInDocument(Ast scriptAst, Version powerShellVersion) + public static IEnumerable FindSymbolsInDocument(Ast scriptAst) { - IEnumerable symbolReferences = null; - // TODO: Restore this when we figure out how to support multiple // PS versions in the new PSES-as-a-module world (issue #276) // if (powerShellVersion >= new Version(5,0)) // { - //#if PowerShellv5 + //#if PowerShell v5 // FindSymbolsVisitor2 findSymbolsVisitor = new FindSymbolsVisitor2(); // scriptAst.Visit(findSymbolsVisitor); // symbolReferences = findSymbolsVisitor.SymbolReferences; @@ -215,8 +213,7 @@ public static IEnumerable FindSymbolsInDocument(Ast scriptAst, FindSymbolsVisitor findSymbolsVisitor = new(); scriptAst.Visit(findSymbolsVisitor); - symbolReferences = findSymbolsVisitor.SymbolReferences; - return symbolReferences; + return findSymbolsVisitor.SymbolReferences; } /// @@ -253,7 +250,7 @@ private static bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap return levelAstTypeMatch; } - IEnumerable astsFound = (node.Item as Ast).FindAll(a => a is Ast, false); + IEnumerable astsFound = (node.Item as Ast)?.FindAll(a => a is not null, false); if (astsFound != null) { foreach (Ast astFound in astsFound) diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDotSourcedVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDotSourcedVisitor.cs index 1dff46772..416a5d611 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDotSourcedVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDotSourcedVisitor.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.EditorServices.Services.Symbols { /// - /// The vistor used to find the dot-sourced files in an AST + /// The visitor used to find the dot-sourced files in an AST /// internal class FindDotSourcedVisitor : AstVisitor { @@ -18,7 +18,7 @@ internal class FindDotSourcedVisitor : AstVisitor /// /// A hash set of the dot sourced files (because we don't want duplicates) /// - public HashSet DotSourcedFiles { get; private set; } + public HashSet DotSourcedFiles { get; } /// /// Creates a new instance of the FindDotSourcedVisitor class. diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolVisitor.cs index 4ded34190..0a1e1ec2a 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolVisitor.cs @@ -6,7 +6,7 @@ namespace Microsoft.PowerShell.EditorServices.Services.Symbols { /// - /// The visitor used to find the the symbol at a specfic location in the AST + /// The visitor used to find the symbol at a specific location in the AST /// internal class FindSymbolVisitor : AstVisitor { diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor.cs index d37299aab..970acb4e7 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.EditorServices.Services.Symbols /// internal class FindSymbolsVisitor : AstVisitor { - public List SymbolReferences { get; private set; } + public List SymbolReferences { get; } public FindSymbolsVisitor() => SymbolReferences = new List(); @@ -78,12 +78,7 @@ private static bool IsAssignedAtScriptScope(VariableExpressionAst variableExpres } parent = parent.Parent; - if (parent == null || parent.Parent == null || parent.Parent.Parent == null) - { - return true; - } - - return false; + return parent is null || parent.Parent is null || parent.Parent.Parent is null; } } @@ -95,7 +90,7 @@ internal class FindHashtableSymbolsVisitor : AstVisitor /// /// List of symbols (keys) found in the hashtable /// - public List SymbolReferences { get; private set; } + public List SymbolReferences { get; } /// /// Initializes a new instance of FindHashtableSymbolsVisitor class @@ -126,13 +121,12 @@ public override AstVisitAction VisitHashtable(HashtableAst hashtableAst) File = hashtableAst.Extent.File }; - SymbolType symbolType = SymbolType.HashtableKey; + const SymbolType symbolType = SymbolType.HashtableKey; SymbolReferences.Add( new SymbolReference( symbolType, nameExtent)); - } } diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor2.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor2.cs index b7949b096..15f5e49db 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor2.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor2.cs @@ -72,4 +72,3 @@ namespace Microsoft.PowerShell.EditorServices.Services.Symbols // } //} } - diff --git a/src/PowerShellEditorServices/Services/Template/Handlers/TemplateHandlers.cs b/src/PowerShellEditorServices/Services/Template/Handlers/TemplateHandlers.cs index 96ce93b12..685fda762 100644 --- a/src/PowerShellEditorServices/Services/Template/Handlers/TemplateHandlers.cs +++ b/src/PowerShellEditorServices/Services/Template/Handlers/TemplateHandlers.cs @@ -32,7 +32,6 @@ public async Task Handle(GetProjectTemplatesRequest await _templateService.GetAvailableTemplatesAsync( request.IncludeInstalledModules).ConfigureAwait(false); - return new GetProjectTemplatesResponse { Templates = availableTemplates diff --git a/src/PowerShellEditorServices/Services/Template/TemplateService.cs b/src/PowerShellEditorServices/Services/Template/TemplateService.cs index c046ab51c..ae9cc3c9b 100644 --- a/src/PowerShellEditorServices/Services/Template/TemplateService.cs +++ b/src/PowerShellEditorServices/Services/Template/TemplateService.cs @@ -82,7 +82,7 @@ public async Task ImportPlasterIfInstalledAsync() _logger.LogTrace($"Plaster is {installedQualifier}installed!"); // Attempt to load plaster - if (isPlasterInstalled.Value && isPlasterLoaded == false) + if (isPlasterInstalled.Value && !isPlasterLoaded) { _logger.LogTrace("Loading Plaster..."); @@ -94,7 +94,7 @@ public async Task ImportPlasterIfInstalledAsync() IReadOnlyList importResult = await _executionService.ExecutePSCommandAsync(psCommand, CancellationToken.None).ConfigureAwait(false); - isPlasterLoaded = importResult.Any(); + isPlasterLoaded = importResult.Count > 0; string loadedQualifier = isPlasterInstalled.Value ? "was" : "could not be"; diff --git a/src/PowerShellEditorServices/Services/TextDocument/BufferPosition.cs b/src/PowerShellEditorServices/Services/TextDocument/BufferPosition.cs index 1a581db98..c5c7efc35 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/BufferPosition.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/BufferPosition.cs @@ -23,12 +23,12 @@ internal class BufferPosition /// /// Gets the line number of the position in the buffer. /// - public int Line { get; private set; } + public int Line { get; } /// /// Gets the column number of the position in the buffer. /// - public int Column { get; private set; } + public int Column { get; } #endregion @@ -100,4 +100,3 @@ public override bool Equals(object obj) #endregion } } - diff --git a/src/PowerShellEditorServices/Services/TextDocument/BufferRange.cs b/src/PowerShellEditorServices/Services/TextDocument/BufferRange.cs index 8bbdaabd1..25eb7c144 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/BufferRange.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/BufferRange.cs @@ -23,12 +23,12 @@ internal sealed class BufferRange /// /// Gets the start position of the range in the buffer. /// - public BufferPosition Start { get; private set; } + public BufferPosition Start { get; } /// /// Gets the end position of the range in the buffer. /// - public BufferPosition End { get; private set; } + public BufferPosition End { get; } /// /// Returns true if the current range is non-zero, i.e. @@ -109,4 +109,3 @@ public override bool Equals(object obj) #endregion } } - diff --git a/src/PowerShellEditorServices/Services/TextDocument/FilePosition.cs b/src/PowerShellEditorServices/Services/TextDocument/FilePosition.cs index b9cb3594e..08b809e4e 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/FilePosition.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/FilePosition.cs @@ -98,4 +98,3 @@ public FilePosition GetLineEnd() #endregion } } - diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/CodeActionHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/CodeActionHandler.cs index 2fe88da96..8ea7eca70 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/CodeActionHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/CodeActionHandler.cs @@ -39,7 +39,7 @@ public override async Task Handle(CodeAction request, CancellationTo // TODO: How on earth do we handle a CodeAction? This is new... if (cancellationToken.IsCancellationRequested) { - _logger.LogDebug("CodeAction request canceled for: {0}", request.Title); + _logger.LogDebug("CodeAction request canceled for: {Title}", request.Title); } return request; } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DefinitionHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DefinitionHandler.cs index decc1ea4a..8b9c2fc60 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DefinitionHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DefinitionHandler.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.Symbols; using Microsoft.PowerShell.EditorServices.Services.TextDocument; @@ -18,16 +17,13 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class PsesDefinitionHandler : DefinitionHandlerBase { - private readonly ILogger _logger; private readonly SymbolsService _symbolsService; private readonly WorkspaceService _workspaceService; public PsesDefinitionHandler( - ILoggerFactory factory, SymbolsService symbolsService, WorkspaceService workspaceService) { - _logger = factory.CreateLogger(); _symbolsService = symbolsService; _workspaceService = workspaceService; } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs index 9a513f942..99fe542e4 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs @@ -20,16 +20,13 @@ internal class PsesDocumentHighlightHandler : DocumentHighlightHandlerBase private static readonly DocumentHighlightContainer s_emptyHighlightContainer = new(); private readonly ILogger _logger; private readonly WorkspaceService _workspaceService; - private readonly SymbolsService _symbolsService; public PsesDocumentHighlightHandler( ILoggerFactory loggerFactory, - WorkspaceService workspaceService, - SymbolsService symbolService) + WorkspaceService workspaceService) { _logger = loggerFactory.CreateLogger(); _workspaceService = workspaceService; - _symbolsService = symbolService; _logger.LogInformation("highlight handler loaded"); } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentSymbolHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentSymbolHandler.cs index d3c157497..f0973a7f0 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentSymbolHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentSymbolHandler.cs @@ -27,7 +27,7 @@ internal class PsesDocumentSymbolHandler : DocumentSymbolHandlerBase private readonly WorkspaceService _workspaceService; private readonly IDocumentSymbolProvider[] _providers; - public PsesDocumentSymbolHandler(ILoggerFactory factory, ConfigurationService configurationService, WorkspaceService workspaceService) + public PsesDocumentSymbolHandler(ILoggerFactory factory, WorkspaceService workspaceService) { _logger = factory.CreateLogger(); _workspaceService = workspaceService; @@ -74,7 +74,6 @@ public override Task Handle(Document .ToArray() : Array.Empty(); - return Task.FromResult(new SymbolInformationOrDocumentSymbolContainer(symbols)); } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/FoldingRangeHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/FoldingRangeHandler.cs index a6eaec1ff..fbf5ad9a5 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/FoldingRangeHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/FoldingRangeHandler.cs @@ -36,19 +36,19 @@ public override Task> Handle(FoldingRangeRequestParam re { if (cancellationToken.IsCancellationRequested) { - _logger.LogDebug("FoldingRange request canceled for file: {0}", request.TextDocument.Uri); + _logger.LogDebug("FoldingRange request canceled for file: {Uri}", request.TextDocument.Uri); return Task.FromResult(new Container()); } // TODO Should be using dynamic registrations - if (!_configurationService.CurrentSettings.CodeFolding.Enable) { return null; } + if (!_configurationService.CurrentSettings.CodeFolding.Enable) { return Task.FromResult(new Container()); } // Avoid crash when using untitled: scheme or any other scheme where the document doesn't // have a backing file. https://github.com/PowerShell/vscode-powershell/issues/1676 // Perhaps a better option would be to parse the contents of the document as a string // as opposed to reading a file but the scenario of "no backing file" probably doesn't // warrant the extra effort. - if (!_workspaceService.TryGetFile(request.TextDocument.Uri, out ScriptFile scriptFile)) { return null; } + if (!_workspaceService.TryGetFile(request.TextDocument.Uri, out ScriptFile scriptFile)) { return Task.FromResult(new Container()); } List result = new(); diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/HoverHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/HoverHandler.cs index 33db7975b..cf90c6565 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/HoverHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/HoverHandler.cs @@ -40,7 +40,7 @@ public override async Task Handle(HoverParams request, CancellationToken { if (cancellationToken.IsCancellationRequested) { - _logger.LogDebug("Hover request canceled for file: {0}", request.TextDocument.Uri); + _logger.LogDebug("Hover request canceled for file: {Uri}", request.TextDocument.Uri); return null; } @@ -57,8 +57,10 @@ await _symbolsService.FindSymbolDetailsAtLocationAsync( return null; } - List symbolInfo = new(); - symbolInfo.Add(new MarkedString("PowerShell", symbolDetails.DisplayString)); + List symbolInfo = new() + { + new MarkedString("PowerShell", symbolDetails.DisplayString) + }; if (!string.IsNullOrEmpty(symbolDetails.Documentation)) { diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/PsesSemanticTokensHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/PsesSemanticTokensHandler.cs index 4cb872a38..e5e69e60f 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/PsesSemanticTokensHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/PsesSemanticTokensHandler.cs @@ -6,7 +6,6 @@ using System.Management.Automation.Language; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.TextDocument; using Microsoft.PowerShell.EditorServices.Utility; @@ -29,14 +28,9 @@ internal class PsesSemanticTokensHandler : SemanticTokensHandlerBase Range = true }; - private readonly ILogger _logger; private readonly WorkspaceService _workspaceService; - public PsesSemanticTokensHandler(ILogger logger, WorkspaceService workspaceService) - { - _logger = logger; - _workspaceService = workspaceService; - } + public PsesSemanticTokensHandler(WorkspaceService workspaceService) => _workspaceService = workspaceService; protected override Task Tokenize(SemanticTokensBuilder builder, ITextDocumentIdentifierParams identifier, CancellationToken cancellationToken) @@ -81,7 +75,7 @@ internal static IEnumerable ConvertToSemanticTokens(Token token) } SemanticTokenType mappedType = MapSemanticTokenType(token); - if (mappedType == null) + if (mappedType == default) { yield break; } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/ReferencesHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/ReferencesHandler.cs index 12c505a01..7600341b9 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/ReferencesHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/ReferencesHandler.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.Symbols; using Microsoft.PowerShell.EditorServices.Services.TextDocument; @@ -18,13 +17,11 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class PsesReferencesHandler : ReferencesHandlerBase { - private readonly ILogger _logger; private readonly SymbolsService _symbolsService; private readonly WorkspaceService _workspaceService; - public PsesReferencesHandler(ILoggerFactory factory, SymbolsService symbolsService, WorkspaceService workspaceService) + public PsesReferencesHandler(SymbolsService symbolsService, WorkspaceService workspaceService) { - _logger = factory.CreateLogger(); _symbolsService = symbolsService; _workspaceService = workspaceService; } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/SignatureHelpHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/SignatureHelpHandler.cs index 2630cddc3..3e294a1e2 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/SignatureHelpHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/SignatureHelpHandler.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; -using Microsoft.PowerShell.EditorServices.Services.PowerShell; using Microsoft.PowerShell.EditorServices.Services.Symbols; using Microsoft.PowerShell.EditorServices.Services.TextDocument; using Microsoft.PowerShell.EditorServices.Utility; @@ -21,18 +20,15 @@ internal class PsesSignatureHelpHandler : SignatureHelpHandlerBase private readonly ILogger _logger; private readonly SymbolsService _symbolsService; private readonly WorkspaceService _workspaceService; - private readonly IInternalPowerShellExecutionService _executionService; public PsesSignatureHelpHandler( ILoggerFactory factory, SymbolsService symbolsService, - WorkspaceService workspaceService, - IInternalPowerShellExecutionService executionService) + WorkspaceService workspaceService) { _logger = factory.CreateLogger(); _symbolsService = symbolsService; _workspaceService = workspaceService; - _executionService = executionService; } protected override SignatureHelpRegistrationOptions CreateRegistrationOptions(SignatureHelpCapability capability, ClientCapabilities clientCapabilities) => new() @@ -46,7 +42,7 @@ public override async Task Handle(SignatureHelpParams request, Ca { if (cancellationToken.IsCancellationRequested) { - _logger.LogDebug("SignatureHelp request canceled for file: {0}", request.TextDocument.Uri); + _logger.LogDebug("SignatureHelp request canceled for file: {Uri}", request.TextDocument.Uri); return new SignatureHelp(); } diff --git a/src/PowerShellEditorServices/Services/TextDocument/ScriptFile.cs b/src/PowerShellEditorServices/Services/TextDocument/ScriptFile.cs index 3c543d1b9..ebc22717b 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/ScriptFile.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/ScriptFile.cs @@ -42,7 +42,7 @@ internal sealed class ScriptFile /// /// Gets the path at which this file resides. /// - public string FilePath { get; private set; } + public string FilePath { get; } /// /// Gets the file path in LSP DocumentUri form. The ClientPath property must not be null. @@ -60,7 +60,7 @@ internal sealed class ScriptFile /// Gets a boolean that determines whether this file is /// in-memory or not (either unsaved or non-file content). /// - public bool IsInMemory { get; private set; } + public bool IsInMemory { get; } /// /// Gets a string containing the full contents of the file. @@ -217,7 +217,7 @@ internal static bool IsUntitledPath(string path) public string GetLine(int lineNumber) { Validate.IsWithinRange( - "lineNumber", lineNumber, + nameof(lineNumber), lineNumber, 1, FileLines.Count + 1); return FileLines[lineNumber - 1]; @@ -310,10 +310,7 @@ public void ApplyChange(FileChange fileChange) if (fileChange.IsReload) { FileLines.Clear(); - foreach (string changeLine in changeLines) - { - FileLines.Add(changeLine); - } + FileLines.AddRange(changeLines); } else { @@ -398,8 +395,8 @@ public void ApplyChange(FileChange fileChange) /// The zero-based offset for the given file position. public int GetOffsetAtPosition(int lineNumber, int columnNumber) { - Validate.IsWithinRange("lineNumber", lineNumber, 1, FileLines.Count + 1); - Validate.IsGreaterThan("columnNumber", columnNumber, 0); + Validate.IsWithinRange(nameof(lineNumber), lineNumber, 1, FileLines.Count + 1); + Validate.IsGreaterThan(nameof(columnNumber), columnNumber, 0); int offset = 0; diff --git a/src/PowerShellEditorServices/Services/TextDocument/ScriptFileMarker.cs b/src/PowerShellEditorServices/Services/TextDocument/ScriptFileMarker.cs index 6dccca37a..43c465701 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/ScriptFileMarker.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/ScriptFileMarker.cs @@ -96,7 +96,7 @@ public class ScriptFileMarker internal static ScriptFileMarker FromParseError( ParseError parseError) { - Validate.IsNotNull("parseError", parseError); + Validate.IsNotNull(nameof(parseError), parseError); return new ScriptFileMarker { @@ -166,4 +166,3 @@ internal static ScriptFileMarker FromDiagnosticRecord(PSObject psObject) #endregion } } - diff --git a/src/PowerShellEditorServices/Services/TextDocument/TokenOperations.cs b/src/PowerShellEditorServices/Services/TextDocument/TokenOperations.cs index 4d91038bf..112cac163 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/TokenOperations.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/TokenOperations.cs @@ -8,7 +8,6 @@ namespace Microsoft.PowerShell.EditorServices.Services.TextDocument { - /// /// Provides common operations for the tokens of a parsed script. /// @@ -90,7 +89,7 @@ internal static FoldingReferenceList FoldableReferences( // // Find blocks of line comments # comment1\n# comment2\n... // Finding blocks of comment tokens is more complicated as the newline characters are not - // classed as comments. To workaround this we search for valid block comments (See IsBlockCmment) + // classed as comments. To workaround this we search for valid block comments (See IsBlockComment) // and then determine contiguous line numbers from there // // Find comments regions <# -> #> @@ -197,7 +196,7 @@ private static FoldingReference CreateFoldingReference( /// /// Returns true if a Token is a block comment; /// - Must be a TokenKind.comment - /// - Must be preceeded by TokenKind.NewLine + /// - Must be preceded by TokenKind.NewLine /// - Token text must start with a '#'.false This is because comment regions /// start with '<#' but have the same TokenKind /// diff --git a/src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs b/src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs index 0e82efea5..9b30391fa 100644 --- a/src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs +++ b/src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs @@ -238,13 +238,9 @@ public Hashtable GetPSSASettingsHashtable( openBraceSettings["NewLineAfter"] = true; closeBraceSettings["NewLineAfter"] = true; break; - - case CodeFormattingPreset.Custom: - default: - break; } - logger.LogDebug("Created formatting hashtable: {0}", JsonConvert.SerializeObject(settings)); + logger.LogDebug("Created formatting hashtable: {Settings}", JsonConvert.SerializeObject(settings)); return settings; } diff --git a/src/PowerShellEditorServices/Services/Workspace/RemoteFileManagerService.cs b/src/PowerShellEditorServices/Services/Workspace/RemoteFileManagerService.cs index 4171d33e6..f986c8eba 100644 --- a/src/PowerShellEditorServices/Services/Workspace/RemoteFileManagerService.cs +++ b/src/PowerShellEditorServices/Services/Workspace/RemoteFileManagerService.cs @@ -6,7 +6,6 @@ using Microsoft.PowerShell.EditorServices.Logging; using Microsoft.PowerShell.EditorServices.Services.Extension; using Microsoft.PowerShell.EditorServices.Services.PowerShell; -using Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Runspace; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility; using Microsoft.PowerShell.EditorServices.Utility; @@ -335,7 +334,7 @@ public async Task FetchRemoteFileAsync( if (fileContent != null) { - RemoteFileManagerService.StoreRemoteFile(localFilePath, fileContent, pathMappings); + StoreRemoteFile(localFilePath, fileContent, pathMappings); } else { @@ -375,7 +374,7 @@ public async Task SaveRemoteFileAsync(string localFilePath) logger.LogTrace( $"Saving remote file {remoteFilePath} (local path: {localFilePath})"); - byte[] localFileContents = null; + byte[] localFileContents; try { localFileContents = File.ReadAllBytes(localFilePath); @@ -760,9 +759,7 @@ public void AddPathMapping(string remotePath, string localPath) public string GetMappedPath(string filePath) { - string mappedPath = filePath; - - if (!pathMappings.TryGetValue(filePath.ToLower(), out mappedPath)) + if (!pathMappings.TryGetValue(filePath.ToLower(), out string mappedPath)) { // If the path isn't mapped yet, generate it if (!filePath.StartsWith(remoteFileManager.remoteFilesPath)) diff --git a/src/PowerShellEditorServices/Services/Workspace/WorkspaceFileSystemWrapper.cs b/src/PowerShellEditorServices/Services/Workspace/WorkspaceFileSystemWrapper.cs index 4ffe8021b..a8861cee2 100644 --- a/src/PowerShellEditorServices/Services/Workspace/WorkspaceFileSystemWrapper.cs +++ b/src/PowerShellEditorServices/Services/Workspace/WorkspaceFileSystemWrapper.cs @@ -11,7 +11,6 @@ namespace Microsoft.PowerShell.EditorServices.Services.Workspace { - /// /// A FileSystem wrapper class which only returns files and directories that the consumer is interested in, /// with a maximum recursion depth and silently ignores most file system errors. Typically this is used by the diff --git a/src/PowerShellEditorServices/Services/Workspace/WorkspaceService.cs b/src/PowerShellEditorServices/Services/Workspace/WorkspaceService.cs index 9ecbb1137..6f8e43e49 100644 --- a/src/PowerShellEditorServices/Services/Workspace/WorkspaceService.cs +++ b/src/PowerShellEditorServices/Services/Workspace/WorkspaceService.cs @@ -298,7 +298,7 @@ public ScriptFile GetFileBuffer(DocumentUri documentUri, string initialBuffer) /// The file path at which the script resides. public void CloseFile(ScriptFile scriptFile) { - Validate.IsNotNull("scriptFile", scriptFile); + Validate.IsNotNull(nameof(scriptFile), scriptFile); workspaceFiles.TryRemove(scriptFile.Id, out ScriptFile _); } @@ -538,7 +538,7 @@ internal string ResolveRelativeScriptPath(string baseFilePath, string relativePa if (resolveException != null) { logger.LogError( - $"Could not resolve relative script path\r\n" + + "Could not resolve relative script path\r\n" + $" baseFilePath = {baseFilePath}\r\n " + $" relativePath = {relativePath}\r\n\r\n" + $"{resolveException}"); diff --git a/src/PowerShellEditorServices/Utility/Extensions.cs b/src/PowerShellEditorServices/Utility/Extensions.cs index 9c6c6b2cf..f2e248514 100644 --- a/src/PowerShellEditorServices/Utility/Extensions.cs +++ b/src/PowerShellEditorServices/Utility/Extensions.cs @@ -87,7 +87,6 @@ public static T MaxElement(this IEnumerable elements, Func comp /// 0 if extentX and extentY are equal in width. 1 if width of extent X is greater than that of extent Y. Otherwise, -1. public static int ExtentWidthComparer(this IScriptExtent extentX, IScriptExtent extentY) { - if (extentX == null && extentY == null) { return 0; diff --git a/src/PowerShellEditorServices/Utility/PathUtils.cs b/src/PowerShellEditorServices/Utility/PathUtils.cs index b97cc6cde..568a92156 100644 --- a/src/PowerShellEditorServices/Utility/PathUtils.cs +++ b/src/PowerShellEditorServices/Utility/PathUtils.cs @@ -4,27 +4,28 @@ using System.IO; using System.Management.Automation; using System.Runtime.InteropServices; -using System.Text; namespace Microsoft.PowerShell.EditorServices.Utility { - internal class PathUtils + internal static class PathUtils { /// - /// The default path separator used by the base implementation of the providers. - /// + /// The default path separator used by the base implementation of the providers. + /// /// Porting note: IO.Path.DirectorySeparatorChar is correct for all platforms. On Windows, /// it is '\', and on Linux, it is '/', as expected. + /// /// internal static readonly char DefaultPathSeparator = Path.DirectorySeparatorChar; /// - /// The alternate path separator used by the base implementation of the providers. - /// + /// The alternate path separator used by the base implementation of the providers. + /// /// Porting note: we do not use .NET's AlternatePathSeparatorChar here because it correctly /// states that both the default and alternate are '/' on Linux. However, for PowerShell to /// be "slash agnostic", we need to use the assumption that a '\' is the alternate path /// separator on Linux. + /// /// internal static readonly char AlternatePathSeparator = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? '/' : '\\'; diff --git a/src/PowerShellEditorServices/Utility/Validate.cs b/src/PowerShellEditorServices/Utility/Validate.cs index 7cc8f141f..f67ffe10a 100644 --- a/src/PowerShellEditorServices/Utility/Validate.cs +++ b/src/PowerShellEditorServices/Utility/Validate.cs @@ -104,8 +104,8 @@ public static void IsGreaterThan( /// /// The type of value to be validated. /// The name of the parameter being validated. - /// The value that valueToCheck should not equal. /// The value of the parameter being validated. + /// The value that valueToCheck should not equal. public static void IsNotEqual( string parameterName, TValue valueToCheck, diff --git a/src/PowerShellEditorServices/Utility/VersionUtils.cs b/src/PowerShellEditorServices/Utility/VersionUtils.cs index 0cdb3a423..a814b73a6 100644 --- a/src/PowerShellEditorServices/Utility/VersionUtils.cs +++ b/src/PowerShellEditorServices/Utility/VersionUtils.cs @@ -65,7 +65,6 @@ internal static class VersionUtils internal static class PowerShellReflectionUtils { - private static readonly Type s_psVersionInfoType = typeof(System.Management.Automation.Runspaces.Runspace).Assembly.GetType("System.Management.Automation.PSVersionInfo"); // This property is a Version type in PowerShell. It's existed since 5.1, but it was only made public in 6.2. diff --git a/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs b/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs index ca6825928..c48954de2 100644 --- a/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs +++ b/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using System; -using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; @@ -56,14 +55,14 @@ public async Task InitializeAsync() .WithOutput(_psesProcess.InputStream) // The OnStarted delegate gets run when we receive the _Initialized_ event from the server: // https://microsoft.github.io/debug-adapter-protocol/specification#Events_Initialized - .OnStarted((client, token) => + .OnStarted((_, _) => { Started.SetResult(true); return Task.CompletedTask; }) // The OnInitialized delegate gets run when we first receive the _Initialize_ response: // https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Initialize - .OnInitialized((client, request, response, token) => + .OnInitialized((_, _, _, _) => { initialized.SetResult(true); return Task.CompletedTask; @@ -125,7 +124,7 @@ private string GenerateScriptFromLoggingStatements(params string[] logStatements { if (logStatements.Length == 0) { - throw new ArgumentNullException("Expected at least one argument."); + throw new ArgumentNullException(nameof(logStatements), "Expected at least one argument."); } // Have script create/overwrite file first with `>`. diff --git a/test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs b/test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs index f386fd983..4d9db8c82 100644 --- a/test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs +++ b/test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; diff --git a/test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs b/test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs index 5214d8cf5..562f3c764 100644 --- a/test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs +++ b/test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs @@ -12,7 +12,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.PowerShell.EditorServices.Handlers; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client; diff --git a/test/PowerShellEditorServices.Test.E2E/Processes/StdioServerProcess.cs b/test/PowerShellEditorServices.Test.E2E/Processes/StdioServerProcess.cs index 736a1fccc..be13c3203 100644 --- a/test/PowerShellEditorServices.Test.E2E/Processes/StdioServerProcess.cs +++ b/test/PowerShellEditorServices.Test.E2E/Processes/StdioServerProcess.cs @@ -119,7 +119,7 @@ public override Task Stop() { Process serverProcess = Interlocked.Exchange(ref _serverProcess, null); ServerExitCompletion.TrySetResult(null); - if (serverProcess != null && !serverProcess.HasExited) + if (serverProcess?.HasExited == false) { serverProcess.Kill(); } diff --git a/test/PowerShellEditorServices.Test.Shared/Completion/CompleteCommandFromModule.cs b/test/PowerShellEditorServices.Test.Shared/Completion/CompleteCommandFromModule.cs index 184e1699a..7b4249228 100644 --- a/test/PowerShellEditorServices.Test.Shared/Completion/CompleteCommandFromModule.cs +++ b/test/PowerShellEditorServices.Test.Shared/Completion/CompleteCommandFromModule.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using Microsoft.PowerShell.EditorServices.Services.TextDocument; using OmniSharp.Extensions.LanguageServer.Protocol.Models; diff --git a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInMultiSymbolFile.cs b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInMultiSymbolFile.cs index 95efed4a9..774376040 100644 --- a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInMultiSymbolFile.cs +++ b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInMultiSymbolFile.cs @@ -5,7 +5,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared.Symbols { - public class FindSymbolsInMultiSymbolFile + public static class FindSymbolsInMultiSymbolFile { public static readonly ScriptRegion SourceDetails = new( diff --git a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInNoSymbolsFile.cs b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInNoSymbolsFile.cs index 7847cfbfe..33fe95888 100644 --- a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInNoSymbolsFile.cs +++ b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInNoSymbolsFile.cs @@ -5,7 +5,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared.Symbols { - public class FindSymbolsInNoSymbolsFile + public static class FindSymbolsInNoSymbolsFile { public static readonly ScriptRegion SourceDetails = new( diff --git a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPSDFile.cs b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPSDFile.cs index 40aa0878b..337098076 100644 --- a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPSDFile.cs +++ b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPSDFile.cs @@ -5,7 +5,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared.Symbols { - public class FindSymbolsInPSDFile + public static class FindSymbolsInPSDFile { public static readonly ScriptRegion SourceDetails = new( diff --git a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPesterFile.cs b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPesterFile.cs index c69825afd..844e047a9 100644 --- a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPesterFile.cs +++ b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPesterFile.cs @@ -5,7 +5,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared.Symbols { - public class FindSymbolsInPesterFile + public static class FindSymbolsInPesterFile { public static readonly ScriptRegion SourceDetails = new( diff --git a/test/PowerShellEditorServices.Test/Language/SemanticTokenTest.cs b/test/PowerShellEditorServices.Test/Language/SemanticTokenTest.cs index d41c7fc0d..172aa27a6 100644 --- a/test/PowerShellEditorServices.Test/Language/SemanticTokenTest.cs +++ b/test/PowerShellEditorServices.Test/Language/SemanticTokenTest.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.IO; using System.Management.Automation.Language; -using System.Threading.Tasks; using Microsoft.PowerShell.EditorServices.Services.TextDocument; using Microsoft.PowerShell.EditorServices.Handlers; using OmniSharp.Extensions.LanguageServer.Protocol; @@ -19,7 +18,7 @@ public class SemanticTokenTest [Fact] public void TokenizesFunctionElements() { - string text = @" + const string text = @" function Get-Sum { param( [int]$a, [int]$b ) return $a + $b @@ -61,7 +60,7 @@ function Get-Sum { [Fact] public void TokenizesStringExpansion() { - string text = "Write-Host \"$(Test-Property Get-Whatever) $(Get-Whatever)\""; + const string text = "Write-Host \"$(Test-Property Get-Whatever) $(Get-Whatever)\""; ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), @@ -84,7 +83,7 @@ public void TokenizesStringExpansion() [Fact] public void RecognizesTokensWithAsterisk() { - string text = @" + const string text = @" function Get-A*A { } Get-A*A @@ -113,7 +112,7 @@ function Get-A*A { [Fact] public void RecognizesArrayPropertyInExpandableString() { - string text = "\"$(@($Array).Count) OtherText\""; + const string text = "\"$(@($Array).Count) OtherText\""; ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), @@ -138,7 +137,7 @@ public void RecognizesArrayPropertyInExpandableString() [Fact] public void RecognizesCurlyQuotedString() { - string text = "“^[-'a-z]*”"; + const string text = "“^[-'a-z]*”"; ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), @@ -152,7 +151,7 @@ public void RecognizesCurlyQuotedString() [Fact] public void RecognizeEnum() { - string text = @" + const string text = @" enum MyEnum{ one two diff --git a/test/PowerShellEditorServices.Test/Language/TokenOperationsTests.cs b/test/PowerShellEditorServices.Test/Language/TokenOperationsTests.cs index f92b8d93e..d8dc653c2 100644 --- a/test/PowerShellEditorServices.Test/Language/TokenOperationsTests.cs +++ b/test/PowerShellEditorServices.Test/Language/TokenOperationsTests.cs @@ -169,7 +169,7 @@ private static void AssertFoldingReferenceArrays( [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithLF() + public void LanguageServiceFindsFoldablRegionsWithLF() { // Remove and CR characters string testString = allInOneScript.Replace("\r", ""); @@ -181,7 +181,7 @@ public void LaguageServiceFindsFoldablRegionsWithLF() [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithCRLF() + public void LanguageServiceFindsFoldablRegionsWithCRLF() { // The Foldable regions should be the same regardless of line ending type // Enforce CRLF line endings, if none exist @@ -198,9 +198,9 @@ public void LaguageServiceFindsFoldablRegionsWithCRLF() [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithMismatchedRegions() + public void LanguageServiceFindsFoldablRegionsWithMismatchedRegions() { - string testString = + const string testString = @"#endregion should not fold - mismatched #region This should fold @@ -219,9 +219,9 @@ public void LaguageServiceFindsFoldablRegionsWithMismatchedRegions() [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithDuplicateRegions() + public void LanguageServiceFindsFoldablRegionsWithDuplicateRegions() { - string testString = + const string testString = @"# This script causes duplicate/overlapping ranges due to the `(` and `{` characters $AnArray = @(Get-ChildItem -Path C:\ -Include *.ps1 -File).Where({ $_.FullName -ne 'foo'}).ForEach({ @@ -241,9 +241,9 @@ public void LaguageServiceFindsFoldablRegionsWithDuplicateRegions() // ( -> ), @( -> ) and $( -> ) does not confuse the folder [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithSameEndToken() + public void LanguageServiceFindsFoldablRegionsWithSameEndToken() { - string testString = + const string testString = @"foreach ($1 in $2) { $x = @{ @@ -269,9 +269,9 @@ public void LaguageServiceFindsFoldablRegionsWithSameEndToken() // A simple PowerShell Classes test [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithClasses() + public void LanguageServiceFindsFoldablRegionsWithClasses() { - string testString = + const string testString = @"class TestClass { [string[]] $TestProperty = @( 'first', @@ -297,9 +297,9 @@ [string] TestMethod() { // This tests DSC style keywords and param blocks [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithDSC() + public void LanguageServiceFindsFoldablRegionsWithDSC() { - string testString = + const string testString = @"Configuration Example { param @@ -309,7 +309,7 @@ public void LaguageServiceFindsFoldablRegionsWithDSC() $NodeName = 'localhost', [Parameter(Mandatory = $true)] - [ValidateNotNullorEmpty()] + [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] $Credential ) diff --git a/test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs b/test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs index 32b6992a3..2543e69fc 100644 --- a/test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs +++ b/test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs @@ -14,7 +14,6 @@ namespace PSLanguageService.Test { public class ScriptFileChangeTests { - #if CoreCLR private static readonly Version PowerShellVersion = new(7, 2); #else @@ -579,10 +578,10 @@ public void PropertiesInitializedCorrectlyForFile() [Fact] public void PropertiesInitializedCorrectlyForUntitled() { - string path = "untitled:untitled-1"; + const string path = "untitled:untitled-1"; // 3 lines and 10 tokens in this script. - string script = @"function foo() { + const string script = @"function foo() { 'foo' }"; @@ -602,7 +601,7 @@ public void PropertiesInitializedCorrectlyForUntitled() [Trait("Category", "ScriptFile")] [Fact] - public void DocumentUriRetunsCorrectStringForAbsolutePath() + public void DocumentUriReturnsCorrectStringForAbsolutePath() { string path; ScriptFile scriptFile; diff --git a/test/PowerShellEditorServices.Test/Session/WorkspaceTests.cs b/test/PowerShellEditorServices.Test/Session/WorkspaceTests.cs index e617e53ab..6d07530ca 100644 --- a/test/PowerShellEditorServices.Test/Session/WorkspaceTests.cs +++ b/test/PowerShellEditorServices.Test/Session/WorkspaceTests.cs @@ -56,8 +56,8 @@ internal static WorkspaceService FixturesWorkspace() // in Microsoft.PowerShell.EditorServices.Workspace class private static readonly string[] s_defaultExcludeGlobs = Array.Empty(); private static readonly string[] s_defaultIncludeGlobs = new[] { "**/*" }; - private static readonly int s_defaultMaxDepth = 64; - private static readonly bool s_defaultIgnoreReparsePoints = false; + private const int s_defaultMaxDepth = 64; + private const bool s_defaultIgnoreReparsePoints = false; internal static List ExecuteEnumeratePSFiles( WorkspaceService workspace, @@ -74,7 +74,7 @@ bool ignoreReparsePoints ignoreReparsePoints: ignoreReparsePoints ); List fileList = new(); - foreach (string file in result) { fileList.Add(file); } + fileList.AddRange(result); // Assume order is not important from EnumeratePSFiles and sort the array so we can use deterministic asserts fileList.Sort(); @@ -158,8 +158,8 @@ public void CanDetermineIsPathInMemory() string tempDir = Path.GetTempPath(); string shortDirPath = Path.Combine(tempDir, "GitHub", "PowerShellEditorServices"); string shortFilePath = Path.Combine(shortDirPath, "foo.ps1"); - string shortUriForm = "git:/c%3A/Users/Keith/GitHub/dahlbyk/posh-git/src/PoshGitTypes.ps1?%7B%22path%22%3A%22c%3A%5C%5CUsers%5C%5CKeith%5C%5CGitHub%5C%5Cdahlbyk%5C%5Cposh-git%5C%5Csrc%5C%5CPoshGitTypes.ps1%22%2C%22ref%22%3A%22~%22%7D"; - string longUriForm = "gitlens-git:c%3A%5CUsers%5CKeith%5CGitHub%5Cdahlbyk%5Cposh-git%5Csrc%5CPoshGitTypes%3Ae0022701.ps1?%7B%22fileName%22%3A%22src%2FPoshGitTypes.ps1%22%2C%22repoPath%22%3A%22c%3A%2FUsers%2FKeith%2FGitHub%2Fdahlbyk%2Fposh-git%22%2C%22sha%22%3A%22e0022701fa12e0bc22d0458673d6443c942b974a%22%7D"; + const string shortUriForm = "git:/c%3A/Users/Keith/GitHub/dahlbyk/posh-git/src/PoshGitTypes.ps1?%7B%22path%22%3A%22c%3A%5C%5CUsers%5C%5CKeith%5C%5CGitHub%5C%5Cdahlbyk%5C%5Cposh-git%5C%5Csrc%5C%5CPoshGitTypes.ps1%22%2C%22ref%22%3A%22~%22%7D"; + const string longUriForm = "gitlens-git:c%3A%5CUsers%5CKeith%5CGitHub%5Cdahlbyk%5Cposh-git%5Csrc%5CPoshGitTypes%3Ae0022701.ps1?%7B%22fileName%22%3A%22src%2FPoshGitTypes.ps1%22%2C%22repoPath%22%3A%22c%3A%2FUsers%2FKeith%2FGitHub%2Fdahlbyk%2Fposh-git%22%2C%22sha%22%3A%22e0022701fa12e0bc22d0458673d6443c942b974a%22%7D"; var testCases = new[] { // Test short file absolute paths