diff --git a/.editorconfig b/.editorconfig index 51d876d19..7fd7d40b1 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,9 +10,17 @@ insert_final_newline = true [*.{cs}] indent_size = 4 trim_trailing_whitespace = true +file_header_template = Copyright (c) Microsoft Corporation.\nLicensed under the MIT License. csharp_space_before_open_square_brackets = true csharp_space_after_keywords_in_control_flow_statements = true csharp_space_before_open_square_brackets = false +csharp_style_expression_bodied_constructors = when_on_single_line +csharp_style_expression_bodied_methods = when_on_single_line +csharp_style_expression_bodied_operators = when_on_single_line +csharp_style_expression_bodied_properties = true +csharp_style_expression_bodied_indexers = true +csharp_style_expression_bodied_accessors = true +csharp_style_expression_bodied_lambdas = when_on_single_line # CS0168: The variable 'var' is declared but never used dotnet_diagnostic.CS0168.severity = error @@ -22,6 +30,8 @@ dotnet_diagnostic.CS0169.severity = error dotnet_diagnostic.CS0219.severity = error # CS0414: The private field 'field' is assigned but its value is never used dotnet_diagnostic.CS0414.severity = error +# CA1067: Should override Equals because it implements IEquatable +dotnet_diagnostic.CA1067.severity = silent # CA1068: CancellationToken parameters must come last dotnet_diagnostic.CA1068.severity = error # CA1822: Mark members as static @@ -32,6 +42,8 @@ dotnet_diagnostic.CA1823.severity = error dotnet_diagnostic.CA2007.severity = error # CA2016: Forward the CancellationToken parameter to methods that take one dotnet_diagnostic.CA2016.severity = error +# CA2254: The logging message template should not vary between calls to 'LoggerExtensions.*' +dotnet_diagnostic.CA2254.severity = silent # TODO: Enable all maintainability issues (dead code etc.) and enforce # See: https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/maintainability-warnings @@ -40,26 +52,30 @@ dotnet_analyzer_diagnostic.category-Maintainability.severity = error # TODO: Fix all of these issues and explicitly ignore the intentional ones! # CA2016: Forward the CancellationToken parameter to methods that take one -dotnet_diagnostic.CA2016.severity = suggestion +dotnet_diagnostic.CA2016.severity = error # CS0618: A class member was marked with the Obsolete attribute dotnet_diagnostic.CS0618.severity = suggestion # CS0649: Uninitialized private or internal field declaration that is never assigned a value -dotnet_diagnostic.CS0649.severity = suggestion +dotnet_diagnostic.CS0649.severity = warning # CS1998: This async method lacks 'await' operators and will run synchronously dotnet_diagnostic.CS1998.severity = suggestion # CS4014: Consider applying the await operator to the result of the call dotnet_diagnostic.CS4014.severity = suggestion # RCS1102: Make class static -dotnet_diagnostic.RCS1102.severity = suggestion +dotnet_diagnostic.RCS1102.severity = warning # RCS1139: Add summary element to documentation comment dotnet_diagnostic.RCS1139.severity = suggestion # RCS1194: Implement exception constructors dotnet_diagnostic.RCS1194.severity = suggestion # RCS1210: Return completed task instead of returning null dotnet_diagnostic.RCS1210.severity = suggestion +# RCS1036: Remove unnecessary blank line +dotnet_diagnostic.RCS1036.severity = warning # RCS1075: Avoid empty catch clause that catches System.Exception dotnet_diagnostic.RCS1075.severity = suggestion +# RCS1170: Use read-only auto-implemented property +dotnet_diagnostic.RCS1170.severity = warning # VSTHRD002: Avoid problematic synchronous waits dotnet_diagnostic.VSTHRD002.severity = suggestion @@ -79,9 +95,118 @@ dotnet_diagnostic.VSTHRD114.severity = suggestion dotnet_diagnostic.VSTHRD200.severity = suggestion # xUnit2013: Do not use equality check to check for collection size -dotnet_diagnostic.xUnit2013.severity = suggestion -# IDE0003: this and Me preferences -dotnet_diagnostic.IDE0003.severity = suggestion +dotnet_diagnostic.xUnit2013.severity = warning +# xUnit1004: Test methods should not be skipped +dotnet_diagnostic.xUnit1004.severity = suggestion + +# IDE0001: Simplify name +dotnet_diagnostic.IDE0001.severity = warning +# IDE0002: Simplify member access +dotnet_diagnostic.IDE0001.severity = warning +# IDE0003: Remove this or Me qualification +dotnet_diagnostic.IDE0003.severity = warning +# IDE0004: Remove unnecessary cast +dotnet_diagnostic.IDE0004.severity = warning +# IDE0005: Remove unnecessary import +dotnet_diagnostic.IDE0005.severity = suggestion +# IDE0008: Use explicit type instead of var +dotnet_diagnostic.IDE0008.severity = warning +# IDE0011: Add braces +dotnet_diagnostic.IDE0011.severity = warning +# IDE0016: Use throw expression +dotnet_diagnostic.IDE0016.severity = warning +# IDE0017: Use object initializers +dotnet_diagnostic.IDE0017.severity = warning +# IDE0018: Inline variable declaration +dotnet_diagnostic.IDE0018.severity = warning +# IDE0019: Use pattern matching to avoid 'as' followed by a 'null' check +dotnet_diagnostic.IDE0019.severity = warning +# IDE0020: Use pattern matching to avoid 'is' check followed by a cast (with variable) +dotnet_diagnostic.IDE0020.severity = warning +# IDE0021: Use expression body for constructors +dotnet_diagnostic.IDE0021.severity = warning +# IDE0022: Use expression body for methods +dotnet_diagnostic.IDE0022.severity = warning +# IDE0023: Use expression body for conversion operators +dotnet_diagnostic.IDE0023.severity = warning +# IDE0024: Use expression body for operators +dotnet_diagnostic.IDE0024.severity = warning +# IDE0025: Use expression body for properties +dotnet_diagnostic.IDE0025.severity = warning +# IDE0026: Use expression body for indexers +dotnet_diagnostic.IDE0026.severity = warning +# IDE0027: Use expression body for accessors +dotnet_diagnostic.IDE0027.severity = warning +# IDE0028: Use collection initializers +dotnet_diagnostic.IDE0028.severity = warning +# IDE0029: Use coalesce expression (non-nullable types) +dotnet_diagnostic.IDE0029.severity = warning +# IDE0030: Use coalesce expression (nullable types) +dotnet_diagnostic.IDE0030.severity = warning +# IDE0031: Use null propagation +dotnet_diagnostic.IDE0031.severity = warning +# IDE0032: Use auto property +dotnet_diagnostic.IDE0032.severity = warning +# IDE0033: Use explicitly provided tuple name +dotnet_diagnostic.IDE0033.severity = warning +# IDE0034: Simplify 'default' expression +dotnet_diagnostic.IDE0034.severity = warning +# IDE0035: Remove unreachable code +dotnet_diagnostic.IDE0035.severity = warning +# IDE0036: Order modifiers +dotnet_diagnostic.IDE0036.severity = warning +# IDE0037: Use inferred member name +dotnet_diagnostic.IDE0037.severity = warning +# IDE0038: Use pattern matching to avoid is check followed by a cast (without variable) +dotnet_diagnostic.IDE0038.severity = suggestion +# IDE0040: Add accessibility modifiers +dotnet_diagnostic.IDE0040.severity = warning +# IDE0041: Use is null check +dotnet_diagnostic.IDE0041.severity = warning +# IDE0042: Deconstruct variable declaration +dotnet_diagnostic.IDE0042.severity = warning +# IDE0044: Add readonly modifier +dotnet_diagnostic.IDE0044.severity = warning +# IDE0045: Use conditional expression for assignment +dotnet_diagnostic.IDE0045.severity = warning +# IDE0046: Use conditional expression for return +dotnet_diagnostic.IDE0046.severity = silent +# IDE0047: Remove unnecessary parentheses +dotnet_diagnostic.IDE0047.severity = warning +# IDE0049: Use language keywords instead of framework type names for type references +dotnet_diagnostic.IDE0049.severity = warning +# IDE0051: Remove unused private member +dotnet_diagnostic.IDE0051.severity = warning +# IDE0052: Remove unread private member +dotnet_diagnostic.IDE0052.severity = suggestion +# IDE0053: Use expression body for lambdas +dotnet_diagnostic.IDE0053.severity = warning +# IDE0054: Use compound assignment +dotnet_diagnostic.IDE0054.severity = warning +# IDE0063: Use simple 'using' statement +dotnet_diagnostic.IDE0063.severity = warning +# IDE0066: Use switch expression +dotnet_diagnostic.IDE0066.severity = warning +# IDE0071: Simplify interpolation +dotnet_diagnostic.IDE0071.severity = warning +# IDE0073: Require file header +dotnet_diagnostic.IDE0073.severity = warning +# IDE0075: Simplify conditional expression +dotnet_diagnostic.IDE0075.severity = warning +# IDE0078: Use pattern matching +dotnet_diagnostic.IDE0078.severity = warning +# IDE0082: Convert typeof to nameof +dotnet_diagnostic.IDE0082.severity = warning +# IDE0083: Use pattern matching (not operator) +dotnet_diagnostic.IDE0083.severity = warning +# IDE0090: Simplify new expression +dotnet_diagnostic.IDE0090.severity = warning +# IDE0100: Remove unnecessary equality operator +dotnet_diagnostic.IDE0100.severity = warning +# IDE0110: Remove unnecessary discard +dotnet_diagnostic.IDE0110.severity = warning +# IDE1005: Use conditional delegate call +dotnet_diagnostic.IDE1005.severity = warning [*.{json}] indent_size = 2 diff --git a/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs b/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs index 56551dfed..3c06e9898 100644 --- a/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs +++ b/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs @@ -36,7 +36,7 @@ namespace Microsoft.PowerShell.EditorServices.Commands public sealed class StartEditorServicesCommand : PSCmdlet { // TODO: Remove this when we drop support for PS6. - private readonly static bool s_isWindows = + private static readonly bool s_isWindows = #if CoreCLR RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #else @@ -237,15 +237,13 @@ protected override void EndProcessing() // Create the configuration from parameters EditorServicesConfig editorServicesConfig = CreateConfigObject(); - var sessionFileWriter = new SessionFileWriter(_logger, SessionDetailsPath); + SessionFileWriter sessionFileWriter = new(_logger, SessionDetailsPath); _logger.Log(PsesLogLevel.Diagnostic, "Session file writer created"); - using (var psesLoader = EditorServicesLoader.Create(_logger, editorServicesConfig, sessionFileWriter, _loggerUnsubscribers)) - { - _logger.Log(PsesLogLevel.Verbose, "Loading EditorServices"); - // Start editor services and wait here until it shuts down - psesLoader.LoadAndRunEditorServicesAsync().GetAwaiter().GetResult(); - } + using EditorServicesLoader psesLoader = EditorServicesLoader.Create(_logger, editorServicesConfig, sessionFileWriter, _loggerUnsubscribers); + _logger.Log(PsesLogLevel.Verbose, "Loading EditorServices"); + // Start editor services and wait here until it shuts down + psesLoader.LoadAndRunEditorServicesAsync().GetAwaiter().GetResult(); } catch (Exception e) { @@ -277,7 +275,7 @@ private void StartLogging() // if it's being used as a protocol transport if (!Stdio) { - var hostLogger = new PSHostLogger(Host.UI); + PSHostLogger hostLogger = new(Host.UI); _loggerUnsubscribers.Add(_logger.Subscribe(hostLogger)); } @@ -292,7 +290,7 @@ private void StartLogging() logPath = Path.Combine(logDirPath, $"StartEditorServices-temp{randomInt.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}.log"); } - var fileLogger = StreamLogger.CreateWithNewFile(logPath); + StreamLogger fileLogger = StreamLogger.CreateWithNewFile(logPath); _disposableResources.Add(fileLogger); IDisposable fileLoggerUnsubscriber = _logger.Subscribe(fileLogger); fileLogger.AddUnsubscriber(fileLoggerUnsubscriber); @@ -316,23 +314,21 @@ private string GetLogDirPath() private void RemovePSReadLineForStartup() { _logger.Log(PsesLogLevel.Verbose, "Removing PSReadLine"); - using (var pwsh = SMA.PowerShell.Create(RunspaceMode.CurrentRunspace)) - { - bool hasPSReadLine = pwsh.AddCommand(new CmdletInfo("Microsoft.PowerShell.Core\\Get-Module", typeof(GetModuleCommand))) - .AddParameter("Name", "PSReadLine") - .Invoke() - .Any(); + using SMA.PowerShell pwsh = SMA.PowerShell.Create(RunspaceMode.CurrentRunspace); + bool hasPSReadLine = pwsh.AddCommand(new CmdletInfo("Microsoft.PowerShell.Core\\Get-Module", typeof(GetModuleCommand))) + .AddParameter("Name", "PSReadLine") + .Invoke() + .Any(); - if (hasPSReadLine) - { - pwsh.Commands.Clear(); + if (hasPSReadLine) + { + pwsh.Commands.Clear(); - pwsh.AddCommand(new CmdletInfo("Microsoft.PowerShell.Core\\Remove-Module", typeof(RemoveModuleCommand))) - .AddParameter("Name", "PSReadLine") - .AddParameter("ErrorAction", "SilentlyContinue"); + pwsh.AddCommand(new CmdletInfo("Microsoft.PowerShell.Core\\Remove-Module", typeof(RemoveModuleCommand))) + .AddParameter("Name", "PSReadLine") + .AddParameter("ErrorAction", "SilentlyContinue"); - _logger.Log(PsesLogLevel.Verbose, "Removed PSReadLine"); - } + _logger.Log(PsesLogLevel.Verbose, "Removed PSReadLine"); } } @@ -352,14 +348,14 @@ private EditorServicesConfig CreateConfigObject() bundledModulesPath)); } - var profile = (PSObject)GetVariableValue("profile"); + PSObject profile = (PSObject)GetVariableValue("profile"); - var hostInfo = new HostInfo(HostName, HostProfileId, HostVersion); + HostInfo hostInfo = new(HostName, HostProfileId, HostVersion); - var initialSessionState = Runspace.DefaultRunspace.InitialSessionState; + InitialSessionState initialSessionState = Runspace.DefaultRunspace.InitialSessionState; initialSessionState.LanguageMode = Runspace.DefaultRunspace.SessionStateProxy.LanguageMode; - var editorServicesConfig = new EditorServicesConfig( + EditorServicesConfig editorServicesConfig = new( hostInfo, Host, SessionDetailsPath, @@ -425,9 +421,9 @@ private ConsoleReplKind GetReplKind() } // TODO: Remove this when we drop support for PS6. - var psVersionTable = (Hashtable) this.SessionState.PSVariable.GetValue("PSVersionTable"); + Hashtable psVersionTable = (Hashtable)SessionState.PSVariable.GetValue("PSVersionTable"); dynamic version = psVersionTable["PSVersion"]; - var majorVersion = (int) version.Major; + int majorVersion = (int)version.Major; if (UseLegacyReadLine || (!s_isWindows && majorVersion == 6)) { diff --git a/src/PowerShellEditorServices.Hosting/Configuration/HostLogger.cs b/src/PowerShellEditorServices.Hosting/Configuration/HostLogger.cs index 2a081e7e2..10ea4d401 100644 --- a/src/PowerShellEditorServices.Hosting/Configuration/HostLogger.cs +++ b/src/PowerShellEditorServices.Hosting/Configuration/HostLogger.cs @@ -49,25 +49,13 @@ private class LogObserver : IObserver<(PsesLogLevel logLevel, string message)> { private readonly IObserver<(int logLevel, string message)> _observer; - public LogObserver(IObserver<(int logLevel, string message)> observer) - { - _observer = observer; - } + public LogObserver(IObserver<(int logLevel, string message)> observer) => _observer = observer; - public void OnCompleted() - { - _observer.OnCompleted(); - } + public void OnCompleted() => _observer.OnCompleted(); - public void OnError(Exception error) - { - _observer.OnError(error); - } + public void OnError(Exception error) => _observer.OnError(error); - public void OnNext((PsesLogLevel logLevel, string message) value) - { - _observer.OnNext(((int)value.logLevel, value.message)); - } + public void OnNext((PsesLogLevel logLevel, string message) value) => _observer.OnNext(((int)value.logLevel, value.message)); } /// @@ -86,10 +74,7 @@ public Unsubscriber(ConcurrentDictionary, bool _thisSubscriber = thisSubscriber; } - public void Dispose() - { - _subscribedObservers.TryRemove(_thisSubscriber, out bool _); - } + public void Dispose() => _subscribedObservers.TryRemove(_thisSubscriber, out bool _); } private readonly PsesLogLevel _minimumLogLevel; @@ -185,10 +170,7 @@ public void LogException( Exception exception, [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}"); - } + [CallerLineNumber] int callerLineNumber = -1) => Log(PsesLogLevel.Error, $"{message}. Exception logged in {callerSourceFile} on line {callerLineNumber} in {callerName}:\n{exception}"); } @@ -209,10 +191,7 @@ internal class PSHostLogger : IObserver<(PsesLogLevel logLevel, string message)> /// Create a new PowerShell host logger. /// /// The PowerShell host user interface object to log output to. - public PSHostLogger(PSHostUserInterface ui) - { - _ui = ui; - } + public PSHostLogger(PSHostUserInterface ui) => _ui = ui; public void OnCompleted() { @@ -220,10 +199,7 @@ public void OnCompleted() // we just stop writing to the host } - public void OnError(Exception error) - { - OnNext((PsesLogLevel.Error, $"Error occurred while logging: {error}")); - } + public void OnError(Exception error) => OnNext((PsesLogLevel.Error, $"Error occurred while logging: {error}")); public void OnNext((PsesLogLevel logLevel, string message) value) { @@ -260,7 +236,7 @@ internal class StreamLogger : IObserver<(PsesLogLevel logLevel, string message)> { public static StreamLogger CreateWithNewFile(string path) { - var fileStream = new FileStream( + FileStream fileStream = new( path, FileMode.Create, FileAccess.Write, @@ -321,10 +297,7 @@ public void OnCompleted() _messageQueue.Dispose(); } - public void OnError(Exception error) - { - OnNext((PsesLogLevel.Error, $"Error occurred while logging: {error}")); - } + public void OnError(Exception error) => OnNext((PsesLogLevel.Error, $"Error occurred while logging: {error}")); public void OnNext((PsesLogLevel logLevel, string message) value) { @@ -355,15 +328,9 @@ public void OnNext((PsesLogLevel logLevel, string message) value) _messageQueue.Add(message); } - public void AddUnsubscriber(IDisposable unsubscriber) - { - _unsubscriber = unsubscriber; - } + public void AddUnsubscriber(IDisposable unsubscriber) => _unsubscriber = unsubscriber; - public void Dispose() - { - OnCompleted(); - } + public void Dispose() => OnCompleted(); private void RunWriter() { diff --git a/src/PowerShellEditorServices.Hosting/Configuration/SessionFileWriter.cs b/src/PowerShellEditorServices.Hosting/Configuration/SessionFileWriter.cs index c7257bc4a..207ef67ab 100644 --- a/src/PowerShellEditorServices.Hosting/Configuration/SessionFileWriter.cs +++ b/src/PowerShellEditorServices.Hosting/Configuration/SessionFileWriter.cs @@ -63,7 +63,7 @@ public void WriteSessionFailure(string reason, object details) { _logger.Log(PsesLogLevel.Diagnostic, "Writing session failure"); - var sessionObject = new Dictionary + Dictionary sessionObject = new() { { "status", "failed" }, { "reason", reason }, @@ -86,7 +86,7 @@ public void WriteSessionStarted(ITransportConfig languageServiceTransport, ITran { _logger.Log(PsesLogLevel.Diagnostic, "Writing session started"); - var sessionObject = new Dictionary + Dictionary sessionObject = new() { { "status", "started" }, }; @@ -128,7 +128,7 @@ private void WriteSessionObject(Dictionary sessionObject) { string psModulePath = Environment.GetEnvironmentVariable("PSModulePath"); string content = null; - using (var pwsh = SMA.PowerShell.Create(RunspaceMode.NewRunspace)) + using (SMA.PowerShell pwsh = SMA.PowerShell.Create(RunspaceMode.NewRunspace)) { content = pwsh.AddCommand("ConvertTo-Json") .AddParameter("InputObject", sessionObject) diff --git a/src/PowerShellEditorServices.Hosting/Configuration/TransportConfig.cs b/src/PowerShellEditorServices.Hosting/Configuration/TransportConfig.cs index 1885b17db..041d1a9df 100644 --- a/src/PowerShellEditorServices.Hosting/Configuration/TransportConfig.cs +++ b/src/PowerShellEditorServices.Hosting/Configuration/TransportConfig.cs @@ -43,10 +43,7 @@ public sealed class StdioTransportConfig : ITransportConfig { private readonly HostLogger _logger; - public StdioTransportConfig(HostLogger logger) - { - _logger = logger; - } + public StdioTransportConfig(HostLogger logger) => _logger = logger; public string EndpointDetails => ""; @@ -70,10 +67,8 @@ 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) - { - return new DuplexNamedPipeTransportConfig(logger, NamedPipeUtils.GenerateValidNamedPipeName()); - } + + public static DuplexNamedPipeTransportConfig Create(HostLogger logger) => new(logger, NamedPipeUtils.GenerateValidNamedPipeName()); /// /// Create a duplex named pipe transport config with the given pipe name. @@ -97,7 +92,7 @@ private DuplexNamedPipeTransportConfig(HostLogger logger, string pipeName) { _logger = logger; _pipeName = pipeName; - SessionFileEntries = new Dictionary{ { "PipeName", NamedPipeUtils.GetNamedPipePath(pipeName) } }; + SessionFileEntries = new Dictionary { { "PipeName", NamedPipeUtils.GetNamedPipePath(pipeName) } }; } public string EndpointDetails => $"InOut pipe: {_pipeName}"; @@ -129,10 +124,7 @@ public sealed class SimplexNamedPipeTransportConfig : ITransportConfig /// Create a pair of simplex named pipes using generated names. /// /// A new simplex named pipe transport config. - public static SimplexNamedPipeTransportConfig Create(HostLogger logger) - { - return SimplexNamedPipeTransportConfig.Create(logger, NamedPipeUtils.GenerateValidNamedPipeName(new[] { InPipePrefix, OutPipePrefix })); - } + public static SimplexNamedPipeTransportConfig Create(HostLogger logger) => SimplexNamedPipeTransportConfig.Create(logger, NamedPipeUtils.GenerateValidNamedPipeName(new[] { InPipePrefix, OutPipePrefix })); /// /// Create a pair of simplex named pipes using the given name as a base. @@ -155,10 +147,7 @@ public static SimplexNamedPipeTransportConfig Create(HostLogger logger, string p /// Create a pair of simplex named pipes using the given names. /// /// A new simplex named pipe transport config. - public static SimplexNamedPipeTransportConfig Create(HostLogger logger, string inPipeName, string outPipeName) - { - return new SimplexNamedPipeTransportConfig(logger, inPipeName, outPipeName); - } + public static SimplexNamedPipeTransportConfig Create(HostLogger logger, string inPipeName, string outPipeName) => new(logger, inPipeName, outPipeName); private readonly HostLogger _logger; private readonly string _inPipeName; diff --git a/src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs b/src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs index 2d62fc164..b83a8ac84 100644 --- a/src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs +++ b/src/PowerShellEditorServices.Hosting/EditorServicesLoader.cs @@ -80,7 +80,7 @@ public static EditorServicesLoader Create( // In .NET Core, we add an event here to redirect dependency loading to the new AssemblyLoadContext we load PSES' dependencies into logger.Log(PsesLogLevel.Verbose, "Adding AssemblyResolve event handler for new AssemblyLoadContext dependency loading"); - var psesLoadContext = new PsesLoadContext(s_psesDependencyDirPath); + PsesLoadContext psesLoadContext = new(s_psesDependencyDirPath); if (hostConfig.LogLevel == PsesLogLevel.Diagnostic) { @@ -140,8 +140,8 @@ public static EditorServicesLoader Create( logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {args.Name}"); #endif - var asmName = new AssemblyName(args.Name); - var dllName = $"{asmName.Name}.dll"; + AssemblyName asmName = new(args.Name); + string dllName = $"{asmName.Name}.dll"; // First look for the required assembly in the .NET Framework DLL dir string baseDirAsmPath = Path.Combine(s_psesBaseDirPath, dllName); @@ -231,31 +231,27 @@ public void Dispose() // This is not high priority, since the PSES process shouldn't be reused } - private static void LoadEditorServices() - { + private static void LoadEditorServices() => // This must be in its own method, since the actual load happens when the calling method is called // The call within this method is therefore a total no-op EditorServicesLoading.LoadEditorServicesForHost(); - } #if !CoreCLR private void CheckNetFxVersion() { _logger.Log(PsesLogLevel.Diagnostic, "Checking that .NET Framework version is at least 4.6.1"); - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full")) + using RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full"); + object netFxValue = key?.GetValue("Release"); + if (netFxValue == null || netFxValue is not int netFxVersion) { - object netFxValue = key?.GetValue("Release"); - if (netFxValue == null || !(netFxValue is int netFxVersion)) - { - return; - } + return; + } - _logger.Log(PsesLogLevel.Verbose, $".NET registry version: {netFxVersion}"); + _logger.Log(PsesLogLevel.Verbose, $".NET registry version: {netFxVersion}"); - if (netFxVersion < Net461Version) - { - _logger.Log(PsesLogLevel.Warning, $".NET Framework version {netFxVersion} lower than .NET 4.6.1. This runtime is not supported and you may experience errors. Please update your .NET runtime version."); - } + if (netFxVersion < Net461Version) + { + _logger.Log(PsesLogLevel.Warning, $".NET Framework version {netFxVersion} lower than .NET 4.6.1. This runtime is not supported and you may experience errors. Please update your .NET runtime version."); } } #endif @@ -328,10 +324,8 @@ private void LogHostInformation() private static string GetPSOutputEncoding() { - using (var pwsh = SMA.PowerShell.Create()) - { - return pwsh.AddScript("$OutputEncoding.EncodingName", useLocalScope: true).Invoke()[0]; - } + using SMA.PowerShell pwsh = SMA.PowerShell.Create(); + return pwsh.AddScript("$OutputEncoding.EncodingName", useLocalScope: true).Invoke()[0]; } private void LogPowerShellDetails() @@ -408,10 +402,12 @@ private static object GetPSVersion() // which is expensive. // Rather than do that, we instead go straight to the source, // which is a static property, internal in WinPS and public in PS 6+ +#pragma warning disable CA1825 return typeof(PSObject).Assembly .GetType("System.Management.Automation.PSVersionInfo") .GetMethod("get_PSVersion", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Invoke(null, new object[0] /* Cannot use Array.Empty, since it must work in net452 */); +#pragma warning restore CA1825 } } } diff --git a/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs b/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs index 896a3d09f..2cb1b0e73 100644 --- a/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs +++ b/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs @@ -75,10 +75,7 @@ public Task RunUntilShutdown() /// only because of the use of that this class is also /// disposable, and instead that class should be fixed. /// - public void Dispose() - { - _serverFactory.Dispose(); - } + public void Dispose() => _serverFactory.Dispose(); /// /// This is the servers' entry point, e.g. main, as it instantiates, runs and waits @@ -93,14 +90,14 @@ public void Dispose() /// Description /// /// - /// + /// /// /// The StartEditorServicesCommand PSCmdlet, our PowerShell cmdlet written in C# and /// shipped in the module. /// /// /// - /// + /// /// /// As a cmdlet, this is the end of its "process" block, and it instantiates . @@ -309,7 +306,7 @@ private void WriteStartupBanner() private void DebugServer_OnSessionEnded(object sender, EventArgs args) { _logger.Log(PsesLogLevel.Verbose, "Debug session ended, restarting debug service..."); - var oldServer = (PsesDebugServer)sender; + PsesDebugServer oldServer = (PsesDebugServer)sender; oldServer.Dispose(); _alreadySubscribedDebug = false; Task.Run(() => diff --git a/src/PowerShellEditorServices.Hosting/Internal/NamedPipeUtils.cs b/src/PowerShellEditorServices.Hosting/Internal/NamedPipeUtils.cs index 30b0f7f28..4df8c38fa 100644 --- a/src/PowerShellEditorServices.Hosting/Internal/NamedPipeUtils.cs +++ b/src/PowerShellEditorServices.Hosting/Internal/NamedPipeUtils.cs @@ -39,10 +39,10 @@ internal static NamedPipeServerStream CreateNamedPipe( // In .NET Framework, we must manually ACL the named pipes we create - var pipeSecurity = new PipeSecurity(); + PipeSecurity pipeSecurity = new(); WindowsIdentity identity = WindowsIdentity.GetCurrent(); - WindowsPrincipal principal = new WindowsPrincipal(identity); + WindowsPrincipal principal = new(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { @@ -137,6 +137,7 @@ public static bool IsPipeNameValid(string pipeName) /// /// The simple name of the named pipe. /// The full path of the named pipe. +#pragma warning disable IDE0022 public static string GetNamedPipePath(string pipeName) { #if CoreCLR @@ -149,4 +150,5 @@ public static string GetNamedPipePath(string pipeName) return $@"\\.\pipe\{pipeName}"; } } +#pragma warning restore IDE0022 } diff --git a/src/PowerShellEditorServices.VSCode/Cmdlets/VSCodeHtmlContentViewCommands.cs b/src/PowerShellEditorServices.VSCode/Cmdlets/VSCodeHtmlContentViewCommands.cs index 70e8113a7..f7d090ff8 100644 --- a/src/PowerShellEditorServices.VSCode/Cmdlets/VSCodeHtmlContentViewCommands.cs +++ b/src/PowerShellEditorServices.VSCode/Cmdlets/VSCodeHtmlContentViewCommands.cs @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.EditorServices.VSCode { /// - [Cmdlet(VerbsCommon.New,"VSCodeHtmlContentView")] + [Cmdlet(VerbsCommon.New, "VSCodeHtmlContentView")] [OutputType(typeof(IHtmlContentView))] public class NewVSCodeHtmlContentViewCommand : PSCmdlet { @@ -59,7 +59,8 @@ protected override void BeginProcessing() .GetAwaiter() .GetResult(); - if (_showInColumn != null) { + if (_showInColumn != null) + { try { view.Show(_showInColumn.Value).GetAwaiter().GetResult(); @@ -82,7 +83,7 @@ protected override void BeginProcessing() } /// - [Cmdlet(VerbsCommon.Set,"VSCodeHtmlContentView")] + [Cmdlet(VerbsCommon.Set, "VSCodeHtmlContentView")] public class SetVSCodeHtmlContentViewCommand : PSCmdlet { /// @@ -108,7 +109,7 @@ public class SetVSCodeHtmlContentViewCommand : PSCmdlet /// protected override void BeginProcessing() { - var htmlContent = new HtmlContent(); + HtmlContent htmlContent = new(); htmlContent.BodyContent = HtmlBodyContent; htmlContent.JavaScriptPaths = JavaScriptPaths; htmlContent.StyleSheetPaths = StyleSheetPaths; @@ -129,7 +130,7 @@ protected override void BeginProcessing() } /// - [Cmdlet(VerbsCommon.Close,"VSCodeHtmlContentView")] + [Cmdlet(VerbsCommon.Close, "VSCodeHtmlContentView")] public class CloseVSCodeHtmlContentViewCommand : PSCmdlet { /// @@ -158,7 +159,7 @@ protected override void BeginProcessing() } /// - [Cmdlet(VerbsCommon.Show,"VSCodeHtmlContentView")] + [Cmdlet(VerbsCommon.Show, "VSCodeHtmlContentView")] public class ShowVSCodeHtmlContentViewCommand : PSCmdlet { /// @@ -193,7 +194,7 @@ protected override void BeginProcessing() } /// - [Cmdlet(VerbsCommunications.Write,"VSCodeHtmlContentView")] + [Cmdlet(VerbsCommunications.Write, "VSCodeHtmlContentView")] public class WriteVSCodeHtmlContentViewCommand : PSCmdlet { /// diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs index b0cc81605..aa49f3607 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs @@ -22,9 +22,9 @@ public CustomViewBase( CustomViewType viewType, ILanguageServerService languageServer) { - this.Id = Guid.NewGuid(); - this.Title = viewTitle; - this.ViewType = viewType; + Id = Guid.NewGuid(); + Title = viewTitle; + ViewType = viewType; this.languageServer = languageServer; } @@ -33,9 +33,9 @@ internal Task CreateAsync() => NewCustomViewRequest.Method, new NewCustomViewRequest { - Id = this.Id, - Title = this.Title, - ViewType = this.ViewType, + Id = Id, + Title = Title, + ViewType = ViewType, }); public Task Show(ViewColumn viewColumn) => @@ -43,7 +43,7 @@ public Task Show(ViewColumn viewColumn) => ShowCustomViewRequest.Method, new ShowCustomViewRequest { - Id = this.Id, + Id = Id, ViewColumn = viewColumn }); @@ -52,7 +52,7 @@ public Task Close() => CloseCustomViewRequest.Method, new CloseCustomViewRequest { - Id = this.Id, + Id = Id, }); } } diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewFeature.cs b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewFeature.cs index 087af149d..3c7b07a3f 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewFeature.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewFeature.cs @@ -17,13 +17,10 @@ internal abstract class CustomViewFeatureBase public CustomViewFeatureBase( ILanguageServerService languageServer) { - this.viewIndex = new Dictionary(); + viewIndex = new Dictionary(); this.languageServer = languageServer; } - protected void AddView(TView view) - { - this.viewIndex.Add(view.Id, view); - } + protected void AddView(TView view) => viewIndex.Add(view.Id, view); } } diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewMessages.cs b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewMessages.cs index 7aa3885f3..254959b0d 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewMessages.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewMessages.cs @@ -28,7 +28,7 @@ public class NewCustomViewRequest /// /// Gets or sets the view's type. /// - public CustomViewType ViewType { get; set;} + public CustomViewType ViewType { get; set; } } /// diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs b/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs index ca3e53ad6..5e5401148 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs @@ -26,7 +26,7 @@ public Task SetContentAsync(string htmlBodyContent) => SetHtmlContentViewRequest.Method, new SetHtmlContentViewRequest { - Id = this.Id, + Id = Id, HtmlContent = new HtmlContent { BodyContent = htmlBodyContent } } ); @@ -36,7 +36,7 @@ public Task SetContentAsync(HtmlContent htmlContent) => SetHtmlContentViewRequest.Method, new SetHtmlContentViewRequest { - Id = this.Id, + Id = Id, HtmlContent = new HtmlContent() { BodyContent = htmlContent.BodyContent, @@ -51,7 +51,7 @@ public Task AppendContentAsync(string appendedHtmlBodyContent) => AppendHtmlContentViewRequest.Method, new AppendHtmlContentViewRequest { - Id = this.Id, + Id = Id, AppendedHtmlBodyContent = appendedHtmlBodyContent } ); @@ -60,7 +60,8 @@ private static string[] GetUriPaths(string[] filePaths) { return filePaths? - .Select(p => { + .Select(p => + { return new Uri( Path.GetFullPath(p), diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs b/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs index dfdf5e3cb..b20a31025 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs @@ -17,12 +17,12 @@ public HtmlContentViewsFeature( public async Task CreateHtmlContentViewAsync(string viewTitle) { HtmlContentView htmlView = - new HtmlContentView( + new( viewTitle, languageServer); await htmlView.CreateAsync().ConfigureAwait(false); - this.AddView(htmlView); + AddView(htmlView); return htmlView; } diff --git a/src/PowerShellEditorServices/Extensions/Api/EditorContextService.cs b/src/PowerShellEditorServices/Extensions/Api/EditorContextService.cs index 9229f7071..b3ba87411 100644 --- a/src/PowerShellEditorServices/Extensions/Api/EditorContextService.cs +++ b/src/PowerShellEditorServices/Extensions/Api/EditorContextService.cs @@ -85,15 +85,12 @@ internal class EditorContextService : IEditorContextService private readonly ILanguageServerFacade _languageServer; internal EditorContextService( - ILanguageServerFacade languageServer) - { - _languageServer = languageServer; - } + ILanguageServerFacade languageServer) => _languageServer = languageServer; public async Task GetCurrentLspFileContextAsync() { ClientEditorContext clientContext = - await _languageServer.SendRequest( + await _languageServer.SendRequest( "editor/getEditorContext", new GetEditorContextRequest()) .Returning(CancellationToken.None) @@ -102,10 +99,7 @@ await _languageServer.SendRequest( return new LspCurrentFileContext(clientContext); } - public Task OpenNewUntitledFileAsync() - { - return _languageServer.SendRequest("editor/newFile", null).ReturningVoid(CancellationToken.None); - } + public Task OpenNewUntitledFileAsync() => _languageServer.SendRequest("editor/newFile", null).ReturningVoid(CancellationToken.None); public Task OpenFileAsync(Uri fileUri) => OpenFileAsync(fileUri, preview: false); @@ -118,10 +112,7 @@ public Task OpenFileAsync(Uri fileUri, bool preview) }).ReturningVoid(CancellationToken.None); } - public Task CloseFileAsync(Uri fileUri) - { - return _languageServer.SendRequest("editor/closeFile", fileUri.LocalPath).ReturningVoid(CancellationToken.None); - } + public Task CloseFileAsync(Uri fileUri) => _languageServer.SendRequest("editor/closeFile", fileUri.LocalPath).ReturningVoid(CancellationToken.None); public Task SaveFileAsync(Uri fileUri) => SaveFileAsync(fileUri, null); diff --git a/src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs b/src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs index 73e8e209e..38e5df692 100644 --- a/src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs +++ b/src/PowerShellEditorServices/Extensions/Api/EditorExtensionServiceProvider.cs @@ -20,13 +20,13 @@ public class EditorExtensionServiceProvider { private static readonly Assembly s_psesAsm = typeof(EditorExtensionServiceProvider).Assembly; - private static readonly Lazy s_psesAsmLoadContextLazy = new Lazy(GetPsesAsmLoadContext); + private static readonly Lazy s_psesAsmLoadContextLazy = new(GetPsesAsmLoadContext); - private static readonly Lazy s_asmLoadContextType = new Lazy(() => Type.GetType("System.Runtime.Loader.AssemblyLoadContext")); + private static readonly Lazy s_asmLoadContextType = new(() => Type.GetType("System.Runtime.Loader.AssemblyLoadContext")); - private static readonly Lazy> s_enterPsesReflectionContextLazy = new Lazy>(GetPsesAlcReflectionContextEntryFunc); + private static readonly Lazy> s_enterPsesReflectionContextLazy = new(GetPsesAlcReflectionContextEntryFunc); - private static readonly Lazy> s_loadAssemblyInPsesAlc = new Lazy>(GetPsesAlcLoadAsmFunc); + private static readonly Lazy> s_loadAssemblyInPsesAlc = new(GetPsesAlcLoadAsmFunc); private static Type AsmLoadContextType => s_asmLoadContextType.Value; @@ -146,10 +146,7 @@ public object GetServiceByAssemblyQualifiedName(string asmQualifiedTypeName) /// 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. /// - public object GetService(Type serviceType) - { - return _serviceProvider.GetService(serviceType); - } + public object GetService(Type serviceType) => _serviceProvider.GetService(serviceType); /// /// Get the assembly load context the PSES loads its dependencies into. diff --git a/src/PowerShellEditorServices/Extensions/Api/EditorUIService.cs b/src/PowerShellEditorServices/Extensions/Api/EditorUIService.cs index 1fcafabcf..4b50e6e41 100644 --- a/src/PowerShellEditorServices/Extensions/Api/EditorUIService.cs +++ b/src/PowerShellEditorServices/Extensions/Api/EditorUIService.cs @@ -99,19 +99,16 @@ public interface IEditorUIService internal class EditorUIService : IEditorUIService { - private static string[] s_choiceResponseLabelSeparators = new[] { ", " }; + private static readonly string[] s_choiceResponseLabelSeparators = new[] { ", " }; private readonly ILanguageServerFacade _languageServer; - public EditorUIService(ILanguageServerFacade languageServer) - { - _languageServer = languageServer; - } + public EditorUIService(ILanguageServerFacade languageServer) => _languageServer = languageServer; public async Task PromptInputAsync(string message) { // The VSCode client currently doesn't use the Label field, so we ignore it - ShowInputPromptResponse response = await _languageServer.SendRequest( + ShowInputPromptResponse response = await _languageServer.SendRequest( "powerShell/showInputPrompt", new ShowInputPromptRequest { @@ -135,7 +132,7 @@ public async Task> PromptMultipleSelectionAsync(string mes { ChoiceDetails[] choiceDetails = GetChoiceDetails(choices); - ShowChoicePromptResponse response = await _languageServer.SendRequest( + ShowChoicePromptResponse response = await _languageServer.SendRequest( "powerShell/showChoicePrompt", new ShowChoicePromptRequest { @@ -163,7 +160,7 @@ public async Task PromptSelectionAsync(string message, IReadOnlyList( + ShowChoicePromptResponse response = await _languageServer.SendRequest( "powerShell/showChoicePrompt", new ShowChoicePromptRequest { @@ -186,17 +183,17 @@ public async Task PromptSelectionAsync(string message, IReadOnlyList promptChoiceDetails) { - var choices = new ChoiceDetails[promptChoiceDetails.Count]; + ChoiceDetails[] choices = new ChoiceDetails[promptChoiceDetails.Count]; for (int i = 0; i < promptChoiceDetails.Count; i++) { choices[i] = new ChoiceDetails { - Label = promptChoiceDetails[i].Label, - HelpMessage = promptChoiceDetails[i].HelpMessage, + Label = promptChoiceDetails[i].Label, + HelpMessage = promptChoiceDetails[i].HelpMessage, // There were intended to enable hotkey use for choice selections, // but currently VSCode does not do anything with them. // They can be exposed once VSCode supports them. - HotKeyIndex = -1, + HotKeyIndex = -1, HotKeyCharacter = null, }; } diff --git a/src/PowerShellEditorServices/Extensions/Api/ExtensionCommandService.cs b/src/PowerShellEditorServices/Extensions/Api/ExtensionCommandService.cs index 10ddc55a7..9a3b4ca3a 100644 --- a/src/PowerShellEditorServices/Extensions/Api/ExtensionCommandService.cs +++ b/src/PowerShellEditorServices/Extensions/Api/ExtensionCommandService.cs @@ -85,19 +85,10 @@ public ExtensionCommandService(ExtensionService extensionService) public void UnregisterCommand(string commandName) => _extensionService.UnregisterCommand(commandName); - private void OnCommandAdded(object sender, EditorCommand editorCommand) - { - CommandAdded?.Invoke(this, editorCommand); - } + private void OnCommandAdded(object sender, EditorCommand editorCommand) => CommandAdded?.Invoke(this, editorCommand); - private void OnCommandUpdated(object sender, EditorCommand editorCommand) - { - CommandUpdated?.Invoke(this, editorCommand); - } + private void OnCommandUpdated(object sender, EditorCommand editorCommand) => CommandUpdated?.Invoke(this, editorCommand); - private void OnCommandRemoved(object sender, EditorCommand editorCommand) - { - CommandRemoved?.Invoke(this, editorCommand); - } + private void OnCommandRemoved(object sender, EditorCommand editorCommand) => CommandRemoved?.Invoke(this, editorCommand); } } diff --git a/src/PowerShellEditorServices/Extensions/Api/LanguageServerService.cs b/src/PowerShellEditorServices/Extensions/Api/LanguageServerService.cs index 1a5254319..4d0de1a7e 100644 --- a/src/PowerShellEditorServices/Extensions/Api/LanguageServerService.cs +++ b/src/PowerShellEditorServices/Extensions/Api/LanguageServerService.cs @@ -65,49 +65,22 @@ internal class LanguageServerService : ILanguageServerService { private readonly ILanguageServerFacade _languageServer; - internal LanguageServerService(ILanguageServerFacade languageServer) - { - _languageServer = languageServer; - } - - public void SendNotification(string method) - { - _languageServer.SendNotification(method); - } - - public void SendNotification(string method, T parameters) - { - _languageServer.SendNotification(method, parameters); - } - - public void SendNotification(string method, object parameters) - { - _languageServer.SendNotification(method, parameters); - } - - public Task SendRequestAsync(string method) - { - return _languageServer.SendRequest(method).ReturningVoid(CancellationToken.None); - } - - public Task SendRequestAsync(string method, T parameters) - { - return _languageServer.SendRequest(method, parameters).ReturningVoid(CancellationToken.None); - } - - public Task SendRequestAsync(string method) - { - return _languageServer.SendRequest(method).Returning(CancellationToken.None); - } - - public Task SendRequestAsync(string method, T parameters) - { - return _languageServer.SendRequest(method, parameters).Returning(CancellationToken.None); - } - - public Task SendRequestAsync(string method, object parameters) - { - return _languageServer.SendRequest(method, parameters).Returning(CancellationToken.None); - } + internal LanguageServerService(ILanguageServerFacade languageServer) => _languageServer = languageServer; + + public void SendNotification(string method) => _languageServer.SendNotification(method); + + public void SendNotification(string method, T parameters) => _languageServer.SendNotification(method, parameters); + + public void SendNotification(string method, object parameters) => _languageServer.SendNotification(method, parameters); + + public Task SendRequestAsync(string method) => _languageServer.SendRequest(method).ReturningVoid(CancellationToken.None); + + public Task SendRequestAsync(string method, T parameters) => _languageServer.SendRequest(method, parameters).ReturningVoid(CancellationToken.None); + + public Task SendRequestAsync(string method) => _languageServer.SendRequest(method).Returning(CancellationToken.None); + + public Task SendRequestAsync(string method, T parameters) => _languageServer.SendRequest(method, parameters).Returning(CancellationToken.None); + + public Task SendRequestAsync(string method, object parameters) => _languageServer.SendRequest(method, parameters).Returning(CancellationToken.None); } } diff --git a/src/PowerShellEditorServices/Extensions/Api/WorkspaceService.cs b/src/PowerShellEditorServices/Extensions/Api/WorkspaceService.cs index dc1300e00..443183f49 100644 --- a/src/PowerShellEditorServices/Extensions/Api/WorkspaceService.cs +++ b/src/PowerShellEditorServices/Extensions/Api/WorkspaceService.cs @@ -138,7 +138,7 @@ public bool TryGetFile(Uri fileUri, out IEditorScriptFile file) public IReadOnlyList GetOpenedFiles() { - var files = new List(); + List files = new(); foreach (ScriptFile openedFile in _workspaceService.GetOpenedFiles()) { files.Add(GetEditorFileFromScriptFile(openedFile)); @@ -146,9 +146,6 @@ public IReadOnlyList GetOpenedFiles() return files.AsReadOnly(); } - private static IEditorScriptFile GetEditorFileFromScriptFile(ScriptFile file) - { - return new EditorScriptFile(file); - } + private static IEditorScriptFile GetEditorFileFromScriptFile(ScriptFile file) => new EditorScriptFile(file); } } diff --git a/src/PowerShellEditorServices/Extensions/EditorCommand.cs b/src/PowerShellEditorServices/Extensions/EditorCommand.cs index a6575493c..966adff27 100644 --- a/src/PowerShellEditorServices/Extensions/EditorCommand.cs +++ b/src/PowerShellEditorServices/Extensions/EditorCommand.cs @@ -75,10 +75,10 @@ public EditorCommand( bool suppressOutput, ScriptBlock scriptBlock) { - this.Name = commandName; - this.DisplayName = displayName; - this.SuppressOutput = suppressOutput; - this.ScriptBlock = scriptBlock; + Name = commandName; + DisplayName = displayName; + SuppressOutput = suppressOutput; + ScriptBlock = scriptBlock; } #endregion diff --git a/src/PowerShellEditorServices/Extensions/EditorContext.cs b/src/PowerShellEditorServices/Extensions/EditorContext.cs index a844febe3..d223dcf6a 100644 --- a/src/PowerShellEditorServices/Extensions/EditorContext.cs +++ b/src/PowerShellEditorServices/Extensions/EditorContext.cs @@ -12,7 +12,7 @@ public sealed class EditorContext { #region Private Fields - private IEditorOperations editorOperations; + private readonly IEditorOperations editorOperations; #endregion @@ -53,9 +53,9 @@ internal EditorContext( string language = "Unknown") { this.editorOperations = editorOperations; - this.CurrentFile = new FileContext(currentFile, this, editorOperations, language); - this.SelectedRange = new BufferFileRange(selectedRange); - this.CursorPosition = new BufferFilePosition(cursorPosition); + CurrentFile = new FileContext(currentFile, this, editorOperations, language); + SelectedRange = new BufferFileRange(selectedRange); + CursorPosition = new BufferFilePosition(cursorPosition); } #endregion @@ -75,7 +75,7 @@ public void SetSelection( int endLine, int endColumn) { - this.SetSelection( + SetSelection( new FileRange( new FilePosition(startLine, startColumn), new FilePosition(endLine, endColumn))); @@ -90,7 +90,7 @@ public void SetSelection( FilePosition startPosition, FilePosition endPosition) { - this.SetSelection( + SetSelection( new FileRange( startPosition, endPosition)); @@ -102,7 +102,7 @@ public void SetSelection( /// The range of the selection. public void SetSelection(FileRange selectionRange) { - this.editorOperations + editorOperations .SetSelectionAsync(selectionRange.ToBufferRange()) .Wait(); } diff --git a/src/PowerShellEditorServices/Extensions/EditorFileRanges.cs b/src/PowerShellEditorServices/Extensions/EditorFileRanges.cs index c7a7d5b38..cbefa4277 100644 --- a/src/PowerShellEditorServices/Extensions/EditorFileRanges.cs +++ b/src/PowerShellEditorServices/Extensions/EditorFileRanges.cs @@ -37,7 +37,7 @@ public static FileScriptPosition FromOffset(FileContext file, int offset) if (offset >= fileText.Length) { - throw new ArgumentException(nameof(offset), "Offset greater than file length"); + throw new ArgumentException("Offset greater than file length", nameof(offset)); } int lastLineOffset = -1; @@ -253,48 +253,33 @@ internal struct OmnisharpLspPosition : ILspFilePosition, IEquatable _position = position; public int Line => _position.Line; public int Character => _position.Character; - public bool Equals(OmnisharpLspPosition other) - { - return _position == other._position; - } + public bool Equals(OmnisharpLspPosition other) => _position == other._position; } internal struct OmnisharpLspRange : ILspFileRange, IEquatable { private readonly Range _range; - public OmnisharpLspRange(Range range) - { - _range = range; - } + public OmnisharpLspRange(Range range) => _range = range; public ILspFilePosition Start => new OmnisharpLspPosition(_range.Start); public ILspFilePosition End => new OmnisharpLspPosition(_range.End); - public bool Equals(OmnisharpLspRange other) - { - return _range == other._range; - } + public bool Equals(OmnisharpLspRange other) => _range == other._range; } internal struct BufferFilePosition : IFilePosition, IEquatable { private readonly BufferPosition _position; - public BufferFilePosition(BufferPosition position) - { - _position = position; - } + public BufferFilePosition(BufferPosition position) => _position = position; public int Line => _position.Line; @@ -311,10 +296,7 @@ internal struct BufferFileRange : IFileRange, IEquatable { private readonly BufferRange _range; - public BufferFileRange(BufferRange range) - { - _range = range; - } + public BufferFileRange(BufferRange range) => _range = range; public IFilePosition Start => new BufferFilePosition(_range.Start); @@ -431,40 +413,28 @@ public static class FileObjectExtensionMethods /// /// The 1-based file position to convert. /// An equivalent 0-based file position. - public static ILspFilePosition ToLspPosition(this IFilePosition position) - { - return new LspFilePosition(position.Line - 1, position.Column - 1); - } + public static ILspFilePosition ToLspPosition(this IFilePosition position) => new LspFilePosition(position.Line - 1, position.Column - 1); /// /// Convert a 1-based file range to a 0-based file range. /// /// The 1-based file range to convert. /// An equivalent 0-based file range. - public static ILspFileRange ToLspRange(this IFileRange range) - { - return new LspFileRange(range.Start.ToLspPosition(), range.End.ToLspPosition()); - } + public static ILspFileRange ToLspRange(this IFileRange range) => new LspFileRange(range.Start.ToLspPosition(), range.End.ToLspPosition()); /// /// Convert a 0-based file position to a 1-based file position. /// /// The 0-based file position to convert. /// An equivalent 1-based file position. - public static IFilePosition ToFilePosition(this ILspFilePosition position) - { - return new FilePosition(position.Line + 1, position.Character + 1); - } + public static IFilePosition ToFilePosition(this ILspFilePosition position) => new FilePosition(position.Line + 1, position.Character + 1); /// /// Convert a 0-based file range to a 1-based file range. /// /// The 0-based file range to convert. /// An equivalent 1-based file range. - public static IFileRange ToFileRange(this ILspFileRange range) - { - return new FileRange(range.Start.ToFilePosition(), range.End.ToFilePosition()); - } + public static IFileRange ToFileRange(this ILspFileRange range) => new FileRange(range.Start.ToFilePosition(), range.End.ToFilePosition()); internal static bool HasRange(this IFileRange range) { @@ -473,34 +443,16 @@ internal static bool HasRange(this IFileRange range) && range.End.Line != 0 && range.End.Column != 0; } - internal static ILspFilePosition ToLspPosition(this Position position) - { - return new OmnisharpLspPosition(position); - } + internal static ILspFilePosition ToLspPosition(this Position position) => new OmnisharpLspPosition(position); - internal static ILspFileRange ToLspRange(this Range range) - { - return new OmnisharpLspRange(range); - } + internal static ILspFileRange ToLspRange(this Range range) => new OmnisharpLspRange(range); - internal static Position ToOmnisharpPosition(this ILspFilePosition position) - { - return new Position(position.Line, position.Character); - } + internal static Position ToOmnisharpPosition(this ILspFilePosition position) => new(position.Line, position.Character); - internal static Range ToOmnisharpRange(this ILspFileRange range) - { - return new Range(range.Start.ToOmnisharpPosition(), range.End.ToOmnisharpPosition()); - } + internal static Range ToOmnisharpRange(this ILspFileRange range) => new(range.Start.ToOmnisharpPosition(), range.End.ToOmnisharpPosition()); - internal static BufferPosition ToBufferPosition(this IFilePosition position) - { - return new BufferPosition(position.Line, position.Column); - } + internal static BufferPosition ToBufferPosition(this IFilePosition position) => new(position.Line, position.Column); - internal static BufferRange ToBufferRange(this IFileRange range) - { - return new BufferRange(range.Start.ToBufferPosition(), range.End.ToBufferPosition()); - } + internal static BufferRange ToBufferRange(this IFileRange range) => new(range.Start.ToBufferPosition(), range.End.ToBufferPosition()); } } diff --git a/src/PowerShellEditorServices/Extensions/EditorObject.cs b/src/PowerShellEditorServices/Extensions/EditorObject.cs index 68747ac27..64585a139 100644 --- a/src/PowerShellEditorServices/Extensions/EditorObject.cs +++ b/src/PowerShellEditorServices/Extensions/EditorObject.cs @@ -20,10 +20,7 @@ public static class EditorObjectExtensions /// /// The editor object ($psEditor). /// The extension services provider. - public static EditorExtensionServiceProvider GetExtensionServiceProvider(this EditorObject editorObject) - { - return editorObject.Api; - } + public static EditorExtensionServiceProvider GetExtensionServiceProvider(this EditorObject editorObject) => editorObject.Api; } /// @@ -32,7 +29,7 @@ public static EditorExtensionServiceProvider GetExtensionServiceProvider(this Ed /// public class EditorObject { - private static readonly TaskCompletionSource s_editorObjectReady = new TaskCompletionSource(); + private static readonly TaskCompletionSource s_editorObjectReady = new(); /// /// A reference to the editor object instance. Only valid when completes. @@ -59,10 +56,7 @@ public class EditorObject /// /// Gets the version of PowerShell Editor Services. /// - public Version EditorServicesVersion - { - get { return this.GetType().GetTypeInfo().Assembly.GetName().Version; } - } + public Version EditorServicesVersion => GetType().GetTypeInfo().Assembly.GetName().Version; /// /// Gets the workspace interface for the editor API. @@ -86,12 +80,12 @@ internal EditorObject( ExtensionService extensionService, IEditorOperations editorOperations) { - this._extensionService = extensionService; - this._editorOperations = editorOperations; + _extensionService = extensionService; + _editorOperations = editorOperations; // Create API area objects - this.Workspace = new EditorWorkspace(this._editorOperations); - this.Window = new EditorWindow(this._editorOperations); + Workspace = new EditorWorkspace(_editorOperations); + Window = new EditorWindow(_editorOperations); // Create this lazily so that dependency injection does not have a circular call dependency _apiLazy = new Lazy(() => new EditorExtensionServiceProvider(serviceProvider)); @@ -102,37 +96,25 @@ internal EditorObject( /// /// The EditorCommand to be registered. /// True if the command is newly registered, false if the command already exists. - public bool RegisterCommand(EditorCommand editorCommand) - { - return this._extensionService.RegisterCommand(editorCommand); - } + public bool RegisterCommand(EditorCommand editorCommand) => _extensionService.RegisterCommand(editorCommand); /// /// Unregisters an existing EditorCommand based on its registered name. /// /// The name of the command to be unregistered. - public void UnregisterCommand(string commandName) - { - this._extensionService.UnregisterCommand(commandName); - } + public void UnregisterCommand(string commandName) => _extensionService.UnregisterCommand(commandName); /// /// Returns all registered EditorCommands. /// /// An Array of all registered EditorCommands. - public EditorCommand[] GetCommands() - { - return this._extensionService.GetCommands(); - } + public EditorCommand[] GetCommands() => _extensionService.GetCommands(); /// /// Gets the EditorContext which contains the state of the editor /// at the time this method is invoked. /// /// A instance of the EditorContext class. - public EditorContext GetEditorContext() - { - return this._editorOperations.GetEditorContextAsync().Result; - } + public EditorContext GetEditorContext() => _editorOperations.GetEditorContextAsync().Result; internal void SetAsStaticInstance() { diff --git a/src/PowerShellEditorServices/Extensions/EditorRequests.cs b/src/PowerShellEditorServices/Extensions/EditorRequests.cs index bd7e23624..47cc691e5 100644 --- a/src/PowerShellEditorServices/Extensions/EditorRequests.cs +++ b/src/PowerShellEditorServices/Extensions/EditorRequests.cs @@ -24,7 +24,7 @@ internal class ExtensionCommandRemovedNotification internal class GetEditorContextRequest - {} + { } internal enum EditorCommandResponse { diff --git a/src/PowerShellEditorServices/Extensions/EditorTerminal.cs b/src/PowerShellEditorServices/Extensions/EditorTerminal.cs index 073e0253d..b3c1c319c 100644 --- a/src/PowerShellEditorServices/Extensions/EditorTerminal.cs +++ b/src/PowerShellEditorServices/Extensions/EditorTerminal.cs @@ -21,10 +21,7 @@ public class EditorTerminal /// Creates a new instance of the EditorTerminal class. /// /// An IEditorOperations implementation which handles operations in the host editor. - internal EditorTerminal(IEditorOperations editorOperations) - { - this.editorOperations = editorOperations; - } + internal EditorTerminal(IEditorOperations editorOperations) => this.editorOperations = editorOperations; #endregion @@ -33,10 +30,7 @@ internal EditorTerminal(IEditorOperations editorOperations) /// /// Triggers to the editor to clear the terminal. /// - public void Clear() - { - this.editorOperations.ClearTerminal(); - } + public void Clear() => editorOperations.ClearTerminal(); #endregion } diff --git a/src/PowerShellEditorServices/Extensions/EditorWindow.cs b/src/PowerShellEditorServices/Extensions/EditorWindow.cs index 00fd3ab9f..072b76f99 100644 --- a/src/PowerShellEditorServices/Extensions/EditorWindow.cs +++ b/src/PowerShellEditorServices/Extensions/EditorWindow.cs @@ -33,7 +33,7 @@ public sealed class EditorWindow internal EditorWindow(IEditorOperations editorOperations) { this.editorOperations = editorOperations; - this.Terminal = new EditorTerminal(editorOperations); + Terminal = new EditorTerminal(editorOperations); } #endregion @@ -44,47 +44,32 @@ internal EditorWindow(IEditorOperations editorOperations) /// Shows an informational message to the user. /// /// The message to be shown. - public void ShowInformationMessage(string message) - { - this.editorOperations.ShowInformationMessageAsync(message).Wait(); - } + public void ShowInformationMessage(string message) => editorOperations.ShowInformationMessageAsync(message).Wait(); /// /// Shows an error message to the user. /// /// The message to be shown. - public void ShowErrorMessage(string message) - { - this.editorOperations.ShowErrorMessageAsync(message).Wait(); - } + public void ShowErrorMessage(string message) => editorOperations.ShowErrorMessageAsync(message).Wait(); /// /// Shows a warning message to the user. /// /// The message to be shown. - public void ShowWarningMessage(string message) - { - this.editorOperations.ShowWarningMessageAsync(message).Wait(); - } + public void ShowWarningMessage(string message) => editorOperations.ShowWarningMessageAsync(message).Wait(); /// /// Sets the status bar message in the editor UI (if applicable). /// /// The message to be shown. - public void SetStatusBarMessage(string message) - { - this.editorOperations.SetStatusBarMessageAsync(message, null).Wait(); - } + public void SetStatusBarMessage(string message) => editorOperations.SetStatusBarMessageAsync(message, null).Wait(); /// /// Sets the status bar message in the editor UI (if applicable). /// /// The message to be shown. /// A timeout in milliseconds for how long the message should remain visible. - public void SetStatusBarMessage(string message, int timeout) - { - this.editorOperations.SetStatusBarMessageAsync(message, timeout).Wait(); - } + public void SetStatusBarMessage(string message, int timeout) => editorOperations.SetStatusBarMessageAsync(message, timeout).Wait(); #endregion } diff --git a/src/PowerShellEditorServices/Extensions/EditorWorkspace.cs b/src/PowerShellEditorServices/Extensions/EditorWorkspace.cs index 6a5c07bc2..1a471b034 100644 --- a/src/PowerShellEditorServices/Extensions/EditorWorkspace.cs +++ b/src/PowerShellEditorServices/Extensions/EditorWorkspace.cs @@ -11,7 +11,7 @@ public sealed class EditorWorkspace { #region Private Fields - private IEditorOperations editorOperations; + private readonly IEditorOperations editorOperations; #endregion @@ -20,19 +20,13 @@ public sealed class EditorWorkspace /// /// Gets the current workspace path if there is one or null otherwise. /// - public string Path - { - get { return this.editorOperations.GetWorkspacePath(); } - } + public string Path => editorOperations.GetWorkspacePath(); #endregion #region Constructors - internal EditorWorkspace(IEditorOperations editorOperations) - { - this.editorOperations = editorOperations; - } + internal EditorWorkspace(IEditorOperations editorOperations) => this.editorOperations = editorOperations; #endregion @@ -41,20 +35,14 @@ internal EditorWorkspace(IEditorOperations editorOperations) /// /// Creates a new file in the editor /// - public void NewFile() - { - this.editorOperations.NewFileAsync().Wait(); - } + public void NewFile() => editorOperations.NewFileAsync().Wait(); /// /// Opens a file in the workspace. If the file is already open /// its buffer will be made active. /// /// The path to the file to be opened. - public void OpenFile(string filePath) - { - this.editorOperations.OpenFileAsync(filePath).Wait(); - } + public void OpenFile(string filePath) => editorOperations.OpenFileAsync(filePath).Wait(); /// /// Opens a file in the workspace. If the file is already open @@ -63,10 +51,7 @@ public void OpenFile(string filePath) /// /// The path to the file to be opened. /// Determines wether the file is opened as a preview or as a durable editor. - public void OpenFile(string filePath, bool preview) - { - this.editorOperations.OpenFileAsync(filePath, preview).Wait(); - } + public void OpenFile(string filePath, bool preview) => editorOperations.OpenFileAsync(filePath, preview).Wait(); #endregion } diff --git a/src/PowerShellEditorServices/Extensions/FileContext.cs b/src/PowerShellEditorServices/Extensions/FileContext.cs index f5c48e784..ecf78e14f 100644 --- a/src/PowerShellEditorServices/Extensions/FileContext.cs +++ b/src/PowerShellEditorServices/Extensions/FileContext.cs @@ -27,13 +27,13 @@ public sealed class FileContext /// /// Gets the parsed abstract syntax tree for the file. /// - public Ast Ast => this.scriptFile.ScriptAst; + public Ast Ast => scriptFile.ScriptAst; /// /// Gets a BufferRange which represents the entire content /// range of the file. /// - public IFileRange FileRange => new BufferFileRange(this.scriptFile.FileRange); + public IFileRange FileRange => new BufferFileRange(scriptFile.FileRange); /// /// Gets the language of the file. @@ -43,7 +43,7 @@ public sealed class FileContext /// /// Gets the filesystem path of the file. /// - public string Path => this.scriptFile.FilePath; + public string Path => scriptFile.FilePath; /// /// Gets the URI of the file. @@ -53,20 +53,13 @@ public sealed class FileContext /// /// Gets the parsed token list for the file. /// - public IReadOnlyList Tokens => this.scriptFile.ScriptTokens; + public IReadOnlyList Tokens => scriptFile.ScriptTokens; /// /// Gets the workspace-relative path of the file. /// - public string WorkspacePath - { - get - { - return - this.editorOperations.GetWorkspaceRelativePath( - this.scriptFile.FilePath); - } - } + public string WorkspacePath => editorOperations.GetWorkspaceRelativePath( + scriptFile.FilePath); #endregion @@ -93,8 +86,8 @@ internal FileContext( this.scriptFile = scriptFile; this.editorContext = editorContext; this.editorOperations = editorOperations; - this.Language = language; - this.Uri = scriptFile.DocumentUri.ToUri(); + Language = language; + Uri = scriptFile.DocumentUri.ToUri(); } #endregion @@ -105,10 +98,7 @@ internal FileContext( /// Gets the complete file content as a string. /// /// A string containing the complete file content. - public string GetText() - { - return this.scriptFile.Contents; - } + public string GetText() => scriptFile.Contents; /// /// Gets the file content in the specified range as a string. @@ -120,27 +110,21 @@ public string GetText(FileRange bufferRange) return string.Join( Environment.NewLine, - this.GetTextLines(bufferRange)); + GetTextLines(bufferRange)); } /// /// Gets the complete file content as an array of strings. /// /// An array of strings, each representing a line in the file. - public string[] GetTextLines() - { - return this.scriptFile.FileLines.ToArray(); - } + public string[] GetTextLines() => scriptFile.FileLines.ToArray(); /// /// Gets the file content in the specified range as an array of strings. /// /// The buffer range for which content will be extracted. /// An array of strings, each representing a line in the file within the specified range. - public string[] GetTextLines(FileRange fileRange) - { - return this.scriptFile.GetLinesInRange(fileRange.ToBufferRange()); - } + public string[] GetTextLines(FileRange fileRange) => scriptFile.GetLinesInRange(fileRange.ToBufferRange()); #endregion @@ -154,17 +138,17 @@ public string[] GetTextLines(FileRange fileRange) public void InsertText(string textToInsert) { // Is there a selection? - if (this.editorContext.SelectedRange.HasRange()) + if (editorContext.SelectedRange.HasRange()) { - this.InsertText( + InsertText( textToInsert, - this.editorContext.SelectedRange); + editorContext.SelectedRange); } else { - this.InsertText( + InsertText( textToInsert, - this.editorContext.CursorPosition); + editorContext.CursorPosition); } } @@ -175,7 +159,7 @@ public void InsertText(string textToInsert) /// The position at which the text will be inserted. public void InsertText(string textToInsert, IFilePosition insertPosition) { - this.InsertText( + InsertText( textToInsert, new FileRange(insertPosition, insertPosition)); } @@ -188,7 +172,7 @@ public void InsertText(string textToInsert, IFilePosition insertPosition) /// The 1-based column number at which the text will be inserted. public void InsertText(string textToInsert, int insertLine, int insertColumn) { - this.InsertText( + InsertText( textToInsert, new FilePosition(insertLine, insertColumn)); } @@ -211,7 +195,7 @@ public void InsertText( int endLine, int endColumn) { - this.InsertText( + InsertText( textToInsert, new FileRange( new FilePosition(startLine, startColumn), @@ -227,8 +211,8 @@ public void InsertText( /// The buffer range which will be replaced by the string. public void InsertText(string textToInsert, IFileRange insertRange) { - this.editorOperations - .InsertTextAsync(this.scriptFile.DocumentUri.ToString(), textToInsert, insertRange.ToBufferRange()) + editorOperations + .InsertTextAsync(scriptFile.DocumentUri.ToString(), textToInsert, insertRange.ToBufferRange()) .Wait(); } @@ -239,10 +223,7 @@ public void InsertText(string textToInsert, IFileRange insertRange) /// /// Saves this file. /// - public void Save() - { - this.editorOperations.SaveFileAsync(this.scriptFile.FilePath); - } + public void Save() => editorOperations.SaveFileAsync(scriptFile.FilePath); /// /// Save this file under a new path and open a new editor window on that file. @@ -256,14 +237,14 @@ public void SaveAs(string newFilePath) // Do some validation here so that we can provide a helpful error if the path won't work string absolutePath = System.IO.Path.IsPathRooted(newFilePath) ? newFilePath : - System.IO.Path.GetFullPath(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.scriptFile.FilePath), newFilePath)); + System.IO.Path.GetFullPath(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(scriptFile.FilePath), newFilePath)); if (File.Exists(absolutePath)) { - throw new IOException(String.Format("The file '{0}' already exists", absolutePath)); + throw new IOException(string.Format("The file '{0}' already exists", absolutePath)); } - this.editorOperations.SaveFileAsync(this.scriptFile.FilePath, newFilePath); + editorOperations.SaveFileAsync(scriptFile.FilePath, newFilePath); } #endregion diff --git a/src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs b/src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs index 59e87b4be..2d21c0bda 100644 --- a/src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs +++ b/src/PowerShellEditorServices/Hosting/EditorServicesServerFactory.cs @@ -93,10 +93,7 @@ private EditorServicesServerFactory(ILoggerFactory loggerFactory, LogLevel minim public PsesLanguageServer CreateLanguageServer( Stream inputStream, Stream outputStream, - HostStartupInfo hostStartupInfo) - { - return new PsesLanguageServer(_loggerFactory, inputStream, outputStream, hostStartupInfo); - } + HostStartupInfo hostStartupInfo) => new(_loggerFactory, inputStream, outputStream, hostStartupInfo); /// /// Create the debug server given a language server instance. @@ -158,7 +155,7 @@ public PsesDebugServer CreateDebugServerForTempSession( Stream outputStream, HostStartupInfo hostStartupInfo) { - var serviceProvider = new ServiceCollection() + ServiceProvider serviceProvider = new ServiceCollection() .AddLogging(builder => builder .ClearProviders() .AddSerilog() @@ -189,7 +186,7 @@ public PsesDebugServer CreateDebugServerForTempSession( /// 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 + /// this class should call in a finalizer. This /// could potentially even be done with by passing dispose=true. /// diff --git a/src/PowerShellEditorServices/Hosting/HostStartupInfo.cs b/src/PowerShellEditorServices/Hosting/HostStartupInfo.cs index ed6fb3e11..ccf5c7c9a 100644 --- a/src/PowerShellEditorServices/Hosting/HostStartupInfo.cs +++ b/src/PowerShellEditorServices/Hosting/HostStartupInfo.cs @@ -36,7 +36,7 @@ public sealed class HostStartupInfo /// no version is specified by the host application, we use 0.0.0 /// to indicate a lack of version. /// - private static readonly Version s_defaultHostVersion = new Version(0, 0, 0); + private static readonly Version s_defaultHostVersion = new(0, 0, 0); #endregion diff --git a/src/PowerShellEditorServices/Logging/HostLoggerAdapter.cs b/src/PowerShellEditorServices/Logging/HostLoggerAdapter.cs index 41026a5f1..3290b2b78 100644 --- a/src/PowerShellEditorServices/Logging/HostLoggerAdapter.cs +++ b/src/PowerShellEditorServices/Logging/HostLoggerAdapter.cs @@ -17,24 +17,15 @@ internal class HostLoggerAdapter : IObserver<(int logLevel, string message)> /// Create a new host logger adapter. /// /// Factory to create logger instances with. - public HostLoggerAdapter(ILoggerFactory loggerFactory) - { - _logger = loggerFactory.CreateLogger("HostLogs"); - } + public HostLoggerAdapter(ILoggerFactory loggerFactory) => _logger = loggerFactory.CreateLogger("HostLogs"); public void OnCompleted() { // Nothing to do; we simply don't send more log messages } - public void OnError(Exception error) - { - _logger.LogError(error, "Error in host logger"); - } + public void OnError(Exception error) => _logger.LogError(error, "Error in host logger"); - public void OnNext((int logLevel, string message) value) - { - _logger.Log((LogLevel)value.logLevel, value.message); - } + public void OnNext((int logLevel, string message) value) => _logger.Log((LogLevel)value.logLevel, value.message); } } diff --git a/src/PowerShellEditorServices/Logging/LoggerExtensions.cs b/src/PowerShellEditorServices/Logging/LoggerExtensions.cs index d0098e9ca..a580c7802 100644 --- a/src/PowerShellEditorServices/Logging/LoggerExtensions.cs +++ b/src/PowerShellEditorServices/Logging/LoggerExtensions.cs @@ -15,10 +15,7 @@ public static void LogException( Exception exception, [CallerMemberName] string callerName = null, [CallerFilePath] string callerSourceFile = null, - [CallerLineNumber] int callerLineNumber = -1) - { - logger.LogError(message, exception); - } + [CallerLineNumber] int callerLineNumber = -1) => logger.LogError(message, exception); public static void LogHandledException( this ILogger logger, @@ -26,9 +23,6 @@ public static void LogHandledException( Exception exception, [CallerMemberName] string callerName = null, [CallerFilePath] string callerSourceFile = null, - [CallerLineNumber] int callerLineNumber = -1) - { - logger.LogWarning(message, exception); - } + [CallerLineNumber] int callerLineNumber = -1) => logger.LogWarning(message, exception); } } diff --git a/src/PowerShellEditorServices/Logging/PsesTelemetryEvent.cs b/src/PowerShellEditorServices/Logging/PsesTelemetryEvent.cs index d8c2a1d2a..079b8b43f 100644 --- a/src/PowerShellEditorServices/Logging/PsesTelemetryEvent.cs +++ b/src/PowerShellEditorServices/Logging/PsesTelemetryEvent.cs @@ -14,26 +14,14 @@ internal class PsesTelemetryEvent : Dictionary { public string EventName { - get - { - return this["EventName"].ToString() ?? "PsesEvent"; - } - set - { - this["EventName"] = value; - } + get => this["EventName"].ToString() ?? "PsesEvent"; + set => this["EventName"] = value; } public JObject Data { - get - { - return this["Data"] as JObject ?? new JObject(); - } - set - { - this["Data"] = value; - } + get => this["Data"] as JObject ?? new JObject(); + set => this["Data"] = value; } } } diff --git a/src/PowerShellEditorServices/Server/PsesDebugServer.cs b/src/PowerShellEditorServices/Server/PsesDebugServer.cs index 088812f7e..a5b7fe298 100644 --- a/src/PowerShellEditorServices/Server/PsesDebugServer.cs +++ b/src/PowerShellEditorServices/Server/PsesDebugServer.cs @@ -91,20 +91,22 @@ 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, request, cancellationToken) => + { // We need to make sure the host has been started - _startedPses = !(await _psesHost.TryStartAsync(new HostStartOptions(), CancellationToken.None).ConfigureAwait(false)); + _startedPses = !await _psesHost.TryStartAsync(new HostStartOptions(), CancellationToken.None).ConfigureAwait(false); // Ensure the debugger mode is set correctly - this is required for remote debugging to work _psesHost.DebugContext.EnableDebugMode(); - var breakpointService = server.GetService(); + BreakpointService breakpointService = server.GetService(); // Clear any existing breakpoints before proceeding await breakpointService.RemoveAllBreakpointsAsync().ConfigureAwait(false); }) // 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((server, request, response, cancellationToken) => + { response.SupportsConditionalBreakpoints = true; response.SupportsConfigurationDoneRequest = true; response.SupportsFunctionBreakpoints = true; @@ -146,10 +148,7 @@ public async Task WaitForShutdown() public event EventHandler SessionEnded; - internal void OnSessionEnded() - { - SessionEnded?.Invoke(this, null); - } + internal void OnSessionEnded() => SessionEnded?.Invoke(this, null); #endregion } diff --git a/src/PowerShellEditorServices/Server/PsesLanguageServer.cs b/src/PowerShellEditorServices/Server/PsesLanguageServer.cs index 8612d595f..63072e72d 100644 --- a/src/PowerShellEditorServices/Server/PsesLanguageServer.cs +++ b/src/PowerShellEditorServices/Server/PsesLanguageServer.cs @@ -125,7 +125,7 @@ public async Task StartAsync() _psesHost = serviceProvider.GetService(); - var workspaceService = serviceProvider.GetService(); + WorkspaceService workspaceService = serviceProvider.GetService(); // Grab the workspace path from the parameters if (request.RootUri != null) @@ -136,7 +136,7 @@ public async Task StartAsync() { // If RootUri isn't set, try to use the first WorkspaceFolder. // TODO: Support multi-workspace. - foreach (var workspaceFolder in request.WorkspaceFolders) + foreach (OmniSharp.Extensions.LanguageServer.Protocol.Models.WorkspaceFolder workspaceFolder in request.WorkspaceFolders) { workspaceService.WorkspacePath = workspaceFolder.Uri.GetFileSystemPath(); break; diff --git a/src/PowerShellEditorServices/Server/PsesServiceCollectionExtensions.cs b/src/PowerShellEditorServices/Server/PsesServiceCollectionExtensions.cs index 74d454a2d..2284b9444 100644 --- a/src/PowerShellEditorServices/Server/PsesServiceCollectionExtensions.cs +++ b/src/PowerShellEditorServices/Server/PsesServiceCollectionExtensions.cs @@ -22,7 +22,7 @@ public static IServiceCollection AddPsesLanguageServices( HostStartupInfo hostStartupInfo) { return collection - .AddSingleton(hostStartupInfo) + .AddSingleton(hostStartupInfo) .AddSingleton() .AddSingleton() .AddSingleton() @@ -36,9 +36,9 @@ public static IServiceCollection AddPsesLanguageServices( .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton((provider) => + .AddSingleton((provider) => { - var extensionService = new ExtensionService( + ExtensionService extensionService = new( provider.GetService(), provider, provider.GetService(), @@ -64,13 +64,13 @@ public static IServiceCollection AddPsesDebugServices( PsesInternalHost internalHost = languageServiceProvider.GetService(); return collection - .AddSingleton(internalHost) + .AddSingleton(internalHost) .AddSingleton(internalHost) .AddSingleton(internalHost.DebugContext) .AddSingleton(languageServiceProvider.GetService()) .AddSingleton(languageServiceProvider.GetService()) .AddSingleton(languageServiceProvider.GetService()) - .AddSingleton(psesDebugServer) + .AddSingleton(psesDebugServer) .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/src/PowerShellEditorServices/Services/Analysis/AnalysisService.cs b/src/PowerShellEditorServices/Services/Analysis/AnalysisService.cs index 36f8f5181..a0d2f77fc 100644 --- a/src/PowerShellEditorServices/Services/Analysis/AnalysisService.cs +++ b/src/PowerShellEditorServices/Services/Analysis/AnalysisService.cs @@ -37,22 +37,22 @@ internal static string GetUniqueIdFromDiagnostic(Diagnostic diagnostic) Position start = diagnostic.Range.Start; Position end = diagnostic.Range.End; - var sb = new StringBuilder(256) + StringBuilder sb = new StringBuilder(256) .Append(diagnostic.Source ?? "?") - .Append("_") + .Append('_') .Append(diagnostic.Code?.IsString ?? true ? diagnostic.Code?.String : diagnostic.Code?.Long.ToString()) - .Append("_") + .Append('_') .Append(diagnostic.Severity?.ToString() ?? "?") - .Append("_") + .Append('_') .Append(start.Line) - .Append(":") + .Append(':') .Append(start.Character) - .Append("-") + .Append('-') .Append(end.Line) - .Append(":") + .Append(':') .Append(end.Character); - var id = sb.ToString(); + string id = sb.ToString(); return id; } @@ -144,7 +144,7 @@ public void StartScriptDiagnostics( EnsureEngineSettingsCurrent(); // If there's an existing task, we want to cancel it here; - var cancellationSource = new CancellationTokenSource(); + CancellationTokenSource cancellationSource = new(); CancellationTokenSource oldTaskCancellation = Interlocked.Exchange(ref _diagnosticsCancellationTokenSource, cancellationSource); if (oldTaskCancellation != null) { @@ -164,7 +164,7 @@ public void StartScriptDiagnostics( return; } - var analysisTask = Task.Run(() => DelayThenInvokeDiagnosticsAsync(filesToAnalyze, _diagnosticsCancellationTokenSource.Token), _diagnosticsCancellationTokenSource.Token); + Task analysisTask = Task.Run(() => DelayThenInvokeDiagnosticsAsync(filesToAnalyze, _diagnosticsCancellationTokenSource.Token), _diagnosticsCancellationTokenSource.Token); // Ensure that any next corrections request will wait for this diagnostics publication foreach (ScriptFile file in filesToAnalyze) @@ -210,7 +210,7 @@ public async Task GetCommentHelpText(string functionText, string helpLoc if (analysisResults.Length == 0 || analysisResults[0]?.Correction?.Edits == null - || analysisResults[0].Correction.Edits.Count() == 0) + || analysisResults[0].Correction.Edits.Length == 0) { return null; } @@ -242,10 +242,7 @@ public async Task> GetMostRecentCo /// /// The file to clear markers in. /// A task that ends when all markers in the file have been cleared. - public void ClearMarkers(ScriptFile file) - { - PublishScriptDiagnostics(file, Array.Empty()); - } + public void ClearMarkers(ScriptFile file) => PublishScriptDiagnostics(file, Array.Empty()); /// /// Event subscription method to be run when PSES configuration has been updated. @@ -294,7 +291,7 @@ private void InitializeAnalysisEngineToCurrentSettings() private PssaCmdletAnalysisEngine InstantiateAnalysisEngine() { - var pssaCmdletEngineBuilder = new PssaCmdletAnalysisEngine.Builder(_loggerFactory); + PssaCmdletAnalysisEngine.Builder pssaCmdletEngineBuilder = new(_loggerFactory); // If there's a settings file use that if (TryFindSettingsFile(out string settingsFilePath)) @@ -393,7 +390,7 @@ private async Task DelayThenInvokeDiagnosticsAsync(ScriptFile[] filesToAnalyze, private void PublishScriptDiagnostics(ScriptFile scriptFile, IReadOnlyList markers) { - var diagnostics = new Diagnostic[markers.Count]; + Diagnostic[] diagnostics = new Diagnostic[markers.Count]; CorrectionTableEntry fileCorrections = _mostRecentCorrectionsByFile.GetOrAdd( scriptFile, @@ -423,11 +420,6 @@ private void PublishScriptDiagnostics(ScriptFile scriptFile, IReadOnlyList CreateFileCorrectionsEntry(string fileUri) - { - return new ConcurrentDictionary(); - } - private static Diagnostic GetDiagnosticFromMarker(ScriptFileMarker scriptFileMarker) { return new Diagnostic @@ -454,13 +446,14 @@ private static Diagnostic GetDiagnosticFromMarker(ScriptFileMarker scriptFileMar private static DiagnosticSeverity MapDiagnosticSeverity(ScriptFileMarkerLevel markerLevel) { - switch (markerLevel) + return markerLevel switch { - case ScriptFileMarkerLevel.Error: return DiagnosticSeverity.Error; - case ScriptFileMarkerLevel.Warning: return DiagnosticSeverity.Warning; - case ScriptFileMarkerLevel.Information: return DiagnosticSeverity.Information; - default: return DiagnosticSeverity.Error; + ScriptFileMarkerLevel.Error => DiagnosticSeverity.Error, + ScriptFileMarkerLevel.Warning => DiagnosticSeverity.Warning, + ScriptFileMarkerLevel.Information => DiagnosticSeverity.Information, + _ => DiagnosticSeverity.Error, }; + ; } private static Hashtable GetCommentHelpRuleSettings(string helpLocation, bool forBlockComment) @@ -500,11 +493,9 @@ protected virtual void Dispose(bool disposing) } // This code added to correctly implement the disposable pattern. - public void Dispose() - { + public void Dispose() => // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); - } #endregion /// @@ -516,10 +507,7 @@ public void Dispose() /// private class CorrectionTableEntry { - public static CorrectionTableEntry CreateForFile(ScriptFile file) - { - return new CorrectionTableEntry(); - } + public static CorrectionTableEntry CreateForFile(ScriptFile file) => new(); public CorrectionTableEntry() { diff --git a/src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs b/src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs index 4e868f7d3..dc416d49b 100644 --- a/src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs +++ b/src/PowerShellEditorServices/Services/Analysis/PssaCmdletAnalysisEngine.cs @@ -38,10 +38,7 @@ public class Builder /// Create a builder for PssaCmdletAnalysisEngine construction. /// /// The logger to use. - public Builder(ILoggerFactory loggerFactory) - { - _loggerFactory = loggerFactory; - } + public Builder(ILoggerFactory loggerFactory) => _loggerFactory = loggerFactory; /// /// Uses a settings file for PSSA rule configuration. @@ -136,20 +133,14 @@ private PssaCmdletAnalysisEngine( RunspacePool analysisRunspacePool, PSModuleInfo pssaModuleInfo, string[] rulesToInclude) - : this(logger, analysisRunspacePool, pssaModuleInfo) - { - _rulesToInclude = rulesToInclude; - } + : this(logger, analysisRunspacePool, pssaModuleInfo) => _rulesToInclude = rulesToInclude; private PssaCmdletAnalysisEngine( ILogger logger, RunspacePool analysisRunspacePool, PSModuleInfo pssaModuleInfo, object analysisSettingsParameter) - : this(logger, analysisRunspacePool, pssaModuleInfo) - { - _settingsParameter = analysisSettingsParameter; - } + : this(logger, analysisRunspacePool, pssaModuleInfo) => _settingsParameter = analysisSettingsParameter; private PssaCmdletAnalysisEngine( ILogger logger, @@ -178,7 +169,7 @@ public async Task FormatAsync(string scriptDefinition, Hashtable formatS return scriptDefinition; } - var psCommand = new PSCommand() + PSCommand psCommand = new PSCommand() .AddCommand("Invoke-Formatter") .AddParameter("ScriptDefinition", scriptDefinition) .AddParameter("Settings", formatSettings); @@ -198,7 +189,7 @@ public async Task FormatAsync(string scriptDefinition, Hashtable formatS if (result.HasErrors) { - var errorBuilder = new StringBuilder().Append(s_indentJoin); + StringBuilder errorBuilder = new StringBuilder().Append(s_indentJoin); foreach (ErrorRecord err in result.Errors) { errorBuilder.Append(err).Append(s_indentJoin); @@ -243,7 +234,7 @@ public Task AnalyzeScriptAsync(string scriptContent, Hashtab return Task.FromResult(Array.Empty()); } - var command = new PSCommand() + PSCommand command = new PSCommand() .AddCommand("Invoke-ScriptAnalyzer") .AddParameter("ScriptDefinition", scriptContent) .AddParameter("Severity", s_scriptMarkerLevels); @@ -261,20 +252,11 @@ public Task AnalyzeScriptAsync(string scriptContent, Hashtab return GetSemanticMarkersFromCommandAsync(command); } - public PssaCmdletAnalysisEngine RecreateWithNewSettings(string settingsPath) - { - return new PssaCmdletAnalysisEngine(_logger, _analysisRunspacePool, _pssaModuleInfo, settingsPath); - } + public PssaCmdletAnalysisEngine RecreateWithNewSettings(string settingsPath) => new(_logger, _analysisRunspacePool, _pssaModuleInfo, settingsPath); - public PssaCmdletAnalysisEngine RecreateWithNewSettings(Hashtable settingsHashtable) - { - return new PssaCmdletAnalysisEngine(_logger, _analysisRunspacePool, _pssaModuleInfo, settingsHashtable); - } + public PssaCmdletAnalysisEngine RecreateWithNewSettings(Hashtable settingsHashtable) => new(_logger, _analysisRunspacePool, _pssaModuleInfo, settingsHashtable); - public PssaCmdletAnalysisEngine RecreateWithRules(string[] rules) - { - return new PssaCmdletAnalysisEngine(_logger, _analysisRunspacePool, _pssaModuleInfo, rules); - } + public PssaCmdletAnalysisEngine RecreateWithRules(string[] rules) => new(_logger, _analysisRunspacePool, _pssaModuleInfo, rules); #region IDisposable Support private bool disposedValue = false; // To detect redundant calls @@ -293,11 +275,9 @@ protected virtual void Dispose(bool disposing) } // This code added to correctly implement the disposable pattern. - public void Dispose() - { + public void Dispose() => // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); - } #endregion @@ -306,9 +286,9 @@ private async Task GetSemanticMarkersFromCommandAsync(PSComm PowerShellResult result = await InvokePowerShellAsync(command).ConfigureAwait(false); IReadOnlyCollection diagnosticResults = result?.Output ?? s_emptyDiagnosticResult; - _logger.LogDebug(String.Format("Found {0} violations", diagnosticResults.Count)); + _logger.LogDebug(string.Format("Found {0} violations", diagnosticResults.Count)); - var scriptMarkers = new ScriptFileMarker[diagnosticResults.Count]; + ScriptFileMarker[] scriptMarkers = new ScriptFileMarker[diagnosticResults.Count]; int i = 0; foreach (PSObject diagnostic in diagnosticResults) { @@ -319,41 +299,36 @@ private async Task GetSemanticMarkersFromCommandAsync(PSComm return scriptMarkers; } - private Task InvokePowerShellAsync(PSCommand command) - { - return Task.Run(() => InvokePowerShell(command)); - } + private Task InvokePowerShellAsync(PSCommand command) => Task.Run(() => InvokePowerShell(command)); private PowerShellResult InvokePowerShell(PSCommand command) { - using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace)) + using System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace); + powerShell.RunspacePool = _analysisRunspacePool; + powerShell.Commands = command; + PowerShellResult result = null; + try { - powerShell.RunspacePool = _analysisRunspacePool; - powerShell.Commands = command; - PowerShellResult result = null; - try - { - Collection output = InvokePowerShellWithModulePathPreservation(powerShell); - PSDataCollection errors = powerShell.Streams.Error; - result = new PowerShellResult(output, errors, powerShell.HadErrors); - } - catch (CommandNotFoundException ex) - { - // This exception is possible if the module path loaded - // is wrong even though PSScriptAnalyzer is available as a module - _logger.LogError(ex.Message); - } - catch (CmdletInvocationException ex) - { - // We do not want to crash EditorServices for exceptions caused by cmdlet invocation. - // Two main reasons that cause the exception are: - // * PSCmdlet.WriteOutput being called from another thread than Begin/Process - // * CompositionContainer.ComposeParts complaining that "...Only one batch can be composed at a time" - _logger.LogError(ex.Message); - } - - return result; + Collection output = InvokePowerShellWithModulePathPreservation(powerShell); + PSDataCollection errors = powerShell.Streams.Error; + result = new PowerShellResult(output, errors, powerShell.HadErrors); + } + catch (CommandNotFoundException ex) + { + // This exception is possible if the module path loaded + // is wrong even though PSScriptAnalyzer is available as a module + _logger.LogError(ex.Message); } + catch (CmdletInvocationException ex) + { + // We do not want to crash EditorServices for exceptions caused by cmdlet invocation. + // Two main reasons that cause the exception are: + // * PSCmdlet.WriteOutput being called from another thread than Begin/Process + // * CompositionContainer.ComposeParts complaining that "...Only one batch can be composed at a time" + _logger.LogError(ex.Message); + } + + return result; } /// @@ -387,7 +362,7 @@ private void LogAvailablePssaFeatures() throw new FileNotFoundException("Unable to find loaded PSScriptAnalyzer module for logging"); } - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("PSScriptAnalyzer successfully imported:"); // Log version @@ -425,8 +400,8 @@ private IEnumerable GetPSScriptAnalyzerRules() return Enumerable.Empty(); } - var ruleNames = new List(getRuleResult.Output.Count); - foreach (var rule in getRuleResult.Output) + List ruleNames = new(getRuleResult.Output.Count); + foreach (PSObject rule in getRuleResult.Output) { ruleNames.Add((string)rule.Members["RuleName"].Value); } @@ -441,55 +416,53 @@ private IEnumerable GetPSScriptAnalyzerRules() /// A runspace pool with PSScriptAnalyzer loaded for running script analysis tasks. private static RunspacePool CreatePssaRunspacePool(out PSModuleInfo pssaModuleInfo) { - using (var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace)) - { - // Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"` - ps.AddCommand("Get-Module") - .AddParameter("ListAvailable") - .AddParameter("Name", PSSA_MODULE_NAME); + using System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace); + // Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"` + ps.AddCommand("Get-Module") + .AddParameter("ListAvailable") + .AddParameter("Name", PSSA_MODULE_NAME); - try - { - using (PSModulePathPreserver.Take()) - { - // Get the latest version of PSScriptAnalyzer we can find - pssaModuleInfo = ps.Invoke()? - .OrderByDescending(moduleInfo => moduleInfo.Version) - .FirstOrDefault(); - } - } - catch (Exception e) - { - throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path", e); - } - - if (pssaModuleInfo == null) + try + { + using (PSModulePathPreserver.Take()) { - throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path"); + // Get the latest version of PSScriptAnalyzer we can find + pssaModuleInfo = ps.Invoke()? + .OrderByDescending(moduleInfo => moduleInfo.Version) + .FirstOrDefault(); } + } + catch (Exception e) + { + throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path", e); + } - // Now that we know where the PSScriptAnalyzer we want to use is, create a base - // session state with PSScriptAnalyzer loaded - // - // We intentionally use `CreateDefault2()` as it loads `Microsoft.PowerShell.Core` - // only, which is a more minimal and therefore safer state. - InitialSessionState sessionState = InitialSessionState.CreateDefault2(); + if (pssaModuleInfo == null) + { + throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path"); + } - sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase }); + // Now that we know where the PSScriptAnalyzer we want to use is, create a base + // session state with PSScriptAnalyzer loaded + // + // We intentionally use `CreateDefault2()` as it loads `Microsoft.PowerShell.Core` + // only, which is a more minimal and therefore safer state. + InitialSessionState sessionState = InitialSessionState.CreateDefault2(); - RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(sessionState); + sessionState.ImportPSModule(new[] { pssaModuleInfo.ModuleBase }); - runspacePool.SetMaxRunspaces(1); - runspacePool.ThreadOptions = PSThreadOptions.ReuseThread; + RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(sessionState); - // Open the runspace pool here so we can deterministically handle the PSModulePath change issue - using (PSModulePathPreserver.Take()) - { - runspacePool.Open(); - } + runspacePool.SetMaxRunspaces(1); + runspacePool.ThreadOptions = PSThreadOptions.ReuseThread; - return runspacePool; + // Open the runspace pool here so we can deterministically handle the PSModulePath change issue + using (PSModulePathPreserver.Take()) + { + runspacePool.Open(); } + + return runspacePool; } /// @@ -524,7 +497,7 @@ public PowerShellResult( /// private struct PSModulePathPreserver : IDisposable { - private static object s_psModulePathMutationLock = new object(); + private static readonly object s_psModulePathMutationLock = new(); public static PSModulePathPreserver Take() { @@ -534,10 +507,7 @@ public static PSModulePathPreserver Take() private readonly string _psModulePath; - private PSModulePathPreserver(string psModulePath) - { - _psModulePath = psModulePath; - } + private PSModulePathPreserver(string psModulePath) => _psModulePath = psModulePath; public void Dispose() { diff --git a/src/PowerShellEditorServices/Services/CodeLens/PesterCodeLensProvider.cs b/src/PowerShellEditorServices/Services/CodeLens/PesterCodeLensProvider.cs index dc6fc91e5..c37a1fa0a 100644 --- a/src/PowerShellEditorServices/Services/CodeLens/PesterCodeLensProvider.cs +++ b/src/PowerShellEditorServices/Services/CodeLens/PesterCodeLensProvider.cs @@ -46,7 +46,7 @@ public PesterCodeLensProvider(ConfigurationService configurationService) private static CodeLens[] GetPesterLens(PesterSymbolReference pesterSymbol, ScriptFile scriptFile) { string word = pesterSymbol.Command == PesterCommandType.It ? "test" : "tests"; - var codeLensResults = new CodeLens[] + CodeLens[] codeLensResults = new CodeLens[] { new CodeLens() { @@ -103,15 +103,15 @@ private static CodeLens[] GetPesterLens(PesterSymbolReference pesterSymbol, Scri public CodeLens[] ProvideCodeLenses(ScriptFile scriptFile) { // Don't return anything if codelens setting is disabled - if (!this._configurationService.CurrentSettings.Pester.CodeLens) + if (!_configurationService.CurrentSettings.Pester.CodeLens) { return Array.Empty(); } - var lenses = new List(); + List lenses = new(); foreach (SymbolReference symbol in _symbolProvider.ProvideDocumentSymbols(scriptFile)) { - if (!(symbol is PesterSymbolReference pesterSymbol)) + if (symbol is not PesterSymbolReference pesterSymbol) { continue; } @@ -134,11 +134,9 @@ public CodeLens[] ProvideCodeLenses(ScriptFile scriptFile) /// The code lens to resolve. /// The script file. /// The given CodeLens, wrapped in a task. - public Task ResolveCodeLens(CodeLens codeLens, ScriptFile scriptFile) - { + public Task ResolveCodeLens(CodeLens codeLens, ScriptFile scriptFile) => // This provider has no specific behavior for // resolving CodeLenses. - return Task.FromResult(codeLens); - } + Task.FromResult(codeLens); } } diff --git a/src/PowerShellEditorServices/Services/CodeLens/ReferencesCodeLensProvider.cs b/src/PowerShellEditorServices/Services/CodeLens/ReferencesCodeLensProvider.cs index e56dc1153..099591e5d 100644 --- a/src/PowerShellEditorServices/Services/CodeLens/ReferencesCodeLensProvider.cs +++ b/src/PowerShellEditorServices/Services/CodeLens/ReferencesCodeLensProvider.cs @@ -26,7 +26,7 @@ internal class ReferencesCodeLensProvider : ICodeLensProvider /// /// The document symbol provider to supply symbols to generate the code lenses. /// - private IDocumentSymbolProvider _symbolProvider; + private readonly IDocumentSymbolProvider _symbolProvider; private readonly SymbolsService _symbolsService; private readonly WorkspaceService _workspaceService; @@ -56,7 +56,7 @@ public ReferencesCodeLensProvider(WorkspaceService workspaceService, SymbolsServ /// An array of CodeLenses describing all functions in the given script file. public CodeLens[] ProvideCodeLenses(ScriptFile scriptFile) { - var acc = new List(); + List acc = new(); foreach (SymbolReference sym in _symbolProvider.ProvideDocumentSymbols(scriptFile)) { if (sym.SymbolType == SymbolType.Function) @@ -104,7 +104,7 @@ public async Task ResolveCodeLens(CodeLens codeLens, ScriptFile script } else { - var acc = new List(); + List acc = new(); foreach (SymbolReference foundReference in referencesResult) { if (IsReferenceDefinition(foundSymbol, foundReference)) @@ -183,7 +183,7 @@ private static string GetReferenceCountHeader(int referenceCount) return "1 reference"; } - var sb = new StringBuilder(14); // "100 references".Length = 14 + StringBuilder sb = new(14); // "100 references".Length = 14 sb.Append(referenceCount); sb.Append(" references"); return sb.ToString(); diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/BreakpointService.cs b/src/PowerShellEditorServices/Services/DebugAdapter/BreakpointService.cs index d978b67e5..3b7e75ec6 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/BreakpointService.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/BreakpointService.cs @@ -67,7 +67,7 @@ public async Task> SetBreakpointsAsync(string esc { BreakpointApiUtils.SetBreakpoint(_editorServicesHost.Runspace.Debugger, breakpointDetails, _debugStateService.RunspaceId); } - catch(InvalidOperationException e) + catch (InvalidOperationException e) { breakpointDetails.Message = e.Message; breakpointDetails.Verified = false; @@ -247,7 +247,7 @@ public async Task RemoveAllBreakpointsAsync(string scriptPath = null) } // Legacy behavior - var psCommand = new PSCommand().AddCommand(@"Microsoft.PowerShell.Utility\Get-PSBreakpoint"); + PSCommand psCommand = new PSCommand().AddCommand(@"Microsoft.PowerShell.Utility\Get-PSBreakpoint"); if (!string.IsNullOrEmpty(scriptPath)) { @@ -286,7 +286,7 @@ public async Task RemoveBreakpointsAsync(IEnumerable breakpoints) } // Legacy behavior - var breakpointIds = breakpoints.Select(b => b.Id); + IEnumerable breakpointIds = breakpoints.Select(b => b.Id); if (breakpointIds.Any()) { PSCommand psCommand = new PSCommand() diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/DebugEventHandlerService.cs b/src/PowerShellEditorServices/Services/DebugAdapter/DebugEventHandlerService.cs index 34c1f5624..69ddb1209 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/DebugEventHandlerService.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/DebugEventHandlerService.cs @@ -58,10 +58,7 @@ internal void UnregisterEventHandlers() #region Public methods - internal void TriggerDebuggerStopped(DebuggerStoppedEventArgs e) - { - OnDebuggerStopped(null, e); - } + internal void TriggerDebuggerStopped(DebuggerStoppedEventArgs e) => OnDebuggerStopped(null, e); #endregion @@ -147,11 +144,12 @@ private void OnBreakpointUpdated(object sender, BreakpointUpdatedEventArgs e) if (e.Breakpoint is LineBreakpoint) { - var breakpoint = LspDebugUtils.CreateBreakpoint( + OmniSharp.Extensions.DebugAdapter.Protocol.Models.Breakpoint breakpoint = LspDebugUtils.CreateBreakpoint( BreakpointDetails.Create(e.Breakpoint, e.UpdateType) ); - string reason = e.UpdateType switch { + string reason = e.UpdateType switch + { BreakpointUpdateType.Set => BreakpointEventReason.New, BreakpointUpdateType.Removed => BreakpointEventReason.Removed, BreakpointUpdateType.Enabled => BreakpointEventReason.Changed, diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs b/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs index 680f81be6..e14c0bf0f 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs @@ -194,53 +194,35 @@ public async Task SetCommandBreakpointsAsync( /// /// Sends a "continue" action to the debugger when stopped. /// - public void Continue() - { - _debugContext.Continue(); - } + public void Continue() => _debugContext.Continue(); /// /// Sends a "step over" action to the debugger when stopped. /// - public void StepOver() - { - _debugContext.StepOver(); - } + public void StepOver() => _debugContext.StepOver(); /// /// Sends a "step in" action to the debugger when stopped. /// - public void StepIn() - { - _debugContext.StepInto(); - } + public void StepIn() => _debugContext.StepInto(); /// /// Sends a "step out" action to the debugger when stopped. /// - public void StepOut() - { - _debugContext.StepOut(); - } + public void StepOut() => _debugContext.StepOut(); /// /// Causes the debugger to break execution wherever it currently /// is at the time. This is equivalent to clicking "Pause" in a /// debugger UI. /// - public void Break() - { - _debugContext.BreakExecution(); - } + public void Break() => _debugContext.BreakExecution(); /// /// Aborts execution of the debugger while it is running, even while /// it is stopped. Equivalent to calling PowerShellContext.AbortExecution. /// - public void Abort() - { - _debugContext.Abort(); - } + public void Abort() => _debugContext.Abort(); /// /// Gets the list of variables that are children of the scope or variable @@ -264,7 +246,7 @@ public VariableDetailsBase[] GetVariables(int variableReferenceId) if (parentVariable.IsExpandable) { childVariables = parentVariable.GetChildren(_logger); - foreach (var child in childVariables) + foreach (VariableDetailsBase child in childVariables) { // Only add child if it hasn't already been added. if (child.Id < 0) @@ -318,7 +300,7 @@ public VariableDetailsBase GetVariableFromExpression(string variableExpression) debugInfoHandle.Release(); } - foreach (var variableName in variablePathParts) + foreach (string variableName in variablePathParts) { if (variableList is null) { @@ -422,7 +404,7 @@ public async Task SetVariableAsync(int variableContainerReferenceId, str } // Now that we have the scope, get the associated PSVariable object for the variable to be set. - var getVariableCommand = new PSCommand() + PSCommand getVariableCommand = new PSCommand() .AddCommand(@"Microsoft.PowerShell.Utility\Get-Variable") .AddParameter("Name", name.TrimStart('$')) .AddParameter("Scope", scope); @@ -486,7 +468,7 @@ public async Task SetVariableAsync(int variableContainerReferenceId, str // Use the VariableDetails.ValueString functionality to get the string representation for client debugger. // This makes the returned string consistent with the strings normally displayed for variables in the debugger. - var tempVariable = new VariableDetails(psVariable); + VariableDetails tempVariable = new(psVariable); _logger.LogTrace($"Set variable '{name}' to: {tempVariable.ValueString ?? ""}"); return tempVariable.ValueString; } @@ -505,7 +487,7 @@ public async Task EvaluateExpressionAsync( string expressionString, bool writeResultAsOutput) { - var command = new PSCommand().AddScript(expressionString); + PSCommand command = new PSCommand().AddScript(expressionString); IReadOnlyList results = await _executionService.ExecutePSCommandAsync( command, CancellationToken.None, @@ -594,7 +576,7 @@ internal async Task GetStackFramesAsync(CancellationToken c /// The list of VariableScope instances which describe the available variable scopes. public VariableScope[] GetVariableScopes(int stackFrameId) { - var stackFrames = GetStackFrames(); + StackFrameDetails[] stackFrames = GetStackFrames(); int autoVariablesId = stackFrames[stackFrameId].AutoVariables.Id; int commandVariablesId = stackFrames[stackFrameId].CommandVariables.Id; @@ -638,16 +620,13 @@ private async Task FetchStackFramesAndVariablesAsync(string scriptNameOverride) } } - private Task FetchVariableContainerAsync(string scope) - { - return FetchVariableContainerAsync(scope, autoVarsOnly: false); - } + private Task FetchVariableContainerAsync(string scope) => FetchVariableContainerAsync(scope, autoVarsOnly: false); private async Task FetchVariableContainerAsync(string scope, bool autoVarsOnly) { PSCommand psCommand = new PSCommand().AddCommand(@"Microsoft.PowerShell.Utility\Get-Variable").AddParameter("Scope", scope); - var scopeVariableContainer = new VariableContainerDetails(nextVariableId++, "Scope: " + scope); + VariableContainerDetails scopeVariableContainer = new(nextVariableId++, "Scope: " + scope); variables.Add(scopeVariableContainer); IReadOnlyList results; @@ -675,7 +654,7 @@ private async Task FetchVariableContainerAsync(string { continue; } - var variableInfo = TryVariableInfo(psVariableObject); + VariableInfo variableInfo = TryVariableInfo(psVariableObject); if (variableInfo is null || !ShouldAddAsVariable(variableInfo)) { continue; @@ -685,7 +664,7 @@ private async Task FetchVariableContainerAsync(string continue; } - var variableDetails = new VariableDetails(variableInfo.Variable) { Id = nextVariableId++ }; + VariableDetails variableDetails = new(variableInfo.Variable) { Id = nextVariableId++ }; variables.Add(variableDetails); scopeVariableContainer.Children.Add(variableDetails.Name, variableDetails); } @@ -748,7 +727,7 @@ private static bool ShouldAddAsVariable(VariableInfo variableInfo) // provided as a convenience. private bool ShouldAddToAutoVariables(VariableInfo variableInfo) { - var variableToAdd = variableInfo.Variable; + PSVariable variableToAdd = variableInfo.Variable; if (!ShouldAddAsVariable(variableInfo)) { return false; @@ -807,31 +786,31 @@ private async Task FetchStackFramesAsync(string scriptNameOverride) // PSObject is used here instead of the specific type because we get deserialized // objects from remote sessions and want a common interface. - var psCommand = new PSCommand().AddScript($"[Collections.ArrayList]{callStackVarName} = @(); {getPSCallStack}; {returnSerializedIfOnRemoteMachine}"); + PSCommand psCommand = new PSCommand().AddScript($"[Collections.ArrayList]{callStackVarName} = @(); {getPSCallStack}; {returnSerializedIfOnRemoteMachine}"); 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 : results; - var stackFrameDetailList = new List(); + List stackFrameDetailList = new(); bool isTopStackFrame = true; - foreach (var callStackFrameItem in callStack) + foreach (object callStackFrameItem in callStack) { // We have to use reflection to get the variable dictionary. - var callStackFrameComponents = (callStackFrameItem as PSObject).BaseObject as IList; - var callStackFrame = callStackFrameComponents[0] as PSObject; + 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 IDictionary; - var autoVariables = new VariableContainerDetails( + VariableContainerDetails autoVariables = new( nextVariableId++, VariableContainerDetails.AutoVariablesName); variables.Add(autoVariables); - var commandVariables = new VariableContainerDetails( + VariableContainerDetails commandVariables = new( nextVariableId++, VariableContainerDetails.CommandVariablesName); @@ -846,7 +825,7 @@ private async Task FetchStackFramesAsync(string scriptNameOverride) continue; } - var variableDetails = new VariableDetails(psVarInfo.Variable) { Id = nextVariableId++ }; + VariableDetails variableDetails = new(psVarInfo.Variable) { Id = nextVariableId++ }; variables.Add(variableDetails); commandVariables.Children.Add(variableDetails.Name, variableDetails); @@ -865,7 +844,7 @@ private async Task FetchStackFramesAsync(string scriptNameOverride) // we'd need a way to detect things such as module borders and dot-sourced files. if (isTopStackFrame) { - var localScopeAutoVariables = await FetchVariableContainerAsync(VariableContainerDetails.LocalScopeName, autoVarsOnly: true).ConfigureAwait(false); + VariableContainerDetails localScopeAutoVariables = await FetchVariableContainerAsync(VariableContainerDetails.LocalScopeName, autoVarsOnly: true).ConfigureAwait(false); foreach (KeyValuePair entry in localScopeAutoVariables.Children) { // NOTE: `TryAdd` doesn't work on `IDictionary`. @@ -877,7 +856,7 @@ private async Task FetchStackFramesAsync(string scriptNameOverride) isTopStackFrame = false; } - var stackFrameDetailsEntry = StackFrameDetails.Create(callStackFrame, autoVariables, commandVariables); + StackFrameDetails stackFrameDetailsEntry = StackFrameDetails.Create(callStackFrame, autoVariables, commandVariables); string stackFrameScriptPath = stackFrameDetailsEntry.ScriptPath; if (scriptNameOverride is not null @@ -1008,10 +987,7 @@ await _remoteFileManager.FetchRemoteFileAsync( DebuggerStopped?.Invoke(sender, CurrentDebuggerStoppedEventArgs); } - private void OnDebuggerResuming(object sender, DebuggerResumingEventArgs debuggerResumingEventArgs) - { - CurrentDebuggerStoppedEventArgs = null; - } + private void OnDebuggerResuming(object sender, DebuggerResumingEventArgs debuggerResumingEventArgs) => CurrentDebuggerStoppedEventArgs = null; /// /// Raised when a breakpoint is added/removed/updated in the debugger. diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointApiUtils.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointApiUtils.cs index f05a96358..c7ea90e45 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointApiUtils.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointApiUtils.cs @@ -154,15 +154,9 @@ public static Breakpoint SetBreakpoint(Debugger debugger, BreakpointDetailsBase }; } - public static List GetBreakpoints(Debugger debugger, int? runspaceId = null) - { - return GetBreakpointsDelegate(debugger, runspaceId); - } + public static List GetBreakpoints(Debugger debugger, int? runspaceId = null) => GetBreakpointsDelegate(debugger, runspaceId); - public static bool RemoveBreakpoint(Debugger debugger, Breakpoint breakpoint, int? runspaceId = null) - { - return RemoveBreakpointDelegate(debugger, breakpoint, runspaceId); - } + public static bool RemoveBreakpoint(Debugger debugger, Breakpoint breakpoint, int? runspaceId = null) => RemoveBreakpointDelegate(debugger, breakpoint, runspaceId); /// /// Inspects the condition, putting in the appropriate scriptblock template @@ -183,7 +177,7 @@ public static ScriptBlock GetBreakpointActionScriptBlock(string condition, strin StringBuilder builder = new( string.IsNullOrEmpty(logMessage) ? "break" - : $"Microsoft.PowerShell.Utility\\Write-Host \"{logMessage.Replace("\"","`\"")}\""); + : $"Microsoft.PowerShell.Utility\\Write-Host \"{logMessage.Replace("\"", "`\"")}\""); // If HitCondition specified, parse and verify it. if (!string.IsNullOrWhiteSpace(hitCondition)) @@ -224,7 +218,7 @@ public static ScriptBlock GetBreakpointActionScriptBlock(string condition, strin // Check for "advanced" condition syntax i.e. if the user has specified // a "break" or "continue" statement anywhere in their scriptblock, // pass their scriptblock through to the Action parameter as-is. - if (parsed.Ast.Find(ast => ast is BreakStatementAst || ast is ContinueStatementAst, true) is not null) + if (parsed.Ast.Find(ast => ast is BreakStatementAst or ContinueStatementAst, true) is not null) { return parsed; } @@ -319,10 +313,7 @@ private static string ExtractAndScrubParseExceptionMessage(ParseException parseE return FormatInvalidBreakpointConditionMessage(condition, parseException.Message); } - private static string FormatInvalidBreakpointConditionMessage(string condition, string message) - { - return $"'{condition}' is not a valid PowerShell expression. {message}"; - } + private static string FormatInvalidBreakpointConditionMessage(string condition, string message) => $"'{condition}' is not a valid PowerShell expression. {message}"; #endregion } diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointDetails.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointDetails.cs index 4147babb1..6fa667462 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointDetails.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/BreakpointDetails.cs @@ -91,7 +91,7 @@ internal static BreakpointDetails Create( "Unexpected breakpoint type: " + breakpoint.GetType().Name); } - var breakpointDetails = new BreakpointDetails + BreakpointDetails breakpointDetails = new() { Id = breakpoint.Id, Verified = updateType != BreakpointUpdateType.Disabled, diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/CommandBreakpointDetails.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/CommandBreakpointDetails.cs index 796c05432..fdef14a15 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/CommandBreakpointDetails.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/CommandBreakpointDetails.cs @@ -36,7 +36,8 @@ internal static CommandBreakpointDetails Create( { Validate.IsNotNull(nameof(name), name); - return new CommandBreakpointDetails { + return new CommandBreakpointDetails + { Name = name, Condition = condition }; @@ -52,13 +53,14 @@ internal static CommandBreakpointDetails Create(Breakpoint breakpoint) { Validate.IsNotNull("breakpoint", breakpoint); - if (!(breakpoint is CommandBreakpoint commandBreakpoint)) + if (breakpoint is not CommandBreakpoint commandBreakpoint) { throw new ArgumentException( "Unexpected breakpoint type: " + breakpoint.GetType().Name); } - var breakpointDetails = new CommandBreakpointDetails { + CommandBreakpointDetails breakpointDetails = new() + { Verified = true, Name = commandBreakpoint.Command, Condition = commandBreakpoint.Action?.ToString() diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/DebuggerStoppedEventArgs.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/DebuggerStoppedEventArgs.cs index e6e1ebc87..fa83e5dba 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/DebuggerStoppedEventArgs.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/DebuggerStoppedEventArgs.cs @@ -25,10 +25,7 @@ internal class DebuggerStoppedEventArgs /// /// Returns true if the breakpoint was raised from a remote debugging session. /// - public bool IsRemoteSession - { - get => RunspaceInfo.RunspaceOrigin != RunspaceOrigin.Local; - } + public bool IsRemoteSession => RunspaceInfo.RunspaceOrigin != RunspaceOrigin.Local; /// /// Gets the original script path if 'IsRemoteSession' returns true. @@ -43,24 +40,12 @@ public bool IsRemoteSession /// /// Gets the line number at which the debugger stopped execution. /// - public int LineNumber - { - get - { - return this.OriginalEvent.InvocationInfo.ScriptLineNumber; - } - } + public int LineNumber => OriginalEvent.InvocationInfo.ScriptLineNumber; /// /// Gets the column number at which the debugger stopped execution. /// - public int ColumnNumber - { - get - { - return this.OriginalEvent.InvocationInfo.OffsetInLine; - } - } + public int ColumnNumber => OriginalEvent.InvocationInfo.OffsetInLine; /// /// Gets the original DebuggerStopEventArgs from the PowerShell engine. @@ -99,16 +84,16 @@ public DebuggerStoppedEventArgs( if (!string.IsNullOrEmpty(localScriptPath)) { - this.ScriptPath = localScriptPath; - this.RemoteScriptPath = originalEvent.InvocationInfo.ScriptName; + ScriptPath = localScriptPath; + RemoteScriptPath = originalEvent.InvocationInfo.ScriptName; } else { - this.ScriptPath = originalEvent.InvocationInfo.ScriptName; + ScriptPath = originalEvent.InvocationInfo.ScriptName; } - this.OriginalEvent = originalEvent; - this.RunspaceInfo = runspaceInfo; + OriginalEvent = originalEvent; + RunspaceInfo = runspaceInfo; } #endregion diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/StackFrameDetails.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/StackFrameDetails.cs index cf31a17ea..b749d67d4 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/StackFrameDetails.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/StackFrameDetails.cs @@ -84,7 +84,7 @@ internal class StackFrameDetails /// A variable container with all the filtered, auto variables for this stack frame. /// /// A new instance of the StackFrameDetails class. - static internal StackFrameDetails Create( + internal static StackFrameDetails Create( PSObject callStackFrameObject, VariableContainerDetails autoVariables, VariableContainerDetails commandVariables) diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableContainerDetails.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableContainerDetails.cs index 25d2b2f3f..2ac7b8c77 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableContainerDetails.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableContainerDetails.cs @@ -55,21 +55,18 @@ public VariableContainerDetails(int id, string name) { Validate.IsNotNull(name, "name"); - this.Id = id; - this.Name = name; - this.IsExpandable = true; - this.ValueString = " "; // An empty string isn't enough due to a temporary bug in VS Code. + Id = id; + Name = name; + IsExpandable = true; + ValueString = " "; // An empty string isn't enough due to a temporary bug in VS Code. - this.children = new Dictionary(); + children = new Dictionary(); } /// /// Gets the collection of child variables. /// - public IDictionary Children - { - get { return this.children; } - } + public IDictionary Children => children; /// /// Returns the details of the variable container's children. If empty, returns an empty array. @@ -77,8 +74,8 @@ public IDictionary Children /// public override VariableDetailsBase[] GetChildren(ILogger logger) { - var variablesArray = new VariableDetailsBase[this.children.Count]; - this.children.Values.CopyTo(variablesArray, 0); + VariableDetailsBase[] variablesArray = new VariableDetailsBase[children.Count]; + children.Values.CopyTo(variablesArray, 0); return variablesArray; } @@ -89,7 +86,7 @@ public override VariableDetailsBase[] GetChildren(ILogger logger) /// Returns true if this variable container directly contains the specified variableReferenceId, false otherwise. public bool ContainsVariable(int variableReferenceId) { - foreach (VariableDetailsBase value in this.children.Values) + foreach (VariableDetailsBase value in children.Values) { if (value.Id == variableReferenceId) { diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableDetails.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableDetails.cs index cf68689d8..b0ff245ed 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableDetails.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableDetails.cs @@ -55,7 +55,7 @@ public VariableDetails(PSVariable psVariable) /// public VariableDetails(PSObject psVariableObject) : this( - DollarPrefix + psVariableObject.Properties["Name"].Value as string, + DollarPrefix + psVariableObject.Properties["Name"].Value, psVariableObject.Properties["Value"].Value) { } @@ -80,15 +80,14 @@ public VariableDetails(PSPropertyInfo psProperty) /// The variable's value. public VariableDetails(string name, object value) { - this.ValueObject = value; + ValueObject = value; - this.Id = -1; // Not been assigned a variable reference id yet - this.Name = name; - this.IsExpandable = GetIsExpandable(value); + Id = -1; // Not been assigned a variable reference id yet + Name = name; + IsExpandable = GetIsExpandable(value); - string typeName; - this.ValueString = GetValueStringAndType(value, this.IsExpandable, out typeName); - this.Type = typeName; + ValueString = GetValueStringAndType(value, IsExpandable, out string typeName); + Type = typeName; } #endregion @@ -104,14 +103,14 @@ public override VariableDetailsBase[] GetChildren(ILogger logger) { VariableDetails[] childVariables = null; - if (this.IsExpandable) + if (IsExpandable) { - if (this.cachedChildren == null) + if (cachedChildren == null) { - this.cachedChildren = GetChildren(this.ValueObject, logger); + cachedChildren = GetChildren(ValueObject, logger); } - return this.cachedChildren; + return cachedChildren; } else { @@ -133,16 +132,13 @@ private static bool GetIsExpandable(object valueObject) } // If a PSObject, unwrap it - var psobject = valueObject as PSObject; - if (psobject != null) + if (valueObject is PSObject psobject) { valueObject = psobject.BaseObject; } Type valueType = - valueObject != null ? - valueObject.GetType() : - null; + valueObject?.GetType(); TypeInfo valueTypeInfo = valueType.GetTypeInfo(); @@ -150,9 +146,9 @@ private static bool GetIsExpandable(object valueObject) valueObject != null && !valueTypeInfo.IsPrimitive && !valueTypeInfo.IsEnum && // Enums don't have any properties - !(valueObject is string) && // Strings get treated as IEnumerables - !(valueObject is decimal) && - !(valueObject is UnableToRetrievePropertyMessage); + valueObject is not string && // Strings get treated as IEnumerables + valueObject is not decimal && + valueObject is not UnableToRetrievePropertyMessage; } private static string GetValueStringAndType(object value, bool isExpandable, out string typeName) @@ -186,11 +182,10 @@ private static string GetValueStringAndType(object value, bool isExpandable, out } else if (isExpandable) { + // For DictionaryEntry - display the key/value as the value. // Get the "value" for an expandable object. - if (value is DictionaryEntry) + if (value is DictionaryEntry entry) { - // For DictionaryEntry - display the key/value as the value. - var entry = (DictionaryEntry)value; valueString = GetValueStringAndType(entry.Value, GetIsExpandable(entry.Value), out typeName); } else @@ -205,15 +200,14 @@ private static string GetValueStringAndType(object value, bool isExpandable, out // For arrays and ICollection, display the number of contained items. if (value is Array) { - var arr = value as Array; + Array arr = value as Array; if (arr.Rank == 1) { shortTypeName = InsertDimensionSize(shortTypeName, arr.Length); } } - else if (value is ICollection) + else if (value is ICollection collection) { - var collection = (ICollection)value; shortTypeName = InsertDimensionSize(shortTypeName, collection.Count); } @@ -228,14 +222,7 @@ private static string GetValueStringAndType(object value, bool isExpandable, out else { // Value is a scalar (not expandable). If it's a string, display it directly otherwise use SafeToString() - if (value is string) - { - valueString = "\"" + value + "\""; - } - else - { - valueString = value.SafeToString(); - } + valueString = value is string ? "\"" + value + "\"" : value.SafeToString(); } return valueString; @@ -265,7 +252,7 @@ private static string InsertDimensionSize(string value, int dimensionSize) private VariableDetails[] GetChildren(object obj, ILogger logger) { - List childVariables = new List(); + List childVariables = new(); if (obj == null) { @@ -303,11 +290,8 @@ private VariableDetails[] GetChildren(object obj, ILogger logger) obj = psObject.BaseObject; } - IDictionary dictionary = obj as IDictionary; - IEnumerable enumerable = obj as IEnumerable; - // We're in the realm of regular, unwrapped .NET objects - if (dictionary != null) + if (obj is IDictionary dictionary) { // Buckle up kids, this is a bit weird. We could not use the LINQ // operator OfType. Even though R# will squiggle the @@ -332,10 +316,10 @@ private VariableDetails[] GetChildren(object obj, ILogger logger) entry)); } } - else if (enumerable != null && !(obj is string)) + else if (obj is IEnumerable enumerable and not string) { int i = 0; - foreach (var item in enumerable) + foreach (object item in enumerable) { childVariables.Add( new VariableDetails( @@ -354,7 +338,7 @@ private VariableDetails[] GetChildren(object obj, ILogger logger) // we aren't loading children on the pipeline thread so // this causes an exception to be raised. In this case, // just return an empty list of children. - logger.LogWarning($"Failed to get properties of variable {this.Name}, value invocation was attempted: {ex.Message}"); + logger.LogWarning($"Failed to get properties of variable {Name}, value invocation was attempted: {ex.Message}"); } return childVariables.ToArray(); @@ -372,9 +356,9 @@ protected static void AddDotNetProperties(object obj, List chil return; } - var properties = objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance); + PropertyInfo[] properties = objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance); - foreach (var property in properties) + foreach (PropertyInfo property in properties) { // Don't display indexer properties, it causes an exception anyway. if (property.GetIndexParameters().Length > 0) @@ -411,17 +395,11 @@ protected static void AddDotNetProperties(object obj, List chil private struct UnableToRetrievePropertyMessage { - public UnableToRetrievePropertyMessage(string message) - { - this.Message = message; - } + public UnableToRetrievePropertyMessage(string message) => Message = message; public string Message { get; } - public override string ToString() - { - return "<" + Message + ">"; - } + public override string ToString() => "<" + Message + ">"; } } @@ -434,8 +412,8 @@ internal sealed class VariableDetailsRawView : VariableDetails public VariableDetailsRawView(object value) : base(RawViewName, value) { - this.ValueString = ""; - this.Type = ""; + ValueString = ""; + Type = ""; } public override VariableDetailsBase[] GetChildren(ILogger logger) diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableScope.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableScope.cs index 50fbb3efc..d5faee6cc 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableScope.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Debugging/VariableScope.cs @@ -28,8 +28,8 @@ internal class VariableScope /// The variable scope's name. public VariableScope(int id, string name) { - this.Id = id; - this.Name = name; + Id = id; + Name = name; } } } diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/BreakpointHandlers.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/BreakpointHandlers.cs index 7055a5a5f..c40cb1e3a 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/BreakpointHandlers.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/BreakpointHandlers.cs @@ -51,7 +51,7 @@ public async Task Handle(SetBreakpointsArguments request if (!_workspaceService.TryGetFile(request.Source.Path, out ScriptFile scriptFile)) { string message = _debugStateService.NoDebug ? string.Empty : "Source file could not be accessed, breakpoint not set."; - var srcBreakpoints = request.Breakpoints + System.Collections.Generic.IEnumerable srcBreakpoints = request.Breakpoints .Select(srcBkpt => LspDebugUtils.CreateBreakpoint( srcBkpt, request.Source.Path, message, verified: _debugStateService.NoDebug)); @@ -70,7 +70,7 @@ public async Task Handle(SetBreakpointsArguments request string message = _debugStateService.NoDebug ? string.Empty : "Source is not a PowerShell script, breakpoint not set."; - var srcBreakpoints = request.Breakpoints + System.Collections.Generic.IEnumerable srcBreakpoints = request.Breakpoints .Select(srcBkpt => LspDebugUtils.CreateBreakpoint( srcBkpt, request.Source.Path, message, verified: _debugStateService.NoDebug)); @@ -163,8 +163,7 @@ await _debugService.SetCommandBreakpointsAsync( }; } - public Task Handle(SetExceptionBreakpointsArguments request, CancellationToken cancellationToken) - { + public Task Handle(SetExceptionBreakpointsArguments request, CancellationToken cancellationToken) => // TODO: When support for exception breakpoints (unhandled and/or first chance) // is added to the PowerShell engine, wire up the VSCode exception // breakpoints here using the pattern below to prevent bug regressions. @@ -187,8 +186,7 @@ public Task Handle(SetExceptionBreakpointsArgum // } //} - return Task.FromResult(new SetExceptionBreakpointsResponse()); - } + Task.FromResult(new SetExceptionBreakpointsResponse()); private bool IsFileSupportedForBreakpoints(string requestedPath, ScriptFile resolvedScriptFile) { diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/LaunchAndAttachHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/LaunchAndAttachHandler.cs index c2d0e34f8..b45edd25d 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/LaunchAndAttachHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/LaunchAndAttachHandler.cs @@ -84,7 +84,7 @@ internal record PsesAttachRequestArguments : AttachRequestArguments internal class LaunchAndAttachHandler : ILaunchHandler, IAttachHandler, IOnDebugAdapterServerStarted { - private static readonly Version s_minVersionForCustomPipeName = new Version(6, 2); + private static readonly Version s_minVersionForCustomPipeName = new(6, 2); private readonly ILogger _logger; private readonly BreakpointService _breakpointService; private readonly DebugService _debugService; @@ -161,7 +161,7 @@ public async Task Handle(PsesLaunchRequestArguments request, Can // the working dir should not be changed. if (!string.IsNullOrEmpty(workingDir)) { - var setDirCommand = new PSCommand().AddCommand("Set-Location").AddParameter("LiteralPath", workingDir); + PSCommand setDirCommand = new PSCommand().AddCommand("Set-Location").AddParameter("LiteralPath", workingDir); await _executionService.ExecutePSCommandAsync(setDirCommand, cancellationToken).ConfigureAwait(false); } @@ -243,7 +243,7 @@ public async Task Handle(PsesAttachRequestArguments request, Can throw new RpcErrorException(0, "Cannot attach to a process in a remote session when already in a remote session."); } - var enterPSSessionCommand = new PSCommand() + PSCommand enterPSSessionCommand = new PSCommand() .AddCommand("Enter-PSSession") .AddParameter("ComputerName", request.ComputerName); @@ -268,7 +268,7 @@ public async Task Handle(PsesAttachRequestArguments request, Can throw new RpcErrorException(0, $"Attaching to a process is only available with PowerShell 5 and higher (current session is {runspaceVersion.Version})."); } - var enterPSHostProcessCommand = new PSCommand() + PSCommand enterPSHostProcessCommand = new PSCommand() .AddCommand("Enter-PSHostProcess") .AddParameter("Id", processId); @@ -290,7 +290,7 @@ public async Task Handle(PsesAttachRequestArguments request, Can throw new RpcErrorException(0, $"Attaching to a process with CustomPipeName is only available with PowerShell 6.2 and higher (current session is {runspaceVersion.Version})."); } - var enterPSHostProcessCommand = new PSCommand() + PSCommand enterPSHostProcessCommand = new PSCommand() .AddCommand("Enter-PSHostProcess") .AddParameter("CustomPipeName", request.CustomPipeName); @@ -318,17 +318,17 @@ public async Task Handle(PsesAttachRequestArguments request, Can // InitializedEvent will be sent as soon as the RunspaceChanged // event gets fired with the attached runspace. - var debugRunspaceCmd = new PSCommand().AddCommand("Debug-Runspace"); + PSCommand debugRunspaceCmd = new PSCommand().AddCommand("Debug-Runspace"); if (request.RunspaceName != null) { - var getRunspaceIdCommand = new PSCommand() + PSCommand getRunspaceIdCommand = new PSCommand() .AddCommand("Microsoft.PowerShell.Utility\\Get-Runspace") .AddParameter("Name", request.RunspaceName) .AddCommand("Microsoft.PowerShell.Utility\\Select-Object") .AddParameter("ExpandProperty", "Id"); IEnumerable ids = await _executionService.ExecutePSCommandAsync(getRunspaceIdCommand, cancellationToken).ConfigureAwait(false); - foreach (var id in ids) + foreach (int? id in ids) { _debugStateService.RunspaceId = id; break; @@ -349,13 +349,13 @@ public async Task Handle(PsesAttachRequestArguments request, Can throw new RpcErrorException(0, "A positive integer must be specified for the RunspaceId field."); } - _debugStateService.RunspaceId = runspaceId; + _debugStateService.RunspaceId = runspaceId; debugRunspaceCmd.AddParameter("Id", runspaceId); } else { - _debugStateService.RunspaceId = 1; + _debugStateService.RunspaceId = 1; debugRunspaceCmd.AddParameter("Id", 1); } @@ -388,12 +388,10 @@ public async Task Handle(PsesAttachRequestArguments request, Can // we can't send the Initialized event until _after_ we finish the Launch/Attach handler. // The flow above depicts this. To achieve this, we wait until _debugStateService.ServerStarted // is set, which will be done by the Launch/Attach handlers. - public async Task OnStarted(IDebugAdapterServer server, CancellationToken cancellationToken) - { + public async Task OnStarted(IDebugAdapterServer server, CancellationToken cancellationToken) => // We wait for this task to be finished before triggering the initialized message to // be sent to the client. await _debugStateService.ServerStarted.Task.ConfigureAwait(false); - } private async Task OnExecutionCompletedAsync(Task executeTask) { diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs index baa5d3dbb..d140ba2dc 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs @@ -30,7 +30,7 @@ public Task Handle(ScopesArguments request, CancellationToken ca { VariableScope[] variableScopes = _debugService.GetVariableScopes( - (int) request.FrameId); + (int)request.FrameId); return Task.FromResult(new ScopesResponse { diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/SetVariableHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/SetVariableHandler.cs index b90bd54f4..fdd9b7889 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/SetVariableHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/SetVariableHandler.cs @@ -32,15 +32,15 @@ public async Task Handle(SetVariableArguments request, Canc { string updatedValue = await _debugService.SetVariableAsync( - (int) request.VariablesReference, + (int)request.VariablesReference, request.Name, request.Value).ConfigureAwait(false); return new SetVariableResponse { Value = updatedValue }; } - catch (Exception ex) when(ex is ArgumentTransformationMetadataException || - ex is InvalidPowerShellExpressionException || - ex is SessionStateUnauthorizedAccessException) + catch (Exception ex) when (ex is ArgumentTransformationMetadataException or + InvalidPowerShellExpressionException or + SessionStateUnauthorizedAccessException) { // Catch common, innocuous errors caused by the user supplying a value that can't be converted or the variable is not settable. _logger.LogTrace($"Failed to set variable: {ex.Message}"); diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/SourceHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/SourceHandler.cs index 911b7e46d..399c6772e 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/SourceHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/SourceHandler.cs @@ -9,11 +9,9 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class SourceHandler : ISourceHandler { - public Task Handle(SourceArguments request, CancellationToken cancellationToken) - { + public Task Handle(SourceArguments request, CancellationToken cancellationToken) => // TODO: Implement this message. For now, doesn't seem to // be a problem that it's missing. - return Task.FromResult(new SourceResponse()); - } + Task.FromResult(new SourceResponse()); } } diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs index 919bc0df3..5f9c8242e 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs @@ -43,14 +43,14 @@ public Task Handle(StackTraceArguments request, Cancellation }); } - List newStackFrames = new List(); + List newStackFrames = new(); long startFrameIndex = request.StartFrame ?? 0; long maxFrameCount = stackFrameDetails.Length; // If the number of requested levels == 0 (or null), that means get all stack frames // after the specified startFrame index. Otherwise get all the stack frames. - long requestedFrameCount = (request.Levels ?? 0); + long requestedFrameCount = request.Levels ?? 0; if (requestedFrameCount > 0) { maxFrameCount = Math.Min(maxFrameCount, startFrameIndex + requestedFrameCount); diff --git a/src/PowerShellEditorServices/Services/Extension/ChoiceDetails.cs b/src/PowerShellEditorServices/Services/Extension/ChoiceDetails.cs index fe82210fd..82d239b88 100644 --- a/src/PowerShellEditorServices/Services/Extension/ChoiceDetails.cs +++ b/src/PowerShellEditorServices/Services/Extension/ChoiceDetails.cs @@ -15,7 +15,7 @@ internal class ChoiceDetails { #region Private Fields - private string hotKeyString; + private readonly string hotKeyString; #endregion @@ -68,22 +68,22 @@ public ChoiceDetails() /// public ChoiceDetails(string label, string helpMessage) { - this.HelpMessage = helpMessage; + HelpMessage = helpMessage; - this.HotKeyIndex = label.IndexOf('&'); - if (this.HotKeyIndex >= 0) + HotKeyIndex = label.IndexOf('&'); + if (HotKeyIndex >= 0) { - this.Label = label.Remove(this.HotKeyIndex, 1); + Label = label.Remove(HotKeyIndex, 1); - if (this.HotKeyIndex < this.Label.Length) + if (HotKeyIndex < Label.Length) { - this.hotKeyString = this.Label[this.HotKeyIndex].ToString().ToUpper(); - this.HotKeyCharacter = this.hotKeyString[0]; + hotKeyString = Label[HotKeyIndex].ToString().ToUpper(); + HotKeyCharacter = hotKeyString[0]; } } else { - this.Label = label; + Label = label; } } @@ -121,8 +121,8 @@ public bool MatchesInput(string inputString) // Is it the hotkey? return - string.Equals(inputString, this.hotKeyString, StringComparison.CurrentCultureIgnoreCase) || - string.Equals(inputString, this.Label, StringComparison.CurrentCultureIgnoreCase); + string.Equals(inputString, hotKeyString, StringComparison.CurrentCultureIgnoreCase) || + string.Equals(inputString, Label, StringComparison.CurrentCultureIgnoreCase); } #endregion diff --git a/src/PowerShellEditorServices/Services/Extension/EditorOperationsService.cs b/src/PowerShellEditorServices/Services/Extension/EditorOperationsService.cs index 07b68ad37..6812cb81c 100644 --- a/src/PowerShellEditorServices/Services/Extension/EditorOperationsService.cs +++ b/src/PowerShellEditorServices/Services/Extension/EditorOperationsService.cs @@ -43,13 +43,13 @@ public async Task GetEditorContextAsync() }; ClientEditorContext clientContext = - await _languageServer.SendRequest( + await _languageServer.SendRequest( "editor/getEditorContext", new GetEditorContextRequest()) .Returning(CancellationToken.None) .ConfigureAwait(false); - return this.ConvertClientEditorContext(clientContext); + return ConvertClientEditorContext(clientContext); } public async Task InsertTextAsync(string filePath, string text, BufferRange insertRange) @@ -180,10 +180,7 @@ await _languageServer.SendRequest("editor/closeFile", filePath) .ConfigureAwait(false); } - public Task SaveFileAsync(string filePath) - { - return SaveFileAsync(filePath, null); - } + public Task SaveFileAsync(string filePath) => SaveFileAsync(filePath, null); public async Task SaveFileAsync(string currentPath, string newSavePath) { @@ -199,15 +196,9 @@ public async Task SaveFileAsync(string currentPath, string newSavePath) }).ReturningVoid(CancellationToken.None).ConfigureAwait(false); } - public string GetWorkspacePath() - { - return _workspaceService.WorkspacePath; - } + public string GetWorkspacePath() => _workspaceService.WorkspacePath; - public string GetWorkspaceRelativePath(string filePath) - { - return _workspaceService.GetRelativePath(filePath); - } + public string GetWorkspaceRelativePath(string filePath) => _workspaceService.GetRelativePath(filePath); public async Task ShowInformationMessageAsync(string message) { diff --git a/src/PowerShellEditorServices/Services/Extension/ExtensionService.cs b/src/PowerShellEditorServices/Services/Extension/ExtensionService.cs index 6882abbbc..30acf01bd 100644 --- a/src/PowerShellEditorServices/Services/Extension/ExtensionService.cs +++ b/src/PowerShellEditorServices/Services/Extension/ExtensionService.cs @@ -210,34 +210,25 @@ public EditorCommand[] GetCommands() /// public event EventHandler CommandAdded; - private void OnCommandAdded(EditorCommand command) - { - CommandAdded?.Invoke(this, command); - } + private void OnCommandAdded(EditorCommand command) => CommandAdded?.Invoke(this, command); /// /// Raised when an existing editor command is updated. /// public event EventHandler CommandUpdated; - private void OnCommandUpdated(EditorCommand command) - { - CommandUpdated?.Invoke(this, command); - } + private void OnCommandUpdated(EditorCommand command) => CommandUpdated?.Invoke(this, command); /// /// Raised when an existing editor command is removed. /// public event EventHandler CommandRemoved; - private void OnCommandRemoved(EditorCommand command) - { - CommandRemoved?.Invoke(this, command); - } + private void OnCommandRemoved(EditorCommand command) => CommandRemoved?.Invoke(this, command); private void ExtensionService_ExtensionAdded(object sender, EditorCommand e) { - _languageServer?.SendNotification( + _languageServer?.SendNotification( "powerShell/extensionCommandAdded", new ExtensionCommandAddedNotification { Name = e.Name, DisplayName = e.DisplayName }); @@ -245,7 +236,7 @@ private void ExtensionService_ExtensionAdded(object sender, EditorCommand e) private void ExtensionService_ExtensionUpdated(object sender, EditorCommand e) { - _languageServer?.SendNotification( + _languageServer?.SendNotification( "powerShell/extensionCommandUpdated", new ExtensionCommandUpdatedNotification { Name = e.Name, }); @@ -253,7 +244,7 @@ private void ExtensionService_ExtensionUpdated(object sender, EditorCommand e) private void ExtensionService_ExtensionRemoved(object sender, EditorCommand e) { - _languageServer?.SendNotification( + _languageServer?.SendNotification( "powerShell/extensionCommandRemoved", new ExtensionCommandRemovedNotification { Name = e.Name, }); diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/ConsoleProxy.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/ConsoleProxy.cs index c73e4f916..296716ff9 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/ConsoleProxy.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/ConsoleProxy.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. using System; using System.Runtime.InteropServices; @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Console /// internal static class ConsoleProxy { - private static IConsoleOperations s_consoleProxy; + private static readonly IConsoleOperations s_consoleProxy; [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1810:Initialize reference type static fields inline", Justification = "Platform specific initialization")] static ConsoleProxy() diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/IConsoleOperations.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/IConsoleOperations.cs index 4972f23a0..0b310eeb1 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/IConsoleOperations.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/IConsoleOperations.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. using System; using System.Threading; @@ -46,7 +46,7 @@ internal interface IConsoleOperations /// /// Obtains the horizontal position of the console cursor. Use this method /// instead of to avoid triggering - /// pending calls to + /// pending calls to /// on Unix platforms. /// /// The horizontal position of the console cursor. @@ -55,7 +55,7 @@ internal interface IConsoleOperations /// /// Obtains the horizontal position of the console cursor. Use this method /// instead of to avoid triggering - /// pending calls to + /// pending calls to /// on Unix platforms. /// /// The to observe. @@ -65,7 +65,7 @@ internal interface IConsoleOperations /// /// Obtains the horizontal position of the console cursor. Use this method /// instead of to avoid triggering - /// pending calls to + /// pending calls to /// on Unix platforms. /// /// @@ -78,7 +78,7 @@ internal interface IConsoleOperations /// /// Obtains the horizontal position of the console cursor. Use this method /// instead of to avoid triggering - /// pending calls to + /// pending calls to /// on Unix platforms. /// /// The to observe. @@ -92,7 +92,7 @@ internal interface IConsoleOperations /// /// Obtains the vertical position of the console cursor. Use this method /// instead of to avoid triggering - /// pending calls to + /// pending calls to /// on Unix platforms. /// /// The vertical position of the console cursor. @@ -101,7 +101,7 @@ internal interface IConsoleOperations /// /// Obtains the vertical position of the console cursor. Use this method /// instead of to avoid triggering - /// pending calls to + /// pending calls to /// on Unix platforms. /// /// The to observe. @@ -111,7 +111,7 @@ internal interface IConsoleOperations /// /// Obtains the vertical position of the console cursor. Use this method /// instead of to avoid triggering - /// pending calls to + /// pending calls to /// on Unix platforms. /// /// @@ -124,7 +124,7 @@ internal interface IConsoleOperations /// /// Obtains the vertical position of the console cursor. Use this method /// instead of to avoid triggering - /// pending calls to + /// pending calls to /// on Unix platforms. /// /// The to observe. diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/LegacyReadLine.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/LegacyReadLine.cs index c83383e3d..601f3f750 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/LegacyReadLine.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/LegacyReadLine.cs @@ -45,7 +45,7 @@ public override string ReadLine(CancellationToken cancellationToken) int historyIndex = -1; IReadOnlyList currentHistory = null; - StringBuilder inputLine = new StringBuilder(); + StringBuilder inputLine = new(); int initialCursorCol = ConsoleProxy.GetCursorLeft(cancellationToken); int initialCursorRow = ConsoleProxy.GetCursorTop(cancellationToken); @@ -420,11 +420,9 @@ private ConsoleKeyInfo ReadKeyWithIdleSupport(CancellationToken cancellationToke } } - private ConsoleKeyInfo InvokeReadKeyFunc() - { + private ConsoleKeyInfo InvokeReadKeyFunc() => // intercept = false means we display the key in the console - return _readKeyFunc(/* intercept */ false); - } + _readKeyFunc(/* intercept */ false); private static int InsertInput( StringBuilder inputLine, @@ -533,7 +531,7 @@ private static void CalculateCursorFromIndex( { cursorCol = promptStartCol + inputIndex; cursorRow = promptStartRow + cursorCol / consoleWidth; - cursorCol = cursorCol % consoleWidth; + cursorCol %= consoleWidth; } } } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/PSReadLineProxy.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/PSReadLineProxy.cs index 8f8c12ced..a166fcfc8 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/PSReadLineProxy.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/PSReadLineProxy.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. using System; using System.IO; @@ -140,15 +140,9 @@ public PSReadLineProxy( internal Func ReadLine { get; } - internal void OverrideReadKey(Func readKeyFunc) - { - _readKeyOverrideField.SetValue(null, readKeyFunc); - } + internal void OverrideReadKey(Func readKeyFunc) => _readKeyOverrideField.SetValue(null, readKeyFunc); - internal void OverrideIdleHandler(Action idleAction) - { - _handleIdleOverrideField.SetValue(null, idleAction); - } + internal void OverrideIdleHandler(Action idleAction) => _handleIdleOverrideField.SetValue(null, idleAction); private static InvalidOperationException NewInvalidPSReadLineVersionException( string memberType, diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/PsrlReadLine.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/PsrlReadLine.cs index 1bee46f76..10a540c0b 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/PsrlReadLine.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/PsrlReadLine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. using Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Host; @@ -38,15 +38,9 @@ public PsrlReadLine( #region Public Methods - public override string ReadLine(CancellationToken cancellationToken) - { - return _psesHost.InvokeDelegate(representation: "ReadLine", new ExecutionOptions { MustRunInForeground = true }, InvokePSReadLine, cancellationToken); - } + public override string ReadLine(CancellationToken cancellationToken) => _psesHost.InvokeDelegate(representation: "ReadLine", new ExecutionOptions { MustRunInForeground = true }, InvokePSReadLine, cancellationToken); - protected override ConsoleKeyInfo ReadKey(CancellationToken cancellationToken) - { - return ConsoleProxy.ReadKey(intercept: true, cancellationToken); - } + protected override ConsoleKeyInfo ReadKey(CancellationToken cancellationToken) => ConsoleProxy.ReadKey(intercept: true, cancellationToken); #endregion diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/ReadLineProvider.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/ReadLineProvider.cs index c85c92097..8b9a50312 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/ReadLineProvider.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/ReadLineProvider.cs @@ -14,10 +14,7 @@ internal class ReadLineProvider : IReadLineProvider { private readonly ILogger _logger; - public ReadLineProvider(ILoggerFactory loggerFactory) - { - _logger = loggerFactory.CreateLogger(); - } + public ReadLineProvider(ILoggerFactory loggerFactory) => _logger = loggerFactory.CreateLogger(); public IReadLine ReadLine { get; private set; } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/TerminalReadLine.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/TerminalReadLine.cs index 474c23f1c..572e97088 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/TerminalReadLine.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/TerminalReadLine.cs @@ -20,7 +20,7 @@ public SecureString ReadSecureLine(CancellationToken cancellationToken) { Console.TreatControlCAsInput = true; int previousInputLength = 0; - SecureString secureString = new SecureString(); + SecureString secureString = new(); try { bool enterPressed = false; diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/UnixConsoleOperations.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/UnixConsoleOperations.cs index e1c39536d..63eff5fc3 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/UnixConsoleOperations.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/UnixConsoleOperations.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. using System; using System.Threading; @@ -17,7 +17,7 @@ internal class UnixConsoleOperations : IConsoleOperations private const int ShortWaitForKeySpinUntilSleepTime = 30; - private static readonly ManualResetEventSlim s_waitHandle = new ManualResetEventSlim(); + private static readonly ManualResetEventSlim s_waitHandle = new(); private static readonly SemaphoreSlim s_readKeyHandle = AsyncUtils.CreateSimpleLockingSemaphore(); @@ -57,7 +57,10 @@ public ConsoleKeyInfo ReadKey(bool intercept, CancellationToken cancellationToke // The WaitForKeyAvailable delegate switches between a long delay between waits and // a short timeout depending on how recently a key has been pressed. This allows us // to let the CPU enter low power mode without compromising responsiveness. - while (!WaitForKeyAvailable(cancellationToken)); + while (!WaitForKeyAvailable(cancellationToken)) + { + ; + } } finally { @@ -94,7 +97,10 @@ public async Task ReadKeyAsync(bool intercept, CancellationToken try { - while (!await WaitForKeyAvailableAsync(cancellationToken).ConfigureAwait(false)) ; + while (!await WaitForKeyAvailableAsync(cancellationToken).ConfigureAwait(false)) + { + ; + } } finally { @@ -116,10 +122,7 @@ public async Task ReadKeyAsync(bool intercept, CancellationToken } } - public int GetCursorLeft() - { - return GetCursorLeft(CancellationToken.None); - } + public int GetCursorLeft() => GetCursorLeft(CancellationToken.None); public int GetCursorLeft(CancellationToken cancellationToken) { @@ -134,10 +137,7 @@ public int GetCursorLeft(CancellationToken cancellationToken) } } - public Task GetCursorLeftAsync() - { - return GetCursorLeftAsync(CancellationToken.None); - } + public Task GetCursorLeftAsync() => GetCursorLeftAsync(CancellationToken.None); public async Task GetCursorLeftAsync(CancellationToken cancellationToken) { @@ -152,10 +152,7 @@ public async Task GetCursorLeftAsync(CancellationToken cancellationToken) } } - public int GetCursorTop() - { - return GetCursorTop(CancellationToken.None); - } + public int GetCursorTop() => GetCursorTop(CancellationToken.None); public int GetCursorTop(CancellationToken cancellationToken) { @@ -170,10 +167,7 @@ public int GetCursorTop(CancellationToken cancellationToken) } } - public Task GetCursorTopAsync() - { - return GetCursorTopAsync(CancellationToken.None); - } + public Task GetCursorTopAsync() => GetCursorTopAsync(CancellationToken.None); public async Task GetCursorTopAsync(CancellationToken cancellationToken) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Console/WindowsConsoleOperations.cs b/src/PowerShellEditorServices/Services/PowerShell/Console/WindowsConsoleOperations.cs index 20bc886ce..7823b6bb6 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Console/WindowsConsoleOperations.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Console/WindowsConsoleOperations.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. using System; using System.Threading; @@ -12,7 +12,7 @@ internal class WindowsConsoleOperations : IConsoleOperations { private ConsoleKeyInfo? _bufferedKey; - private SemaphoreSlim _readKeyHandle = AsyncUtils.CreateSimpleLockingSemaphore(); + private readonly SemaphoreSlim _readKeyHandle = AsyncUtils.CreateSimpleLockingSemaphore(); public int GetCursorLeft() => System.Console.CursorLeft; @@ -58,9 +58,7 @@ public ConsoleKeyInfo ReadKey(bool intercept, CancellationToken cancellationToke try { return - _bufferedKey.HasValue - ? _bufferedKey.Value - : (_bufferedKey = System.Console.ReadKey(intercept)).Value; + _bufferedKey ?? (_bufferedKey = System.Console.ReadKey(intercept)).Value; } finally { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellContextFrame.cs b/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellContextFrame.cs index 9a31bf629..b3007a0e7 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellContextFrame.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellContextFrame.cs @@ -16,7 +16,7 @@ public static PowerShellContextFrame CreateForPowerShellInstance( PowerShellFrameType frameType, string localComputerName) { - var runspaceInfo = RunspaceInfo.CreateFromPowerShell(logger, pwsh, localComputerName); + RunspaceInfo runspaceInfo = RunspaceInfo.CreateFromPowerShell(logger, pwsh, localComputerName); return new PowerShellContextFrame(pwsh, runspaceInfo, frameType); } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellVersionDetails.cs b/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellVersionDetails.cs index 2b1980cc1..157fe865c 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellVersionDetails.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Context/PowerShellVersionDetails.cs @@ -77,10 +77,10 @@ public PowerShellVersionDetails( string editionString, PowerShellProcessArchitecture architecture) { - this.Version = version; - this.VersionString = versionString; - this.Edition = editionString; - this.Architecture = architecture; + Version = version; + VersionString = versionString; + Edition = editionString; + Architecture = architecture; } #endregion @@ -94,10 +94,10 @@ public PowerShellVersionDetails( /// A new PowerShellVersionDetails instance. public static PowerShellVersionDetails GetVersionDetails(ILogger logger, PowerShell pwsh) { - Version powerShellVersion = new Version(5, 0); + Version powerShellVersion = new(5, 0); string versionString = null; string powerShellEdition = "Desktop"; - var architecture = PowerShellProcessArchitecture.Unknown; + PowerShellProcessArchitecture architecture = PowerShellProcessArchitecture.Unknown; try { @@ -108,8 +108,7 @@ public static PowerShellVersionDetails GetVersionDetails(ILogger logger, PowerSh if (psVersionTable != null) { - var edition = psVersionTable["PSEdition"] as string; - if (edition != null) + if (psVersionTable["PSEdition"] is string edition) { powerShellEdition = edition; } @@ -117,7 +116,7 @@ public static PowerShellVersionDetails GetVersionDetails(ILogger logger, PowerSh // The PSVersion value will either be of Version or SemanticVersion. // In the former case, take the value directly. In the latter case, // generate a Version from its string representation. - var version = psVersionTable["PSVersion"]; + object version = psVersionTable["PSVersion"]; if (version is Version) { powerShellVersion = (Version)version; @@ -128,17 +127,9 @@ public static PowerShellVersionDetails GetVersionDetails(ILogger logger, PowerSh powerShellVersion = new Version(version.ToString().Split('-')[0]); } - var gitCommitId = psVersionTable["GitCommitId"] as string; - if (gitCommitId != null) - { - versionString = gitCommitId; - } - else - { - versionString = powerShellVersion.ToString(); - } + versionString = psVersionTable["GitCommitId"] is string gitCommitId ? gitCommitId : powerShellVersion.ToString(); - var procArchCommand = new PSCommand().AddScript("$env:PROCESSOR_ARCHITECTURE", useLocalScope: true); + PSCommand procArchCommand = new PSCommand().AddScript("$env:PROCESSOR_ARCHITECTURE", useLocalScope: true); string arch = pwsh .AddScript("$env:PROCESSOR_ARCHITECTURE", useLocalScope: true) diff --git a/src/PowerShellEditorServices/Services/PowerShell/Debugging/DscBreakpointCapability.cs b/src/PowerShellEditorServices/Services/PowerShell/Debugging/DscBreakpointCapability.cs index c13d3e301..1579c00a6 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Debugging/DscBreakpointCapability.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Debugging/DscBreakpointCapability.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. using System.Linq; using System.Threading.Tasks; @@ -23,8 +23,8 @@ internal class DscBreakpointCapability { private string[] dscResourceRootPaths = Array.Empty(); - private Dictionary breakpointsPerFile = - new Dictionary(); + private readonly Dictionary breakpointsPerFile = + new(); public async Task SetLineBreakpointsAsync( IInternalPowerShellExecutionService executionService, @@ -32,32 +32,32 @@ public async Task SetLineBreakpointsAsync( BreakpointDetails[] breakpoints) { List resultBreakpointDetails = - new List(); + new(); // We always get the latest array of breakpoint line numbers // so store that for future use if (breakpoints.Length > 0) { // Set the breakpoints for this scriptPath - this.breakpointsPerFile[scriptPath] = + breakpointsPerFile[scriptPath] = breakpoints.Select(b => b.LineNumber).ToArray(); } else { // No more breakpoints for this scriptPath, remove it - this.breakpointsPerFile.Remove(scriptPath); + breakpointsPerFile.Remove(scriptPath); } string hashtableString = string.Join( ", ", - this.breakpointsPerFile + breakpointsPerFile .Select(file => $"@{{Path=\"{file.Key}\";Line=@({string.Join(",", file.Value)})}}")); // Run Enable-DscDebug as a script because running it as a PSCommand // causes an error which states that the Breakpoint parameter has not // been passed. - var dscCommand = new PSCommand().AddScript( + PSCommand dscCommand = new PSCommand().AddScript( hashtableString.Length > 0 ? $"Enable-DscDebug -Breakpoint {hashtableString}" : "Disable-DscDebug"); @@ -68,7 +68,7 @@ await executionService.ExecutePSCommandAsync( .ConfigureAwait(false); // Verify all the breakpoints and return them - foreach (var breakpoint in breakpoints) + foreach (BreakpointDetails breakpoint in breakpoints) { breakpoint.Verified = true; } @@ -100,7 +100,7 @@ public static Task GetDscCapabilityAsync( Func getDscBreakpointCapabilityFunc = (pwsh, cancellationToken) => { - var invocationSettings = new PSInvocationSettings + PSInvocationSettings invocationSettings = new() { AddToHistory = false, ErrorActionPreference = ActionPreference.Stop @@ -129,7 +129,7 @@ public static Task GetDscCapabilityAsync( logger.LogTrace("Side-by-side DSC module found, gathering DSC resource paths..."); // The module was loaded, add the breakpoint capability - var capability = new DscBreakpointCapability(); + DscBreakpointCapability capability = new(); pwsh.AddCommand("Microsoft.PowerShell.Utility\\Write-Host") .AddArgument("Gathering DSC resource paths, this may take a while...") @@ -162,7 +162,7 @@ public static Task GetDscCapabilityAsync( return capability; }; - return psesHost.ExecuteDelegateAsync( + return psesHost.ExecuteDelegateAsync( nameof(getDscBreakpointCapabilityFunc), executionOptions: null, getDscBreakpointCapabilityFunc, diff --git a/src/PowerShellEditorServices/Services/PowerShell/Debugging/PowerShellDebugContext.cs b/src/PowerShellEditorServices/Services/PowerShell/Debugging/PowerShellDebugContext.cs index a6c1d27e1..60a858a4c 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Debugging/PowerShellDebugContext.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Debugging/PowerShellDebugContext.cs @@ -74,17 +74,11 @@ public PowerShellDebugContext( public event Action DebuggerResuming; public event Action BreakpointUpdated; - public Task GetDscBreakpointCapabilityAsync(CancellationToken cancellationToken) - { - return _psesHost.CurrentRunspace.GetDscBreakpointCapabilityAsync(_logger, _psesHost, cancellationToken); - } + public Task GetDscBreakpointCapabilityAsync(CancellationToken cancellationToken) => _psesHost.CurrentRunspace.GetDscBreakpointCapabilityAsync(_logger, _psesHost, cancellationToken); // This is required by the PowerShell API so that remote debugging works. Without it, a // runspace may not have these options set and attempting to set breakpoints remotely fails. - public void EnableDebugMode() - { - _psesHost.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); - } + public void EnableDebugMode() => _psesHost.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); public void Abort() => SetDebugResuming(DebuggerResumeAction.Stop); @@ -133,7 +127,7 @@ public void SetDebuggerStopped(DebuggerStopEventArgs args) LastStopEventArgs = args; } - public void SetDebuggerResumed() { IsStopped = false; } + public void SetDebuggerResumed() => IsStopped = false; public void ProcessDebuggerResult(DebuggerCommandResults debuggerResult) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Execution/BlockingConcurrentDeque.cs b/src/PowerShellEditorServices/Services/PowerShell/Execution/BlockingConcurrentDeque.cs index 71d34d4f3..197a8bede 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Execution/BlockingConcurrentDeque.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Execution/BlockingConcurrentDeque.cs @@ -41,15 +41,9 @@ public BlockingConcurrentDeque() public bool IsEmpty => _queues[0].Count == 0 && _queues[1].Count == 0; - public void Prepend(T item) - { - _queues[0].Add(item); - } + public void Prepend(T item) => _queues[0].Add(item); - public void Append(T item) - { - _queues[1].Add(item); - } + public void Append(T item) => _queues[1].Add(item); public T Take(CancellationToken cancellationToken) { @@ -71,10 +65,7 @@ public bool TryTake(out T item) public IDisposable BlockConsumers() => PriorityQueueBlockLifetime.StartBlocking(_blockConsumersEvent); - public void Dispose() - { - ((IDisposable)_blockConsumersEvent).Dispose(); - } + public void Dispose() => ((IDisposable)_blockConsumersEvent).Dispose(); private class PriorityQueueBlockLifetime : IDisposable { @@ -86,15 +77,9 @@ public static PriorityQueueBlockLifetime StartBlocking(ManualResetEventSlim bloc private readonly ManualResetEventSlim _blockEvent; - private PriorityQueueBlockLifetime(ManualResetEventSlim blockEvent) - { - _blockEvent = blockEvent; - } + private PriorityQueueBlockLifetime(ManualResetEventSlim blockEvent) => _blockEvent = blockEvent; - public void Dispose() - { - _blockEvent.Set(); - } + public void Dispose() => _blockEvent.Set(); } } } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousDelegateTask.cs b/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousDelegateTask.cs index 77bae18a3..2d40681e3 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousDelegateTask.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousDelegateTask.cs @@ -36,10 +36,7 @@ public override object Run(CancellationToken cancellationToken) return null; } - public override string ToString() - { - return _representation; - } + public override string ToString() => _representation; } internal class SynchronousDelegateTask : SynchronousTask @@ -63,15 +60,9 @@ public SynchronousDelegateTask( public override ExecutionOptions ExecutionOptions { get; } - public override TResult Run(CancellationToken cancellationToken) - { - return _func(cancellationToken); - } + public override TResult Run(CancellationToken cancellationToken) => _func(cancellationToken); - public override string ToString() - { - return _representation; - } + public override string ToString() => _representation; } internal class SynchronousPSDelegateTask : SynchronousTask @@ -105,10 +96,7 @@ public override object Run(CancellationToken cancellationToken) return null; } - public override string ToString() - { - return _representation; - } + public override string ToString() => _representation; } internal class SynchronousPSDelegateTask : SynchronousTask @@ -136,14 +124,8 @@ public SynchronousPSDelegateTask( public override ExecutionOptions ExecutionOptions { get; } - public override TResult Run(CancellationToken cancellationToken) - { - return _func(_psesHost.CurrentPowerShell, cancellationToken); - } + public override TResult Run(CancellationToken cancellationToken) => _func(_psesHost.CurrentPowerShell, cancellationToken); - public override string ToString() - { - return _representation; - } + public override string ToString() => _representation; } } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousPowerShellTask.cs b/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousPowerShellTask.cs index c5fdcc698..56239947f 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousPowerShellTask.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousPowerShellTask.cs @@ -25,7 +25,7 @@ internal class SynchronousPowerShellTask : SynchronousTask Run(CancellationToken cancellationToken) { @@ -66,10 +66,7 @@ public override IReadOnlyList Run(CancellationToken cancellationToken) : ExecuteNormally(cancellationToken); } - public override string ToString() - { - return _psCommand.GetInvocationText(); - } + public override string ToString() => _psCommand.GetInvocationText(); private IReadOnlyList ExecuteNormally(CancellationToken cancellationToken) { @@ -83,7 +80,7 @@ private IReadOnlyList ExecuteNormally(CancellationToken cancellationTok Collection result = null; try { - var invocationSettings = new PSInvocationSettings + PSInvocationSettings invocationSettings = new() { AddToHistory = PowerShellExecutionOptions.AddToHistory, }; @@ -118,7 +115,7 @@ private IReadOnlyList ExecuteNormally(CancellationToken cancellationTok throw; } - var command = new PSCommand() + PSCommand command = new PSCommand() .AddOutputCommand() .AddParameter("InputObject", e.ErrorRecord.AsPSObject()); @@ -141,7 +138,7 @@ private IReadOnlyList ExecuteInDebugger(CancellationToken cancellationT // intrinsic debugger commands? cancellationToken.Register(CancelDebugExecution); - var outputCollection = new PSDataCollection(); + PSDataCollection outputCollection = new(); // Out-Default doesn't work as needed in the debugger // Instead we add Out-String to the command and collect results in a PSDataCollection @@ -195,7 +192,7 @@ private IReadOnlyList ExecuteInDebugger(CancellationToken cancellationT throw; } - var errorOutputCollection = new PSDataCollection(); + PSDataCollection errorOutputCollection = new(); errorOutputCollection.DataAdded += (object sender, DataAddedEventArgs args) => { for (int i = args.Index; i < outputCollection.Count; i++) @@ -204,7 +201,7 @@ private IReadOnlyList ExecuteInDebugger(CancellationToken cancellationT } }; - var command = new PSCommand() + PSCommand command = new PSCommand() .AddDebugOutputCommand() .AddParameter("InputObject", e.ErrorRecord.AsPSObject()); @@ -234,7 +231,7 @@ private IReadOnlyList ExecuteInDebugger(CancellationToken cancellationT } // Otherwise, convert things over - var results = new List(outputCollection.Count); + List results = new(outputCollection.Count); foreach (PSObject outputResult in outputCollection) { if (LanguagePrimitives.TryConvertTo(outputResult, typeof(TResult), out object result)) @@ -252,9 +249,9 @@ private void StopDebuggerIfRemoteDebugSessionFailed() // Instead we have to query the remote directly if (_pwsh.Runspace.RunspaceIsRemote) { - var assessDebuggerCommand = new PSCommand().AddScript("$Host.Runspace.Debugger.InBreakpoint"); + PSCommand assessDebuggerCommand = new PSCommand().AddScript("$Host.Runspace.Debugger.InBreakpoint"); - var outputCollection = new PSDataCollection(); + PSDataCollection outputCollection = new(); _pwsh.Runspace.Debugger.ProcessCommand(assessDebuggerCommand, outputCollection); foreach (PSObject output in outputCollection) @@ -269,14 +266,8 @@ private void StopDebuggerIfRemoteDebugSessionFailed() } } - private void CancelNormalExecution() - { - _pwsh.Stop(); - } + private void CancelNormalExecution() => _pwsh.Stop(); - private void CancelDebugExecution() - { - _pwsh.Runspace.Debugger.StopProcessCommand(); - } + private void CancelDebugExecution() => _pwsh.Runspace.Debugger.StopProcessCommand(); } } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousTask.cs b/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousTask.cs index d8efdbf4b..a3554fa7e 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousTask.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Execution/SynchronousTask.cs @@ -79,7 +79,7 @@ public void ExecuteSynchronously(CancellationToken executorCancellationToken) return; } - using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(_taskRequesterCancellationToken, executorCancellationToken); + using CancellationTokenSource cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(_taskRequesterCancellationToken, executorCancellationToken); if (cancellationSource.IsCancellationRequested) { SetCanceled(); diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/ExpandAliasHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/ExpandAliasHandler.cs index 44ba1bfe7..92141cc89 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/ExpandAliasHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/ExpandAliasHandler.cs @@ -63,17 +63,17 @@ function __Expand-Alias { }"; // TODO: Refactor to not rerun the function definition every time. - var psCommand = new PSCommand(); + PSCommand psCommand = new(); psCommand .AddScript(script) .AddStatement() .AddCommand("__Expand-Alias") .AddArgument(request.Text); - var result = await _executionService.ExecutePSCommandAsync(psCommand, cancellationToken).ConfigureAwait(false); + System.Collections.Generic.IReadOnlyList result = await _executionService.ExecutePSCommandAsync(psCommand, cancellationToken).ConfigureAwait(false); return new ExpandAliasResult { - Text = result.First() + Text = result[0] }; } } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommandHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommandHandler.cs index 6db8a898a..12b8b797e 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommandHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommandHandler.cs @@ -43,7 +43,7 @@ public GetCommandHandler(ILoggerFactory factory, IInternalPowerShellExecutionSer public async Task> Handle(GetCommandParams request, CancellationToken cancellationToken) { - PSCommand psCommand = new PSCommand(); + PSCommand psCommand = new(); // Executes the following: // Get-Command -CommandType Function,Cmdlet,ExternalScript | Sort-Object -Property Name @@ -55,7 +55,7 @@ public async Task> Handle(GetCommandParams request, Cance IEnumerable result = await _executionService.ExecutePSCommandAsync(psCommand, cancellationToken).ConfigureAwait(false); - var commandList = new List(); + List commandList = new(); if (result != null) { foreach (CommandInfo command in result) diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommentHelpHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommentHelpHandler.cs index dfab76aa0..782d8e989 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommentHelpHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetCommentHelpHandler.cs @@ -33,7 +33,7 @@ public GetCommentHelpHandler( public async Task Handle(CommentHelpRequestParams request, CancellationToken cancellationToken) { - var result = new CommentHelpRequestResult(); + CommentHelpRequestResult result = new(); if (!_workspaceService.TryGetFile(request.DocumentUri, out ScriptFile scriptFile)) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetVersionHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetVersionHandler.cs index afe0b8e20..58b0f5d89 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetVersionHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/GetVersionHandler.cs @@ -20,7 +20,7 @@ namespace Microsoft.PowerShell.EditorServices.Handlers internal class GetVersionHandler : IGetVersionHandler { private readonly ILogger _logger; - private IRunspaceContext _runspaceContext; + private readonly IRunspaceContext _runspaceContext; private readonly IInternalPowerShellExecutionService _executionService; private readonly ILanguageServerFacade _languageServer; private readonly ConfigurationService _configurationService; @@ -41,7 +41,7 @@ public GetVersionHandler( public async Task Handle(GetVersionParams request, CancellationToken cancellationToken) { - var architecture = PowerShellProcessArchitecture.Unknown; + PowerShellProcessArchitecture architecture = PowerShellProcessArchitecture.Unknown; // This should be changed to using a .NET call sometime in the future... but it's just for logging purposes. string arch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); if (arch != null) diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/IGetRunspaceHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/IGetRunspaceHandler.cs index 8290c86ed..7cf86e45e 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/IGetRunspaceHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/IGetRunspaceHandler.cs @@ -11,7 +11,7 @@ internal interface IGetRunspaceHandler : IJsonRpcRequestHandler { - public string ProcessId {get; set; } + public string ProcessId { get; set; } } internal class RunspaceResponse diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/IGetVersionHandler.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/IGetVersionHandler.cs index d727950b3..66e66eab6 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/IGetVersionHandler.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/IGetVersionHandler.cs @@ -25,22 +25,16 @@ public PowerShellVersion() public PowerShellVersion(PowerShellVersionDetails versionDetails) { - this.Version = versionDetails.VersionString; - this.DisplayVersion = $"{versionDetails.Version.Major}.{versionDetails.Version.Minor}"; - this.Edition = versionDetails.Edition; + Version = versionDetails.VersionString; + DisplayVersion = $"{versionDetails.Version.Major}.{versionDetails.Version.Minor}"; + Edition = versionDetails.Edition; - switch (versionDetails.Architecture) + Architecture = versionDetails.Architecture switch { - case PowerShellProcessArchitecture.X64: - this.Architecture = "x64"; - break; - case PowerShellProcessArchitecture.X86: - this.Architecture = "x86"; - break; - default: - this.Architecture = "Architecture Unknown"; - break; - } + PowerShellProcessArchitecture.X64 => "x64", + PowerShellProcessArchitecture.X86 => "x86", + _ => "Architecture Unknown", + }; } } } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Handlers/PSHostProcessAndRunspaceHandlers.cs b/src/PowerShellEditorServices/Services/PowerShell/Handlers/PSHostProcessAndRunspaceHandlers.cs index e4f5586bb..f288a9584 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Handlers/PSHostProcessAndRunspaceHandlers.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Handlers/PSHostProcessAndRunspaceHandlers.cs @@ -25,11 +25,11 @@ public PSHostProcessAndRunspaceHandlers(ILoggerFactory factory, IInternalPowerSh public Task Handle(GetPSHostProcesssesParams request, CancellationToken cancellationToken) { - var psHostProcesses = new List(); + List psHostProcesses = new(); int processId = System.Diagnostics.Process.GetCurrentProcess().Id; - using (var pwsh = PowerShell.Create()) + using (PowerShell pwsh = PowerShell.Create()) { pwsh.AddCommand("Get-PSHostProcessInfo") .AddCommand("Where-Object") @@ -37,7 +37,7 @@ public Task Handle(GetPSHostProcesssesParams request, C .AddParameter("NE") .AddParameter("Value", processId.ToString()); - var processes = pwsh.Invoke(); + System.Collections.ObjectModel.Collection processes = pwsh.Invoke(); if (processes != null) { @@ -72,23 +72,21 @@ public async Task Handle(GetRunspaceParams request, Cancella if (int.TryParse(request.ProcessId, out int pid)) { // Create a remote runspace that we will invoke Get-Runspace in. - using (var rs = RunspaceFactory.CreateRunspace(new NamedPipeConnectionInfo(pid))) - using (var ps = PowerShell.Create()) - { - rs.Open(); - ps.Runspace = rs; - // Returns deserialized Runspaces. For simpler code, we use PSObject and rely on dynamic later. - runspaces = ps.AddCommand("Microsoft.PowerShell.Utility\\Get-Runspace").Invoke(); - } + using Runspace rs = RunspaceFactory.CreateRunspace(new NamedPipeConnectionInfo(pid)); + using PowerShell ps = PowerShell.Create(); + rs.Open(); + ps.Runspace = rs; + // Returns deserialized Runspaces. For simpler code, we use PSObject and rely on dynamic later. + runspaces = ps.AddCommand("Microsoft.PowerShell.Utility\\Get-Runspace").Invoke(); } else { - var psCommand = new PSCommand().AddCommand("Microsoft.PowerShell.Utility\\Get-Runspace"); + PSCommand psCommand = new PSCommand().AddCommand("Microsoft.PowerShell.Utility\\Get-Runspace"); // returns (not deserialized) Runspaces. For simpler code, we use PSObject and rely on dynamic later. runspaces = await _executionService.ExecutePSCommandAsync(psCommand, cancellationToken).ConfigureAwait(false); } - var runspaceResponses = new List(); + List runspaceResponses = new(); if (runspaces != null) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHost.cs b/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHost.cs index bc83286e0..06371b6b5 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHost.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHost.cs @@ -12,10 +12,7 @@ public class EditorServicesConsolePSHost : PSHost, IHostSupportsInteractiveSessi private readonly PsesInternalHost _internalHost; internal EditorServicesConsolePSHost( - PsesInternalHost internalHost) - { - _internalHost = internalHost; - } + PsesInternalHost internalHost) => _internalHost = internalHost; public override CultureInfo CurrentCulture => _internalHost.CurrentCulture; diff --git a/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHostRawUserInterface.cs b/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHostRawUserInterface.cs index acf866942..b435ac321 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHostRawUserInterface.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHostRawUserInterface.cs @@ -45,8 +45,8 @@ public EditorServicesConsolePSHostRawUserInterface( /// public override ConsoleColor BackgroundColor { - get { return System.Console.BackgroundColor; } - set { System.Console.BackgroundColor = value; } + get => System.Console.BackgroundColor; + set => System.Console.BackgroundColor = value; } /// @@ -54,8 +54,8 @@ public override ConsoleColor BackgroundColor /// public override ConsoleColor ForegroundColor { - get { return System.Console.ForegroundColor; } - set { System.Console.ForegroundColor = value; } + get => System.Console.ForegroundColor; + set => System.Console.ForegroundColor = value; } /// @@ -72,12 +72,9 @@ public override Size BufferSize /// public override Coordinates CursorPosition { - get - { - return new Coordinates( + get => new( ConsoleProxy.GetCursorLeft(), ConsoleProxy.GetCursorTop()); - } set => _internalRawUI.CursorPosition = value; } @@ -170,7 +167,7 @@ public override KeyInfo ReadKey(ReadKeyOptions options) try { System.Console.TreatControlCAsInput = true; - ConsoleKeyInfo key = ConsoleProxy.ReadKey(intercept, default(CancellationToken)); + ConsoleKeyInfo key = ConsoleProxy.ReadKey(intercept, default); if (IsCtrlC(key)) { @@ -208,10 +205,7 @@ public override void FlushInputBuffer() /// /// The rectangle inside which buffer contents will be accessed. /// A BufferCell array with the requested buffer contents. - public override BufferCell[,] GetBufferContents(Rectangle rectangle) - { - return _internalRawUI.GetBufferContents(rectangle); - } + public override BufferCell[,] GetBufferContents(Rectangle rectangle) => _internalRawUI.GetBufferContents(rectangle); /// /// Scrolls the contents of the console buffer. @@ -224,10 +218,7 @@ public override void ScrollBufferContents( Rectangle source, Coordinates destination, Rectangle clip, - BufferCell fill) - { - _internalRawUI.ScrollBufferContents(source, destination, clip, fill); - } + BufferCell fill) => _internalRawUI.ScrollBufferContents(source, destination, clip, fill); /// /// Sets the contents of the buffer inside the specified rectangle. @@ -258,10 +249,7 @@ public override void SetBufferContents( /// The new contents for the buffer at the given coordinate. public override void SetBufferContents( Coordinates origin, - BufferCell[,] contents) - { - _internalRawUI.SetBufferContents(origin, contents); - } + BufferCell[,] contents) => _internalRawUI.SetBufferContents(origin, contents); /// /// Determines the number of BufferCells a character occupies. @@ -273,10 +261,7 @@ public override void SetBufferContents( /// The length in buffer cells according to the original host /// implementation for the process. /// - public override int LengthInBufferCells(char source) - { - return _internalRawUI.LengthInBufferCells(source); - } + public override int LengthInBufferCells(char source) => _internalRawUI.LengthInBufferCells(source); /// /// Determines the number of BufferCells a string occupies. /// @@ -287,10 +272,7 @@ public override int LengthInBufferCells(char source) /// The length in buffer cells according to the original host /// implementation for the process. /// - public override int LengthInBufferCells(string source) - { - return _internalRawUI.LengthInBufferCells(source); - } + public override int LengthInBufferCells(string source) => _internalRawUI.LengthInBufferCells(source); /// /// Determines the number of BufferCells a substring of a string occupies. @@ -305,10 +287,7 @@ public override int LengthInBufferCells(string source) /// The length in buffer cells according to the original host /// implementation for the process. /// - public override int LengthInBufferCells(string source, int offset) - { - return _internalRawUI.LengthInBufferCells(source, offset); - } + public override int LengthInBufferCells(string source, int offset) => _internalRawUI.LengthInBufferCells(source, offset); #endregion @@ -360,7 +339,7 @@ private KeyInfo ProcessKey(ConsoleKeyInfo key, bool isDown) states |= ControlKeyStates.ShiftPressed; } - var result = new KeyInfo((int)key.Key, key.KeyChar, states, isDown); + KeyInfo result = new((int)key.Key, key.KeyChar, states, isDown); if (isDown) { _lastKeyDown = result; diff --git a/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHostUserInterface.cs b/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHostUserInterface.cs index fbc02a70f..44ea3cb1b 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHostUserInterface.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Host/EditorServicesConsolePSHostUserInterface.cs @@ -112,14 +112,9 @@ public override PSCredential PromptForCredential(string caption, string message, public override void WriteProgress(long sourceId, ProgressRecord record) { - if (record.RecordType == ProgressRecordType.Completed) - { - _ = _currentProgressRecords.TryRemove((sourceId, record.ActivityId), out _); - } - else - { - _ = _currentProgressRecords.TryAdd((sourceId, record.ActivityId), null); - } + _ = record.RecordType == ProgressRecordType.Completed + ? _currentProgressRecords.TryRemove((sourceId, record.ActivityId), out _) + : _currentProgressRecords.TryAdd((sourceId, record.ActivityId), null); _underlyingHostUI.WriteProgress(sourceId, record); } @@ -156,9 +151,6 @@ private static PSHostUserInterface GetConsoleHostUI(PSHostUserInterface ui) return (PSHostUserInterface)externalUIField.GetValue(ui); } - private static void SetConsoleHostUIToInteractive(PSHostUserInterface ui) - { - ui.GetType().GetProperty("ThrowOnReadAndPrompt", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(ui, false); - } + private static void SetConsoleHostUIToInteractive(PSHostUserInterface ui) => ui.GetType().GetProperty("ThrowOnReadAndPrompt", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(ui, false); } } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostRawUI.cs b/src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostRawUI.cs index cb5c997c1..8d5774780 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostRawUI.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostRawUI.cs @@ -10,10 +10,7 @@ internal class NullPSHostRawUI : PSHostRawUserInterface { private readonly BufferCell[,] _buffer; - public NullPSHostRawUI() - { - _buffer = new BufferCell[0, 0]; - } + public NullPSHostRawUI() => _buffer = new BufferCell[0, 0]; public override ConsoleColor BackgroundColor { get; set; } public override Size BufferSize { get; set; } @@ -25,7 +22,7 @@ public NullPSHostRawUI() public override Size MaxPhysicalWindowSize => MaxWindowSize; - public override Size MaxWindowSize => new Size { Width = _buffer.GetLength(0), Height = _buffer.GetLength(1) }; + public override Size MaxWindowSize => new() { Width = _buffer.GetLength(0), Height = _buffer.GetLength(1) }; public override Coordinates WindowPosition { get; set; } public override Size WindowSize { get; set; } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostUI.cs b/src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostUI.cs index 655fd2fe9..2b8fb7f50 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostUI.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Host/NullPSHostUI.cs @@ -12,40 +12,22 @@ namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Host { internal class NullPSHostUI : PSHostUserInterface { - public NullPSHostUI() - { - RawUI = new NullPSHostRawUI(); - } + public NullPSHostUI() => RawUI = new NullPSHostRawUI(); public override PSHostRawUserInterface RawUI { get; } - public override Dictionary Prompt(string caption, string message, Collection descriptions) - { - return new Dictionary(); - } + public override Dictionary Prompt(string caption, string message, Collection descriptions) => new(); - public override int PromptForChoice(string caption, string message, Collection choices, int defaultChoice) - { - return 0; - } + public override int PromptForChoice(string caption, string message, Collection choices, int defaultChoice) => 0; - public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) - { - return new PSCredential(userName: string.Empty, password: new SecureString()); - } + public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) => new(userName: string.Empty, password: new SecureString()); public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName) => PromptForCredential(caption, message, userName, targetName, PSCredentialTypes.Default, PSCredentialUIOptions.Default); - public override string ReadLine() - { - return string.Empty; - } + public override string ReadLine() => string.Empty; - public override SecureString ReadLineAsSecureString() - { - return new SecureString(); - } + public override SecureString ReadLineAsSecureString() => new(); public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Host/PsesInternalHost.cs b/src/PowerShellEditorServices/Services/PowerShell/Host/PsesInternalHost.cs index bf0316a65..3ffc2761d 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Host/PsesInternalHost.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Host/PsesInternalHost.cs @@ -283,10 +283,7 @@ public Task InvokeTaskOnPipelineThreadAsync( return task.Task; } - public void CancelCurrentTask() - { - _cancellationContext.CancelCurrentTask(); - } + public void CancelCurrentTask() => _cancellationContext.CancelCurrentTask(); public Task ExecuteDelegateAsync( string representation, @@ -340,43 +337,37 @@ public Task> ExecutePSCommandAsync( public Task ExecutePSCommandAsync( PSCommand psCommand, CancellationToken cancellationToken, - PowerShellExecutionOptions executionOptions = null) - { - return ExecutePSCommandAsync(psCommand, cancellationToken, executionOptions); - } + PowerShellExecutionOptions executionOptions = null) => ExecutePSCommandAsync(psCommand, cancellationToken, executionOptions); public TResult InvokeDelegate(string representation, ExecutionOptions executionOptions, Func func, CancellationToken cancellationToken) { - var task = new SynchronousDelegateTask(_logger, representation, executionOptions, func, cancellationToken); + SynchronousDelegateTask task = new(_logger, representation, executionOptions, func, cancellationToken); return task.ExecuteAndGetResult(cancellationToken); } public void InvokeDelegate(string representation, ExecutionOptions executionOptions, Action action, CancellationToken cancellationToken) { - var task = new SynchronousDelegateTask(_logger, representation, executionOptions, action, cancellationToken); + SynchronousDelegateTask task = new(_logger, representation, executionOptions, action, cancellationToken); task.ExecuteAndGetResult(cancellationToken); } public IReadOnlyList InvokePSCommand(PSCommand psCommand, PowerShellExecutionOptions executionOptions, CancellationToken cancellationToken) { - var task = new SynchronousPowerShellTask(_logger, this, psCommand, executionOptions, cancellationToken); + SynchronousPowerShellTask task = new(_logger, this, psCommand, executionOptions, cancellationToken); return task.ExecuteAndGetResult(cancellationToken); } - public void InvokePSCommand(PSCommand psCommand, PowerShellExecutionOptions executionOptions, CancellationToken cancellationToken) - { - InvokePSCommand(psCommand, executionOptions, cancellationToken); - } + public void InvokePSCommand(PSCommand psCommand, PowerShellExecutionOptions executionOptions, CancellationToken cancellationToken) => InvokePSCommand(psCommand, executionOptions, cancellationToken); public TResult InvokePSDelegate(string representation, ExecutionOptions executionOptions, Func func, CancellationToken cancellationToken) { - var task = new SynchronousPSDelegateTask(_logger, this, representation, executionOptions, func, cancellationToken); + SynchronousPSDelegateTask task = new(_logger, this, representation, executionOptions, func, cancellationToken); return task.ExecuteAndGetResult(cancellationToken); } public void InvokePSDelegate(string representation, ExecutionOptions executionOptions, Action action, CancellationToken cancellationToken) { - var task = new SynchronousPSDelegateTask(_logger, this, representation, executionOptions, action, cancellationToken); + SynchronousPSDelegateTask task = new(_logger, this, representation, executionOptions, action, cancellationToken); task.ExecuteAndGetResult(cancellationToken); } @@ -666,7 +657,7 @@ private string GetPrompt(CancellationToken cancellationToken) try { // TODO: Should we cache PSCommands like this as static members? - var command = new PSCommand().AddCommand("prompt"); + PSCommand command = new PSCommand().AddCommand("prompt"); IReadOnlyList results = InvokePSCommand(command, executionOptions: null, cancellationToken); if (results.Count > 0) { @@ -699,14 +690,11 @@ public void WriteWithPrompt(PSCommand command, CancellationToken cancellationTok UI.WriteLine(command.GetInvocationText()); } - private string InvokeReadLine(CancellationToken cancellationToken) - { - return _readLineProvider.ReadLine.ReadLine(cancellationToken); - } + private string InvokeReadLine(CancellationToken cancellationToken) => _readLineProvider.ReadLine.ReadLine(cancellationToken); private void InvokeInput(string input, CancellationToken cancellationToken) { - var command = new PSCommand().AddScript(input, useLocalScope: false); + PSCommand command = new PSCommand().AddScript(input, useLocalScope: false); InvokePSCommand(command, new PowerShellExecutionOptions { AddToHistory = true, ThrowOnError = false, WriteOutputToHost = true }, cancellationToken); } @@ -734,14 +722,14 @@ private static PowerShell CreateNestedPowerShell(RunspaceInfo currentRunspace) // PowerShell.CreateNestedPowerShell() sets IsNested but not IsChild // This means it throws due to the parent pipeline not running... // So we must use the RunspaceMode.CurrentRunspace option on PowerShell.Create() instead - var pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace); + PowerShell pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace); pwsh.Runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; return pwsh; } private static PowerShell CreatePowerShellForRunspace(Runspace runspace) { - var pwsh = PowerShell.Create(); + PowerShell pwsh = PowerShell.Create(); pwsh.Runspace = runspace; return pwsh; } @@ -753,7 +741,7 @@ private static PowerShell CreatePowerShellForRunspace(Runspace runspace) Runspace runspace = CreateInitialRunspace(hostStartupInfo.InitialSessionState); PowerShell pwsh = CreatePowerShellForRunspace(runspace); - var engineIntrinsics = (EngineIntrinsics)runspace.SessionStateProxy.GetVariable("ExecutionContext"); + EngineIntrinsics engineIntrinsics = (EngineIntrinsics)runspace.SessionStateProxy.GetVariable("ExecutionContext"); if (hostStartupInfo.ConsoleReplEnabled) { @@ -928,10 +916,7 @@ private void OnDebuggerStopped(object sender, DebuggerStopEventArgs debuggerStop } } - private void OnBreakpointUpdated(object sender, BreakpointUpdatedEventArgs breakpointUpdatedEventArgs) - { - DebugContext.HandleBreakpointUpdated(breakpointUpdatedEventArgs); - } + private void OnBreakpointUpdated(object sender, BreakpointUpdatedEventArgs breakpointUpdatedEventArgs) => DebugContext.HandleBreakpointUpdated(breakpointUpdatedEventArgs); private void OnRunspaceStateChanged(object sender, RunspaceStateEventArgs runspaceStateEventArgs) { @@ -991,7 +976,7 @@ internal bool TryLoadPSReadLine(PowerShell pwsh, EngineIntrinsics engineIntrinsi psrlReadLine = null; try { - var psrlProxy = PSReadLineProxy.LoadAndCreate(_loggerFactory, s_bundledModulePath, pwsh); + PSReadLineProxy psrlProxy = PSReadLineProxy.LoadAndCreate(_loggerFactory, s_bundledModulePath, pwsh); psrlReadLine = new PsrlReadLine(psrlProxy, this, engineIntrinsics, ReadKey, OnPowerShellIdle); return true; } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceChangedEventArgs.cs b/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceChangedEventArgs.cs index 5d889ba1c..19bbf6911 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceChangedEventArgs.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceChangedEventArgs.cs @@ -44,9 +44,9 @@ public RunspaceChangedEventArgs( { Validate.IsNotNull(nameof(previousRunspace), previousRunspace); - this.ChangeAction = changeAction; - this.PreviousRunspace = previousRunspace; - this.NewRunspace = newRunspace; + ChangeAction = changeAction; + PreviousRunspace = previousRunspace; + NewRunspace = newRunspace; } /// diff --git a/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceInfo.cs b/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceInfo.cs index c9b4d247c..60b542b55 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceInfo.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceInfo.cs @@ -20,8 +20,8 @@ public static RunspaceInfo CreateFromLocalPowerShell( ILogger logger, PowerShell pwsh) { - var psVersionDetails = PowerShellVersionDetails.GetVersionDetails(logger, pwsh); - var sessionDetails = SessionDetails.GetFromPowerShell(pwsh); + PowerShellVersionDetails psVersionDetails = PowerShellVersionDetails.GetVersionDetails(logger, pwsh); + SessionDetails sessionDetails = SessionDetails.GetFromPowerShell(pwsh); return new RunspaceInfo( pwsh.Runspace, @@ -36,8 +36,8 @@ public static RunspaceInfo CreateFromPowerShell( PowerShell pwsh, string localComputerName) { - var psVersionDetails = PowerShellVersionDetails.GetVersionDetails(logger, pwsh); - var sessionDetails = SessionDetails.GetFromPowerShell(pwsh); + PowerShellVersionDetails psVersionDetails = PowerShellVersionDetails.GetVersionDetails(logger, pwsh); + SessionDetails sessionDetails = SessionDetails.GetFromPowerShell(pwsh); bool isOnLocalMachine = string.Equals(sessionDetails.ComputerName, localComputerName, StringComparison.OrdinalIgnoreCase) || string.Equals(sessionDetails.ComputerName, "localhost", StringComparison.OrdinalIgnoreCase); diff --git a/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceOrigin.cs b/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceOrigin.cs index b91faf020..875001ef6 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceOrigin.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Runspace/RunspaceOrigin.cs @@ -1,7 +1,5 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Runspace { diff --git a/src/PowerShellEditorServices/Services/PowerShell/Utility/CancellationContext.cs b/src/PowerShellEditorServices/Services/PowerShell/Utility/CancellationContext.cs index 8503b2065..daee301ba 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Utility/CancellationContext.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Utility/CancellationContext.cs @@ -14,8 +14,8 @@ namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility /// Implicitly handles the merging and cleanup of cancellation token sources. /// /// - /// The class - /// and the struct + /// The class + /// and the struct /// are intended to be used with a using block so you can do this: /// /// using (CancellationScope cancellationScope = _cancellationContext.EnterScope(_globalCancellationSource.CancellationToken, localCancellationToken)) @@ -28,10 +28,7 @@ internal class CancellationContext { private readonly ConcurrentStack _cancellationSourceStack; - public CancellationContext() - { - _cancellationSourceStack = new ConcurrentStack(); - } + public CancellationContext() => _cancellationSourceStack = new ConcurrentStack(); public CancellationScope EnterScope(bool isIdleScope, CancellationToken cancellationToken) { @@ -82,7 +79,7 @@ public void CancelIdleParentTask() private CancellationScope EnterScope(bool isIdleScope, CancellationTokenSource cancellationFrameSource) { - var scope = new CancellationScope(_cancellationSourceStack, cancellationFrameSource, isIdleScope); + CancellationScope scope = new(_cancellationSourceStack, cancellationFrameSource, isIdleScope); _cancellationSourceStack.Push(scope); return scope; } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Utility/CommandHelpers.cs b/src/PowerShellEditorServices/Services/PowerShell/Utility/CommandHelpers.cs index d65503167..4495ebf63 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Utility/CommandHelpers.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Utility/CommandHelpers.cs @@ -19,35 +19,35 @@ internal static class CommandHelpers { private static readonly HashSet s_nounExclusionList = new() { - // PowerShellGet v2 nouns - "CredsFromCredentialProvider", - "DscResource", - "InstalledModule", - "InstalledScript", - "PSRepository", - "RoleCapability", - "Script", - "ScriptFileInfo", - - // PackageManagement nouns - "Package", - "PackageProvider", - "PackageSource", - }; + // PowerShellGet v2 nouns + "CredsFromCredentialProvider", + "DscResource", + "InstalledModule", + "InstalledScript", + "PSRepository", + "RoleCapability", + "Script", + "ScriptFileInfo", + + // PackageManagement nouns + "Package", + "PackageProvider", + "PackageSource", + }; // This is used when a noun exists in multiple modules (for example, "Command" is used in Microsoft.PowerShell.Core and also PowerShellGet) private static readonly HashSet s_cmdletExclusionList = new() { - // Commands in PowerShellGet with conflicting nouns - "Find-Command", - "Find-Module", - "Install-Module", - "Publish-Module", - "Save-Module", - "Uninstall-Module", - "Update-Module", - "Update-ModuleManifest", - }; + // Commands in PowerShellGet with conflicting nouns + "Find-Command", + "Find-Module", + "Install-Module", + "Publish-Module", + "Save-Module", + "Uninstall-Module", + "Update-Module", + "Update-ModuleManifest", + }; private static readonly ConcurrentDictionary s_commandInfoCache = new(); private static readonly ConcurrentDictionary s_synopsisCache = new(); @@ -86,7 +86,7 @@ public static async Task GetCommandInfoAsync( // This is currently necessary to make sure that Get-Command doesn't // load PackageManagement or PowerShellGet v2 because they cause // a major slowdown in IntelliSense. - var commandParts = commandName.Split('-'); + string[] commandParts = commandName.Split('-'); if ((commandParts.Length == 2 && s_nounExclusionList.Contains(commandParts[1])) || s_cmdletExclusionList.Contains(commandName)) { @@ -128,9 +128,9 @@ public static async Task GetCommandSynopsisAsync( Validate.IsNotNull(nameof(executionService), executionService); // A small optimization to not run Get-Help on things like DSC resources. - if (commandInfo.CommandType != CommandTypes.Cmdlet && - commandInfo.CommandType != CommandTypes.Function && - commandInfo.CommandType != CommandTypes.Filter) + if (commandInfo.CommandType is not CommandTypes.Cmdlet and + not CommandTypes.Function and + not CommandTypes.Filter) { return string.Empty; } @@ -183,7 +183,7 @@ public static async Task GetCommandSynopsisAsync( { Validate.IsNotNull(nameof(executionService), executionService); - IEnumerable aliases = await executionService.ExecuteDelegateAsync>( + IEnumerable aliases = await executionService.ExecuteDelegateAsync( nameof(GetAliasesAsync), executionOptions: null, (pwsh, _) => diff --git a/src/PowerShellEditorServices/Services/PowerShell/Utility/ErrorRecordExtensions.cs b/src/PowerShellEditorServices/Services/PowerShell/Utility/ErrorRecordExtensions.cs index 41721dc12..e52675061 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Utility/ErrorRecordExtensions.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Utility/ErrorRecordExtensions.cs @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility { internal static class ErrorRecordExtensions { - private static Action s_setWriteStreamProperty = null; + private static readonly Action s_setWriteStreamProperty = null; [SuppressMessage("Performance", "CA1810:Initialize reference type static fields inline", Justification = "cctor needed for version specific initialization")] static ErrorRecordExtensions() @@ -25,7 +25,7 @@ static ErrorRecordExtensions() Type writeStreamType = typeof(PSObject).Assembly.GetType("System.Management.Automation.WriteStreamType"); object errorStreamType = Enum.Parse(writeStreamType, "Error"); - var errorObjectParameter = Expression.Parameter(typeof(PSObject)); + ParameterExpression errorObjectParameter = Expression.Parameter(typeof(PSObject)); // Generates a call like: // $errorPSObject.WriteStream = [System.Management.Automation.WriteStreamType]::Error @@ -43,7 +43,7 @@ static ErrorRecordExtensions() public static PSObject AsPSObject(this ErrorRecord errorRecord) { - var errorObject = PSObject.AsPSObject(errorRecord); + PSObject errorObject = PSObject.AsPSObject(errorRecord); // Used to write ErrorRecords to the Error stream so they are rendered in the console correctly. if (s_setWriteStreamProperty != null) @@ -52,7 +52,7 @@ public static PSObject AsPSObject(this ErrorRecord errorRecord) } else { - var note = new PSNoteProperty("writeErrorStream", true); + PSNoteProperty note = new("writeErrorStream", true); errorObject.Properties.Add(note); } diff --git a/src/PowerShellEditorServices/Services/PowerShell/Utility/PowerShellExtensions.cs b/src/PowerShellEditorServices/Services/PowerShell/Utility/PowerShellExtensions.cs index aa6684b4d..a34032a89 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Utility/PowerShellExtensions.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Utility/PowerShellExtensions.cs @@ -124,14 +124,14 @@ public static void SetCorrectExecutionPolicy(this PowerShell pwsh, ILogger logge // set to expected values, so we must sift through those. ExecutionPolicy policyToSet = ExecutionPolicy.Bypass; - var currentUserPolicy = (ExecutionPolicy)policies[policies.Count - 2].Members["ExecutionPolicy"].Value; + ExecutionPolicy currentUserPolicy = (ExecutionPolicy)policies[policies.Count - 2].Members["ExecutionPolicy"].Value; if (currentUserPolicy != ExecutionPolicy.Undefined) { policyToSet = currentUserPolicy; } else { - var localMachinePolicy = (ExecutionPolicy)policies[policies.Count - 1].Members["ExecutionPolicy"].Value; + ExecutionPolicy localMachinePolicy = (ExecutionPolicy)policies[policies.Count - 1].Members["ExecutionPolicy"].Value; if (localMachinePolicy != ExecutionPolicy.Undefined) { policyToSet = localMachinePolicy; @@ -168,9 +168,9 @@ public static void LoadProfiles(this PowerShell pwsh, ProfilePathInfo profilePat // `$PROFILE` variable. Its type is `String`. // // https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles?view=powershell-7.1#the-profile-variable - var profileVariable = PSObject.AsPSObject(profilePaths.CurrentUserCurrentHost); + PSObject profileVariable = PSObject.AsPSObject(profilePaths.CurrentUserCurrentHost); - var psCommand = new PSCommand() + PSCommand psCommand = new PSCommand() .AddProfileLoadIfExists(profileVariable, nameof(profilePaths.AllUsersAllHosts), profilePaths.AllUsersAllHosts) .AddProfileLoadIfExists(profileVariable, nameof(profilePaths.AllUsersCurrentHost), profilePaths.AllUsersCurrentHost) .AddProfileLoadIfExists(profileVariable, nameof(profilePaths.CurrentUserAllHosts), profilePaths.CurrentUserAllHosts) @@ -191,7 +191,7 @@ public static void ImportModule(this PowerShell pwsh, string moduleNameOrPath) public static string GetErrorString(this PowerShell pwsh) { - var sb = new StringBuilder(capacity: 1024) + StringBuilder sb = new StringBuilder(capacity: 1024) .Append("Execution of the following command(s) completed with errors:") .AppendLine() .AppendLine() diff --git a/src/PowerShellEditorServices/Services/PowerShell/Utility/RunspaceExtensions.cs b/src/PowerShellEditorServices/Services/PowerShell/Utility/RunspaceExtensions.cs index 0a5076e57..681e16d8f 100644 --- a/src/PowerShellEditorServices/Services/PowerShell/Utility/RunspaceExtensions.cs +++ b/src/PowerShellEditorServices/Services/PowerShell/Utility/RunspaceExtensions.cs @@ -39,10 +39,7 @@ static RunspaceExtensions() new ParameterExpression[] { runspaceParam, basePromptParam }).Compile(); } - public static void SetApartmentStateToSta(this Runspace runspace) - { - s_runspaceApartmentStateSetter?.Invoke(runspace, ApartmentState.STA); - } + public static void SetApartmentStateToSta(this Runspace runspace) => s_runspaceApartmentStateSetter?.Invoke(runspace, ApartmentState.STA); /// /// Augment a given prompt string with a remote decoration. @@ -51,25 +48,15 @@ public static void SetApartmentStateToSta(this Runspace runspace) /// The runspace the prompt is for. /// The base prompt to decorate. /// A prompt string decorated with remote connection details. - public static string GetRemotePrompt(this Runspace runspace, string basePrompt) - { - return s_getRemotePromptFunc(runspace, basePrompt); - } + public static string GetRemotePrompt(this Runspace runspace, string basePrompt) => s_getRemotePromptFunc(runspace, basePrompt); public static bool IsUsable(this RunspaceStateInfo runspaceStateInfo) { - switch (runspaceStateInfo.State) + return runspaceStateInfo.State switch { - case RunspaceState.Broken: - case RunspaceState.Closed: - case RunspaceState.Closing: - case RunspaceState.Disconnecting: - case RunspaceState.Disconnected: - return false; - - default: - return true; - } + RunspaceState.Broken or RunspaceState.Closed or RunspaceState.Closing or RunspaceState.Disconnecting or RunspaceState.Disconnected => false, + _ => true, + }; } } } diff --git a/src/PowerShellEditorServices/Services/Symbols/ParameterSetSignatures.cs b/src/PowerShellEditorServices/Services/Symbols/ParameterSetSignatures.cs index 48b812626..aa094ce7b 100644 --- a/src/PowerShellEditorServices/Services/Symbols/ParameterSetSignatures.cs +++ b/src/PowerShellEditorServices/Services/Symbols/ParameterSetSignatures.cs @@ -40,7 +40,7 @@ internal class ParameterSetSignatures /// The SymbolReference of the command public ParameterSetSignatures(IEnumerable commandInfoSet, SymbolReference foundSymbol) { - List paramSetSignatures = new List(); + List paramSetSignatures = new(); foreach (CommandParameterSetInfo setInfo in commandInfoSet) { paramSetSignatures.Add(new ParameterSetSignature(setInfo)); @@ -57,7 +57,7 @@ public ParameterSetSignatures(IEnumerable commandInfoSe internal class ParameterSetSignature { private static readonly ConcurrentDictionary commonParameterNames = - new ConcurrentDictionary(); + new(); static ParameterSetSignature() { @@ -92,7 +92,7 @@ static ParameterSetSignature() /// Collection of parameter info public ParameterSetSignature(CommandParameterSetInfo commandParamInfoSet) { - List parameterInfo = new List(); + List parameterInfo = new(); foreach (CommandParameterInfo commandParameterInfo in commandParamInfoSet.Parameters) { if (!commonParameterNames.ContainsKey(commandParameterInfo.Name)) @@ -144,11 +144,11 @@ internal class ParameterInfo /// Parameter info of the parameter public ParameterInfo(CommandParameterInfo parameterInfo) { - this.Name = "-" + parameterInfo.Name; - this.ParameterType = parameterInfo.ParameterType.FullName; - this.Position = parameterInfo.Position; - this.IsMandatory = parameterInfo.IsMandatory; - this.HelpMessage = parameterInfo.HelpMessage; + Name = "-" + parameterInfo.Name; + ParameterType = parameterInfo.ParameterType.FullName; + Position = parameterInfo.Position; + IsMandatory = parameterInfo.IsMandatory; + HelpMessage = parameterInfo.HelpMessage; } } } diff --git a/src/PowerShellEditorServices/Services/Symbols/PesterDocumentSymbolProvider.cs b/src/PowerShellEditorServices/Services/Symbols/PesterDocumentSymbolProvider.cs index 95e383d00..3b1e8a87a 100644 --- a/src/PowerShellEditorServices/Services/Symbols/PesterDocumentSymbolProvider.cs +++ b/src/PowerShellEditorServices/Services/Symbols/PesterDocumentSymbolProvider.cs @@ -42,9 +42,7 @@ IEnumerable IDocumentSymbolProvider.ProvideDocumentSymbols( /// true if the Ast represents a PowerShell command with arguments, false otherwise private static bool IsNamedCommandWithArguments(Ast ast) { - CommandAst commandAst = ast as CommandAst; - - return commandAst != null && + return ast is CommandAst commandAst && commandAst.InvocationOperator != TokenKind.Dot && PesterSymbolReference.GetCommandType(commandAst.GetCommandName()).HasValue && commandAst.CommandElements.Count >= 2; @@ -69,7 +67,7 @@ private static bool IsPesterCommand(CommandAst commandAst) } // Ensure that the last argument of the command is a scriptblock - if (!(commandAst.CommandElements[commandAst.CommandElements.Count-1] is ScriptBlockExpressionAst)) + if (commandAst.CommandElements[commandAst.CommandElements.Count - 1] is not ScriptBlockExpressionAst) { return false; } @@ -142,7 +140,7 @@ private static bool TryGetTestNameArgument(CommandElementAst commandElementAst, return true; } - return (commandElementAst is ExpandableStringExpressionAst); + return commandElementAst is ExpandableStringExpressionAst; } } @@ -181,7 +179,7 @@ internal class PesterSymbolReference : SymbolReference .Cast() .ToDictionary(pct => pct.ToString(), pct => pct, StringComparer.OrdinalIgnoreCase); - private static char[] DefinitionTrimChars = new char[] { ' ', '{' }; + private static readonly char[] DefinitionTrimChars = new char[] { ' ', '{' }; /// /// Gets the name of the test @@ -206,14 +204,13 @@ internal PesterSymbolReference( scriptFile.FilePath, testLine) { - this.Command = commandType; - this.TestName = testName; + Command = commandType; + TestName = testName; } internal static PesterCommandType? GetCommandType(string commandName) { - PesterCommandType pesterCommandType; - if (commandName == null || !PesterKeywords.TryGetValue(commandName, out pesterCommandType)) + if (commandName == null || !PesterKeywords.TryGetValue(commandName, out PesterCommandType pesterCommandType)) { return null; } diff --git a/src/PowerShellEditorServices/Services/Symbols/PsdDocumentSymbolProvider.cs b/src/PowerShellEditorServices/Services/Symbols/PsdDocumentSymbolProvider.cs index 174a4b3c9..fb2c3351c 100644 --- a/src/PowerShellEditorServices/Services/Symbols/PsdDocumentSymbolProvider.cs +++ b/src/PowerShellEditorServices/Services/Symbols/PsdDocumentSymbolProvider.cs @@ -24,7 +24,7 @@ IEnumerable IDocumentSymbolProvider.ProvideDocumentSymbols( scriptFile.FilePath.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase)) || IsPowerShellDataFileAst(scriptFile.ScriptAst)) { - var findHashtableSymbolsVisitor = new FindHashtableSymbolsVisitor(); + FindHashtableSymbolsVisitor findHashtableSymbolsVisitor = new(); scriptFile.ScriptAst.Visit(findHashtableSymbolsVisitor); return findHashtableSymbolsVisitor.SymbolReferences; } @@ -37,7 +37,7 @@ IEnumerable IDocumentSymbolProvider.ProvideDocumentSymbols( /// /// The abstract syntax tree of the given script /// true if the AST represts a *.psd1 file, otherwise false - static public bool IsPowerShellDataFileAst(Ast ast) + public static bool IsPowerShellDataFileAst(Ast ast) { // sometimes we don't have reliable access to the filename // so we employ heuristics to check if the contents are @@ -53,9 +53,9 @@ static public bool IsPowerShellDataFileAst(Ast ast) 0); } - static private bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap, int level) + private static bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap, int level) { - var levelAstTypeMatch = node.Item.GetType().Equals(levelAstMap[level]); + dynamic levelAstTypeMatch = node.Item.GetType().Equals(levelAstMap[level]); if (!levelAstTypeMatch) { return false; @@ -66,10 +66,10 @@ static private bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap return levelAstTypeMatch; } - var astsFound = (node.Item as Ast).FindAll(a => a is Ast, false); + IEnumerable astsFound = (node.Item as Ast).FindAll(a => a is Ast, false); if (astsFound != null) { - foreach (var astFound in astsFound) + foreach (Ast astFound in astsFound) { if (!astFound.Equals(node.Item) && node.Item.Equals(astFound.Parent) diff --git a/src/PowerShellEditorServices/Services/Symbols/ScriptDocumentSymbolProvider.cs b/src/PowerShellEditorServices/Services/Symbols/ScriptDocumentSymbolProvider.cs index 8399b943b..b721ee284 100644 --- a/src/PowerShellEditorServices/Services/Symbols/ScriptDocumentSymbolProvider.cs +++ b/src/PowerShellEditorServices/Services/Symbols/ScriptDocumentSymbolProvider.cs @@ -32,7 +32,7 @@ IEnumerable IDocumentSymbolProvider.ProvideDocumentSymbols( /// The abstract syntax tree of the given script /// The PowerShell version the Ast was generated from /// A collection of SymbolReference objects - static public IEnumerable FindSymbolsInDocument(Ast scriptAst) + public static IEnumerable FindSymbolsInDocument(Ast scriptAst) { IEnumerable symbolReferences = null; @@ -48,7 +48,7 @@ static public IEnumerable FindSymbolsInDocument(Ast scriptAst) // } // else - FindSymbolsVisitor findSymbolsVisitor = new FindSymbolsVisitor(); + FindSymbolsVisitor findSymbolsVisitor = new(); scriptAst.Visit(findSymbolsVisitor); symbolReferences = findSymbolsVisitor.SymbolReferences; return symbolReferences; diff --git a/src/PowerShellEditorServices/Services/Symbols/ScriptExtent.cs b/src/PowerShellEditorServices/Services/Symbols/ScriptExtent.cs index 7e8dc2bda..2224be725 100644 --- a/src/PowerShellEditorServices/Services/Symbols/ScriptExtent.cs +++ b/src/PowerShellEditorServices/Services/Symbols/ScriptExtent.cs @@ -54,10 +54,7 @@ public int StartOffset /// /// Gets or sets the starting script position of the extent. /// - public IScriptPosition StartScriptPosition - { - get { throw new NotImplementedException(); } - } + public IScriptPosition StartScriptPosition => throw new NotImplementedException(); /// /// Gets or sets the text that is contained within the extent. /// @@ -97,10 +94,7 @@ public int EndOffset /// /// Gets the ending script position of the extent. /// - public IScriptPosition EndScriptPosition - { - get { throw new NotImplementedException(); } - } + public IScriptPosition EndScriptPosition => throw new NotImplementedException(); #endregion } diff --git a/src/PowerShellEditorServices/Services/Symbols/SymbolDetails.cs b/src/PowerShellEditorServices/Services/Symbols/SymbolDetails.cs index 47b5e40a4..80a1dd8b4 100644 --- a/src/PowerShellEditorServices/Services/Symbols/SymbolDetails.cs +++ b/src/PowerShellEditorServices/Services/Symbols/SymbolDetails.cs @@ -43,7 +43,7 @@ internal static async Task CreateAsync( IRunspaceInfo currentRunspace, IInternalPowerShellExecutionService executionService) { - SymbolDetails symbolDetails = new SymbolDetails + SymbolDetails symbolDetails = new() { SymbolReference = symbolReference }; diff --git a/src/PowerShellEditorServices/Services/Symbols/SymbolReference.cs b/src/PowerShellEditorServices/Services/Symbols/SymbolReference.cs index b128fb668..ddaef21e0 100644 --- a/src/PowerShellEditorServices/Services/Symbols/SymbolReference.cs +++ b/src/PowerShellEditorServices/Services/Symbols/SymbolReference.cs @@ -86,11 +86,11 @@ public SymbolReference( string sourceLine = "") { // TODO: Verify params - this.SymbolType = symbolType; - this.SymbolName = symbolName; - this.ScriptRegion = ScriptRegion.Create(scriptExtent); - this.FilePath = filePath; - this.SourceLine = sourceLine; + SymbolType = symbolType; + SymbolName = symbolName; + ScriptRegion = ScriptRegion.Create(scriptExtent); + FilePath = filePath; + SourceLine = sourceLine; // TODO: Make sure end column number usage is correct diff --git a/src/PowerShellEditorServices/Services/Symbols/SymbolsService.cs b/src/PowerShellEditorServices/Services/Symbols/SymbolsService.cs index 1b3293972..96a997a17 100644 --- a/src/PowerShellEditorServices/Services/Symbols/SymbolsService.cs +++ b/src/PowerShellEditorServices/Services/Symbols/SymbolsService.cs @@ -65,7 +65,7 @@ public SymbolsService( _workspaceService = workspaceService; _codeLensProviders = new ConcurrentDictionary(); - var codeLensProviders = new ICodeLensProvider[] + ICodeLensProvider[] codeLensProviders = new ICodeLensProvider[] { new ReferencesCodeLensProvider(_workspaceService, this), new PesterCodeLensProvider(configurationService) @@ -77,7 +77,7 @@ public SymbolsService( } _documentSymbolProviders = new ConcurrentDictionary(); - var documentSymbolProviders = new IDocumentSymbolProvider[] + IDocumentSymbolProvider[] documentSymbolProviders = new IDocumentSymbolProvider[] { new ScriptDocumentSymbolProvider(), new PsdDocumentSymbolProvider(), @@ -91,35 +91,17 @@ public SymbolsService( #endregion - public bool TryResgisterCodeLensProvider(ICodeLensProvider codeLensProvider) - { - return _codeLensProviders.TryAdd(codeLensProvider.ProviderId, codeLensProvider); - } + public bool TryResgisterCodeLensProvider(ICodeLensProvider codeLensProvider) => _codeLensProviders.TryAdd(codeLensProvider.ProviderId, codeLensProvider); - public bool DeregisterCodeLensProvider(string providerId) - { - return _codeLensProviders.TryRemove(providerId, out _); - } + public bool DeregisterCodeLensProvider(string providerId) => _codeLensProviders.TryRemove(providerId, out _); - public IEnumerable GetCodeLensProviders() - { - return _codeLensProviders.Values; - } + public IEnumerable GetCodeLensProviders() => _codeLensProviders.Values; - public bool TryRegisterDocumentSymbolProvider(IDocumentSymbolProvider documentSymbolProvider) - { - return _documentSymbolProviders.TryAdd(documentSymbolProvider.ProviderId, documentSymbolProvider); - } + public bool TryRegisterDocumentSymbolProvider(IDocumentSymbolProvider documentSymbolProvider) => _documentSymbolProviders.TryAdd(documentSymbolProvider.ProviderId, documentSymbolProvider); - public bool DeregisterDocumentSymbolProvider(string providerId) - { - return _documentSymbolProviders.TryRemove(providerId, out _); - } + public bool DeregisterDocumentSymbolProvider(string providerId) => _documentSymbolProviders.TryRemove(providerId, out _); - public IEnumerable GetDocumentSymbolProviders() - { - return _documentSymbolProviders.Values; - } + public IEnumerable GetDocumentSymbolProviders() => _documentSymbolProviders.Values; /// /// Finds all the symbols in a file. @@ -130,7 +112,7 @@ public List FindSymbolsInFile(ScriptFile scriptFile) { Validate.IsNotNull(nameof(scriptFile), scriptFile); - var foundOccurrences = new List(); + List foundOccurrences = new(); foreach (IDocumentSymbolProvider symbolProvider in GetDocumentSymbolProviders()) { foreach (SymbolReference reference in symbolProvider.ProvideDocumentSymbols(scriptFile)) @@ -193,7 +175,7 @@ public async Task> FindReferencesOfSymbol( // We want to look for references first in referenced files, hence we use ordered dictionary // TODO: File system case-sensitivity is based on filesystem not OS, but OS is a much cheaper heuristic - var fileMap = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) + OrderedDictionary fileMap = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? new OrderedDictionary() : new OrderedDictionary(StringComparer.OrdinalIgnoreCase); @@ -216,10 +198,10 @@ public async Task> FindReferencesOfSymbol( } } - var symbolReferences = new List(); + List symbolReferences = new(); foreach (object fileName in fileMap.Keys) { - var file = (ScriptFile)fileMap[fileName]; + ScriptFile file = (ScriptFile)fileMap[fileName]; IEnumerable references = AstOperations.FindReferencesOfSymbol( file.ScriptAst, @@ -351,8 +333,8 @@ public async Task FindParameterSetsInFileAsync( // If we are not possibly looking at a Function, we don't // need to continue because we won't be able to get the // CommandInfo object. - if (foundSymbol?.SymbolType != SymbolType.Function - && foundSymbol?.SymbolType != SymbolType.Unknown) + if (foundSymbol?.SymbolType is not SymbolType.Function + and not SymbolType.Unknown) { return null; } @@ -423,7 +405,7 @@ public async Task GetDefinitionOfSymbolAsync( _workspaceService.ExpandScriptReferences( sourceFile); - var filesSearched = new HashSet(StringComparer.OrdinalIgnoreCase); + HashSet filesSearched = new(StringComparer.OrdinalIgnoreCase); // look through the referenced files until definition is found // or there are no more file to look through diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs index a0cc38ac4..13e5aee97 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/AstOperations.cs @@ -33,7 +33,7 @@ static AstOperations() ParameterExpression originalPosition = Expression.Parameter(typeof(IScriptPosition)); ParameterExpression newOffset = Expression.Parameter(typeof(int)); - var parameters = new ParameterExpression[] { originalPosition, newOffset }; + ParameterExpression[] parameters = new ParameterExpression[] { originalPosition, newOffset }; s_clonePositionWithNewOffset = Expression.Lambda>( Expression.Call( Expression.Convert(originalPosition, internalScriptPositionType), @@ -83,7 +83,7 @@ public static async Task GetCompletionsAsync( cursorPosition.LineNumber, cursorPosition.ColumnNumber)); - var stopwatch = new Stopwatch(); + Stopwatch stopwatch = new(); CommandCompletion commandCompletion = null; await executionService.ExecuteDelegateAsync( @@ -123,7 +123,7 @@ public static SymbolReference FindSymbolAtPosition( bool includeFunctionDefinitions = false) { FindSymbolVisitor symbolVisitor = - new FindSymbolVisitor( + new( lineNumber, columnNumber, includeFunctionDefinitions); @@ -142,7 +142,7 @@ public static SymbolReference FindSymbolAtPosition( /// SymbolReference of found command public static SymbolReference FindCommandAtPosition(Ast scriptAst, int lineNumber, int columnNumber) { - FindCommandVisitor commandVisitor = new FindCommandVisitor(lineNumber, columnNumber); + FindCommandVisitor commandVisitor = new(lineNumber, columnNumber); scriptAst.Visit(commandVisitor); return commandVisitor.FoundCommandReference; @@ -184,7 +184,7 @@ public static SymbolReference FindDefinitionOfSymbol( SymbolReference symbolReference) { FindDeclarationVisitor declarationVisitor = - new FindDeclarationVisitor( + new( symbolReference); scriptAst.Visit(declarationVisitor); @@ -213,7 +213,7 @@ public static IEnumerable FindSymbolsInDocument(Ast scriptAst, // } // else - FindSymbolsVisitor findSymbolsVisitor = new FindSymbolsVisitor(); + FindSymbolsVisitor findSymbolsVisitor = new(); scriptAst.Visit(findSymbolsVisitor); symbolReferences = findSymbolsVisitor.SymbolReferences; return symbolReferences; @@ -240,9 +240,9 @@ public static bool IsPowerShellDataFileAst(Ast ast) 0); } - static private bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap, int level) + private static bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap, int level) { - var levelAstTypeMatch = node.Item.GetType().Equals(levelAstMap[level]); + dynamic levelAstTypeMatch = node.Item.GetType().Equals(levelAstMap[level]); if (!levelAstTypeMatch) { return false; @@ -253,10 +253,10 @@ static private bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap return levelAstTypeMatch; } - var astsFound = (node.Item as Ast).FindAll(a => a is Ast, false); + IEnumerable astsFound = (node.Item as Ast).FindAll(a => a is Ast, false); if (astsFound != null) { - foreach (var astFound in astsFound) + foreach (Ast astFound in astsFound) { if (!astFound.Equals(node.Item) && node.Item.Equals(astFound.Parent) @@ -281,7 +281,7 @@ static private bool IsPowerShellDataFileAstNode(dynamic node, Type[] levelAstMap /// public static string[] FindDotSourcedIncludes(Ast scriptAst, string psScriptRoot) { - FindDotSourcedVisitor dotSourcedVisitor = new FindDotSourcedVisitor(psScriptRoot); + FindDotSourcedVisitor dotSourcedVisitor = new(psScriptRoot); scriptAst.Visit(dotSourcedVisitor); return dotSourcedVisitor.DotSourcedFiles.ToArray(); diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindCommandVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindCommandVisitor.cs index 26f2a1d00..4a7b78faa 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindCommandVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindCommandVisitor.cs @@ -24,10 +24,10 @@ public FindCommandVisitor(int lineNumber, int columnNumber) public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) { - if (this.lineNumber == pipelineAst.Extent.StartLineNumber) + if (lineNumber == pipelineAst.Extent.StartLineNumber) { // Which command is the cursor in? - foreach (var commandAst in pipelineAst.PipelineElements.OfType()) + foreach (CommandAst commandAst in pipelineAst.PipelineElements.OfType()) { int trueEndColumnNumber = commandAst.Extent.EndColumnNumber; string currentLine = commandAst.Extent.StartScriptPosition.Line; @@ -54,7 +54,7 @@ public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) if (commandAst.Extent.StartColumnNumber <= columnNumber && trueEndColumnNumber >= columnNumber) { - this.FoundCommandReference = + FoundCommandReference = new SymbolReference( SymbolType.Function, commandAst.CommandElements[0].Extent); @@ -66,20 +66,5 @@ public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) return base.VisitPipeline(pipelineAst); } - - /// - /// Is the position of the given location is in the range of the start - /// of the first element to the character before the second element - /// - /// The script extent of the first element of the command ast - /// The script extent of the second element of the command ast - /// True if the given position is in the range of the start of - /// the first element to the character before the second element - private bool IsPositionInExtent(IScriptExtent firstExtent, IScriptExtent secondExtent) - { - return (firstExtent.StartLineNumber == lineNumber && - firstExtent.StartColumnNumber <= columnNumber && - secondExtent.StartColumnNumber >= columnNumber - 1); - } } } diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDeclarationVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDeclarationVisitor.cs index d48d17ab9..5c3071451 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDeclarationVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDeclarationVisitor.cs @@ -11,10 +11,10 @@ namespace Microsoft.PowerShell.EditorServices.Services.Symbols /// internal class FindDeclarationVisitor : AstVisitor { - private SymbolReference symbolRef; - private string variableName; + private readonly SymbolReference symbolRef; + private readonly string variableName; - public SymbolReference FoundDeclaration{ get; private set; } + public SymbolReference FoundDeclaration { get; private set; } public FindDeclarationVisitor(SymbolReference symbolRef) { @@ -57,7 +57,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun if (symbolRef.SymbolType.Equals(SymbolType.Function) && nameExtent.Text.Equals(symbolRef.SymbolName, StringComparison.CurrentCultureIgnoreCase)) { - this.FoundDeclaration = + FoundDeclaration = new SymbolReference( SymbolType.Function, nameExtent); @@ -83,7 +83,7 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a } // We want to check VariableExpressionAsts from within this AssignmentStatementAst so we visit it. - FindDeclarationVariableExpressionVisitor visitor = new FindDeclarationVariableExpressionVisitor(symbolRef); + FindDeclarationVariableExpressionVisitor visitor = new(symbolRef); assignmentStatementAst.Left.Visit(visitor); if (visitor.FoundDeclaration != null) @@ -99,10 +99,10 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a /// private class FindDeclarationVariableExpressionVisitor : AstVisitor { - private SymbolReference symbolRef; - private string variableName; + private readonly SymbolReference symbolRef; + private readonly string variableName; - public SymbolReference FoundDeclaration{ get; private set; } + public SymbolReference FoundDeclaration { get; private set; } public FindDeclarationVariableExpressionVisitor(SymbolReference symbolRef) { @@ -131,17 +131,13 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var return AstVisitAction.Continue; } - public override AstVisitAction VisitMemberExpression(MemberExpressionAst functionDefinitionAst) - { + public override AstVisitAction VisitMemberExpression(MemberExpressionAst functionDefinitionAst) => // We don't want to discover any variables in member expressisons (`$something.Foo`) - return AstVisitAction.SkipChildren; - } + AstVisitAction.SkipChildren; - public override AstVisitAction VisitIndexExpression(IndexExpressionAst functionDefinitionAst) - { + public override AstVisitAction VisitIndexExpression(IndexExpressionAst functionDefinitionAst) => // We don't want to discover any variables in index expressions (`$something[0]`) - return AstVisitAction.SkipChildren; - } + AstVisitAction.SkipChildren; } } } diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDotSourcedVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDotSourcedVisitor.cs index 5e3fe0a6c..1dff46772 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDotSourcedVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindDotSourcedVisitor.cs @@ -42,22 +42,12 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) CommandElementAst commandElementAst = commandAst.CommandElements[0]; if (commandAst.InvocationOperator.Equals(TokenKind.Dot)) { - string path; - switch (commandElementAst) + string path = commandElementAst switch { - case StringConstantExpressionAst stringConstantExpressionAst: - path = stringConstantExpressionAst.Value; - break; - - case ExpandableStringExpressionAst expandableStringExpressionAst: - path = GetPathFromExpandableStringExpression(expandableStringExpressionAst); - break; - - default: - path = null; - break; - } - + StringConstantExpressionAst stringConstantExpressionAst => stringConstantExpressionAst.Value, + ExpandableStringExpressionAst expandableStringExpressionAst => GetPathFromExpandableStringExpression(expandableStringExpressionAst), + _ => null, + }; if (!string.IsNullOrWhiteSpace(path)) { DotSourcedFiles.Add(PathUtils.NormalizePathSeparators(path)); @@ -69,8 +59,8 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) private string GetPathFromExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { - var path = expandableStringExpressionAst.Value; - foreach (var nestedExpression in expandableStringExpressionAst.NestedExpressions) + string path = expandableStringExpressionAst.Value; + foreach (ExpressionAst nestedExpression in expandableStringExpressionAst.NestedExpressions) { // If the string contains the variable $PSScriptRoot, we replace it with the corresponding value. if (!(nestedExpression is VariableExpressionAst variableAst diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindReferencesVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindReferencesVisitor.cs index 7dae792a7..0dcbe7e0d 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindReferencesVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindReferencesVisitor.cs @@ -173,21 +173,7 @@ private static (int, int) GetStartColumnAndLineNumbersFromAst(FunctionDefinition { int startColumnNumber = ast.Extent.StartColumnNumber; int startLineNumber = ast.Extent.StartLineNumber; - int astOffset; - - if (ast.IsFilter) - { - astOffset = "filter".Length; - } - else if (ast.IsWorkflow) - { - astOffset = "workflow".Length; - } - else - { - astOffset = "function".Length; - } - + int astOffset = ast.IsFilter ? "filter".Length : ast.IsWorkflow ? "workflow".Length : "function".Length; string astText = ast.Extent.Text; // The line offset represents the offset on the line that we're on where as // astOffset is the offset on the entire text of the AST. diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolVisitor.cs index 85b6f41bb..4ded34190 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolVisitor.cs @@ -10,9 +10,9 @@ namespace Microsoft.PowerShell.EditorServices.Services.Symbols /// internal class FindSymbolVisitor : AstVisitor { - private int lineNumber; - private int columnNumber; - private bool includeFunctionDefinitions; + private readonly int lineNumber; + private readonly int columnNumber; + private readonly bool includeFunctionDefinitions; public SymbolReference FoundSymbolReference { get; private set; } @@ -36,9 +36,9 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) { Ast commandNameAst = commandAst.CommandElements[0]; - if (this.IsPositionInExtent(commandNameAst.Extent)) + if (IsPositionInExtent(commandNameAst.Extent)) { - this.FoundSymbolReference = + FoundSymbolReference = new SymbolReference( SymbolType.Function, commandNameAst.Extent); @@ -59,7 +59,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun { int startColumnNumber = 1; - if (!this.includeFunctionDefinitions) + if (!includeFunctionDefinitions) { startColumnNumber = functionDefinitionAst.Extent.Text.IndexOf( @@ -76,9 +76,9 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun File = functionDefinitionAst.Extent.File }; - if (this.IsPositionInExtent(nameExtent)) + if (IsPositionInExtent(nameExtent)) { - this.FoundSymbolReference = + FoundSymbolReference = new SymbolReference( SymbolType.Function, nameExtent); @@ -97,9 +97,9 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun /// or a decision to continue if it wasn't found public override AstVisitAction VisitCommandParameter(CommandParameterAst commandParameterAst) { - if (this.IsPositionInExtent(commandParameterAst.Extent)) + if (IsPositionInExtent(commandParameterAst.Extent)) { - this.FoundSymbolReference = + FoundSymbolReference = new SymbolReference( SymbolType.Parameter, commandParameterAst.Extent); @@ -116,9 +116,9 @@ public override AstVisitAction VisitCommandParameter(CommandParameterAst command /// or a decision to continue if it wasn't found public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) { - if (this.IsPositionInExtent(variableExpressionAst.Extent)) + if (IsPositionInExtent(variableExpressionAst.Extent)) { - this.FoundSymbolReference = + FoundSymbolReference = new SymbolReference( SymbolType.Variable, variableExpressionAst.Extent); @@ -136,9 +136,9 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var /// True if the given position is in the range of the element's extent private bool IsPositionInExtent(IScriptExtent extent) { - return (extent.StartLineNumber == lineNumber && + return extent.StartLineNumber == lineNumber && extent.StartColumnNumber <= columnNumber && - extent.EndColumnNumber >= columnNumber); + extent.EndColumnNumber >= columnNumber; } } } diff --git a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor.cs b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor.cs index e0c10e5a2..d37299aab 100644 --- a/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor.cs +++ b/src/PowerShellEditorServices/Services/Symbols/Vistors/FindSymbolsVisitor.cs @@ -16,10 +16,7 @@ internal class FindSymbolsVisitor : AstVisitor { public List SymbolReferences { get; private set; } - public FindSymbolsVisitor() - { - this.SymbolReferences = new List(); - } + public FindSymbolsVisitor() => SymbolReferences = new List(); /// /// Adds each function definition as a @@ -29,7 +26,8 @@ public FindSymbolsVisitor() /// or a decision to continue if it wasn't found public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { - IScriptExtent nameExtent = new ScriptExtent() { + IScriptExtent nameExtent = new ScriptExtent() + { Text = functionDefinitionAst.Name, StartLineNumber = functionDefinitionAst.Extent.StartLineNumber, EndLineNumber = functionDefinitionAst.Extent.EndLineNumber, @@ -42,7 +40,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun functionDefinitionAst.IsWorkflow ? SymbolType.Workflow : SymbolType.Function; - this.SymbolReferences.Add( + SymbolReferences.Add( new SymbolReference( symbolType, nameExtent)); @@ -63,7 +61,7 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var return AstVisitAction.Continue; } - this.SymbolReferences.Add( + SymbolReferences.Add( new SymbolReference( SymbolType.Variable, variableExpressionAst.Extent)); @@ -74,7 +72,7 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var private static bool IsAssignedAtScriptScope(VariableExpressionAst variableExpressionAst) { Ast parent = variableExpressionAst.Parent; - if (!(parent is AssignmentStatementAst)) + if (parent is not AssignmentStatementAst) { return false; } @@ -102,10 +100,7 @@ internal class FindHashtableSymbolsVisitor : AstVisitor /// /// Initializes a new instance of FindHashtableSymbolsVisitor class /// - public FindHashtableSymbolsVisitor() - { - SymbolReferences = new List(); - } + public FindHashtableSymbolsVisitor() => SymbolReferences = new List(); /// /// Adds keys in the input hashtable to the symbol reference @@ -117,7 +112,7 @@ public override AstVisitAction VisitHashtable(HashtableAst hashtableAst) return AstVisitAction.Continue; } - foreach (var kvp in hashtableAst.KeyValuePairs) + foreach (System.Tuple kvp in hashtableAst.KeyValuePairs) { if (kvp.Item1 is StringConstantExpressionAst keyStrConstExprAst) { @@ -133,7 +128,7 @@ public override AstVisitAction VisitHashtable(HashtableAst hashtableAst) SymbolType symbolType = SymbolType.HashtableKey; - this.SymbolReferences.Add( + SymbolReferences.Add( new SymbolReference( symbolType, nameExtent)); diff --git a/src/PowerShellEditorServices/Services/Template/Handlers/TemplateHandlers.cs b/src/PowerShellEditorServices/Services/Template/Handlers/TemplateHandlers.cs index 57f7552ce..96ce93b12 100644 --- a/src/PowerShellEditorServices/Services/Template/Handlers/TemplateHandlers.cs +++ b/src/PowerShellEditorServices/Services/Template/Handlers/TemplateHandlers.cs @@ -28,7 +28,7 @@ public async Task Handle(GetProjectTemplatesRequest if (plasterInstalled) { - var availableTemplates = + TemplateDetails[] availableTemplates = await _templateService.GetAvailableTemplatesAsync( request.IncludeInstalledModules).ConfigureAwait(false); diff --git a/src/PowerShellEditorServices/Services/Template/TemplateService.cs b/src/PowerShellEditorServices/Services/Template/TemplateService.cs index a3c416190..c046ab51c 100644 --- a/src/PowerShellEditorServices/Services/Template/TemplateService.cs +++ b/src/PowerShellEditorServices/Services/Template/TemplateService.cs @@ -52,9 +52,9 @@ public TemplateService(IInternalPowerShellExecutionService executionService, ILo /// A Task that can be awaited until the check is complete. The result will be true if Plaster is installed. public async Task ImportPlasterIfInstalledAsync() { - if (!this.isPlasterInstalled.HasValue) + if (!isPlasterInstalled.HasValue) { - PSCommand psCommand = new PSCommand(); + PSCommand psCommand = new(); psCommand .AddCommand("Get-Module") @@ -70,21 +70,21 @@ public async Task ImportPlasterIfInstalledAsync() .AddCommand("Select-Object") .AddParameter("First", 1); - this._logger.LogTrace("Checking if Plaster is installed..."); + _logger.LogTrace("Checking if Plaster is installed..."); - PSObject moduleObject = (await _executionService.ExecutePSCommandAsync(psCommand, CancellationToken.None).ConfigureAwait(false)).First(); + PSObject moduleObject = (await _executionService.ExecutePSCommandAsync(psCommand, CancellationToken.None).ConfigureAwait(false))[0]; - this.isPlasterInstalled = moduleObject != null; + isPlasterInstalled = moduleObject != null; string installedQualifier = - this.isPlasterInstalled.Value + isPlasterInstalled.Value ? string.Empty : "not "; - this._logger.LogTrace($"Plaster is {installedQualifier}installed!"); + _logger.LogTrace($"Plaster is {installedQualifier}installed!"); // Attempt to load plaster - if (this.isPlasterInstalled.Value && this.isPlasterLoaded == false) + if (isPlasterInstalled.Value && isPlasterLoaded == false) { - this._logger.LogTrace("Loading Plaster..."); + _logger.LogTrace("Loading Plaster..."); psCommand = new PSCommand(); psCommand @@ -94,16 +94,16 @@ public async Task ImportPlasterIfInstalledAsync() IReadOnlyList importResult = await _executionService.ExecutePSCommandAsync(psCommand, CancellationToken.None).ConfigureAwait(false); - this.isPlasterLoaded = importResult.Any(); + isPlasterLoaded = importResult.Any(); string loadedQualifier = - this.isPlasterInstalled.Value + isPlasterInstalled.Value ? "was" : "could not be"; - this._logger.LogTrace($"Plaster {loadedQualifier} loaded successfully!"); + _logger.LogTrace($"Plaster {loadedQualifier} loaded successfully!"); } } - return this.isPlasterInstalled.Value; + return isPlasterInstalled.Value; } /// @@ -118,12 +118,12 @@ public async Task ImportPlasterIfInstalledAsync() public async Task GetAvailableTemplatesAsync( bool includeInstalledModules) { - if (!this.isPlasterLoaded) + if (!isPlasterLoaded) { throw new InvalidOperationException("Plaster is not loaded, templates cannot be accessed."); } - PSCommand psCommand = new PSCommand(); + PSCommand psCommand = new(); psCommand.AddCommand("Get-PlasterTemplate"); if (includeInstalledModules) @@ -135,7 +135,7 @@ public async Task GetAvailableTemplatesAsync( psCommand, CancellationToken.None).ConfigureAwait(false); - this._logger.LogTrace($"Found {templateObjects.Count()} Plaster templates"); + _logger.LogTrace($"Found {templateObjects.Count} Plaster templates"); return templateObjects @@ -155,10 +155,10 @@ public async Task CreateFromTemplateAsync( string templatePath, string destinationPath) { - this._logger.LogTrace( + _logger.LogTrace( $"Invoking Plaster...\n\n TemplatePath: {templatePath}\n DestinationPath: {destinationPath}"); - PSCommand command = new PSCommand(); + PSCommand command = new(); command.AddCommand("Invoke-Plaster"); command.AddParameter("TemplatePath", templatePath); command.AddParameter("DestinationPath", destinationPath); diff --git a/src/PowerShellEditorServices/Services/TextDocument/BufferPosition.cs b/src/PowerShellEditorServices/Services/TextDocument/BufferPosition.cs index 104298d2c..1a581db98 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/BufferPosition.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/BufferPosition.cs @@ -18,7 +18,7 @@ internal class BufferPosition /// /// Provides an instance that represents a position that has not been set. /// - public static readonly BufferPosition None = new BufferPosition(-1, -1); + public static readonly BufferPosition None = new(-1, -1); /// /// Gets the line number of the position in the buffer. @@ -41,8 +41,8 @@ internal class BufferPosition /// The column number of the position. public BufferPosition(int line, int column) { - this.Line = line; - this.Column = column; + Line = line; + Column = column; } #endregion @@ -56,7 +56,7 @@ public BufferPosition(int line, int column) /// True if the positions are equal, false otherwise. public override bool Equals(object obj) { - if (!(obj is BufferPosition)) + if (obj is not BufferPosition) { return false; } @@ -64,18 +64,15 @@ public override bool Equals(object obj) BufferPosition other = (BufferPosition)obj; return - this.Line == other.Line && - this.Column == other.Column; + Line == other.Line && + Column == other.Column; } /// /// Calculates a unique hash code that represents this instance. /// /// A hash code representing this instance. - public override int GetHashCode() - { - return this.Line.GetHashCode() ^ this.Column.GetHashCode(); - } + public override int GetHashCode() => Line.GetHashCode() ^ Column.GetHashCode(); /// /// Compares two positions to check if one is greater than the other. @@ -98,10 +95,7 @@ public override int GetHashCode() /// The first position to compare. /// The second position to compare. /// True if positionOne is less than positionTwo. - public static bool operator <(BufferPosition positionOne, BufferPosition positionTwo) - { - return positionTwo > positionOne; - } + public static bool operator <(BufferPosition positionOne, BufferPosition positionTwo) => positionTwo > positionOne; #endregion } diff --git a/src/PowerShellEditorServices/Services/TextDocument/BufferRange.cs b/src/PowerShellEditorServices/Services/TextDocument/BufferRange.cs index 5c129c466..8bbdaabd1 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/BufferRange.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/BufferRange.cs @@ -18,7 +18,7 @@ internal sealed class BufferRange /// /// Provides an instance that represents a range that has not been set. /// - public static readonly BufferRange None = new BufferRange(0, 0, 0, 0); + public static readonly BufferRange None = new(0, 0, 0, 0); /// /// Gets the start position of the range in the buffer. @@ -34,13 +34,7 @@ internal sealed class BufferRange /// Returns true if the current range is non-zero, i.e. /// contains valid start and end positions. /// - public bool HasRange - { - get - { - return this.Equals(BufferRange.None); - } - } + public bool HasRange => Equals(BufferRange.None); #endregion @@ -62,8 +56,8 @@ public BufferRange(BufferPosition start, BufferPosition end) end.Line, end.Column)); } - this.Start = start; - this.End = end; + Start = start; + End = end; } /// @@ -79,8 +73,8 @@ public BufferRange( int endLine, int endColumn) { - this.Start = new BufferPosition(startLine, startColumn); - this.End = new BufferPosition(endLine, endColumn); + Start = new BufferPosition(startLine, startColumn); + End = new BufferPosition(endLine, endColumn); } #endregion @@ -94,7 +88,7 @@ public BufferRange( /// True if the ranges are equal, false otherwise. public override bool Equals(object obj) { - if (!(obj is BufferRange)) + if (obj is not BufferRange) { return false; } @@ -102,18 +96,15 @@ public override bool Equals(object obj) BufferRange other = (BufferRange)obj; return - this.Start.Equals(other.Start) && - this.End.Equals(other.End); + Start.Equals(other.Start) && + End.Equals(other.End); } /// /// Calculates a unique hash code that represents this instance. /// /// A hash code representing this instance. - public override int GetHashCode() - { - return this.Start.GetHashCode() ^ this.End.GetHashCode(); - } + public override int GetHashCode() => Start.GetHashCode() ^ End.GetHashCode(); #endregion } diff --git a/src/PowerShellEditorServices/Services/TextDocument/FilePosition.cs b/src/PowerShellEditorServices/Services/TextDocument/FilePosition.cs index d0339b1d2..b9cb3594e 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/FilePosition.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/FilePosition.cs @@ -11,7 +11,7 @@ internal sealed class FilePosition : BufferPosition { #region Private Fields - private ScriptFile scriptFile; + private readonly ScriptFile scriptFile; #endregion @@ -28,10 +28,7 @@ public FilePosition( ScriptFile scriptFile, int line, int column) - : base(line, column) - { - this.scriptFile = scriptFile; - } + : base(line, column) => this.scriptFile = scriptFile; /// /// Creates a new FilePosition instance for the specified file by @@ -42,10 +39,7 @@ public FilePosition( public FilePosition( ScriptFile scriptFile, BufferPosition copiedPosition) - : this(scriptFile, copiedPosition.Line, copiedPosition.Column) - { - scriptFile.ValidatePosition(copiedPosition); - } + : this(scriptFile, copiedPosition.Line, copiedPosition.Column) => scriptFile.ValidatePosition(copiedPosition); #endregion @@ -61,7 +55,7 @@ public FilePosition( /// A new FilePosition instance for the calculated position. public FilePosition AddOffset(int lineOffset, int columnOffset) { - return this.scriptFile.CalculatePosition( + return scriptFile.CalculatePosition( this, lineOffset, columnOffset); @@ -75,7 +69,7 @@ public FilePosition AddOffset(int lineOffset, int columnOffset) /// A new FilePosition instance for the calculated position. public FilePosition GetLineStart() { - string scriptLine = scriptFile.FileLines[this.Line - 1]; + string scriptLine = scriptFile.FileLines[Line - 1]; int lineStartColumn = 1; for (int i = 0; i < scriptLine.Length; i++) @@ -87,7 +81,7 @@ public FilePosition GetLineStart() } } - return new FilePosition(this.scriptFile, this.Line, lineStartColumn); + return new FilePosition(scriptFile, Line, lineStartColumn); } /// @@ -97,8 +91,8 @@ public FilePosition GetLineStart() /// A new FilePosition instance for the calculated position. public FilePosition GetLineEnd() { - string scriptLine = scriptFile.FileLines[this.Line - 1]; - return new FilePosition(this.scriptFile, this.Line, scriptLine.Length + 1); + string scriptLine = scriptFile.FileLines[Line - 1]; + return new FilePosition(scriptFile, Line, scriptLine.Length + 1); } #endregion diff --git a/src/PowerShellEditorServices/Services/TextDocument/FoldingReference.cs b/src/PowerShellEditorServices/Services/TextDocument/FoldingReference.cs index 92acdf7eb..9b5be96f5 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/FoldingReference.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/FoldingReference.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell.EditorServices.Services.TextDocument /// /// A class that holds the information for a foldable region of text in a document /// - internal class FoldingReference: IComparable, IEquatable + internal class FoldingReference : IComparable, IEquatable { /// /// The zero-based line number from where the folded range starts. @@ -40,24 +40,25 @@ internal class FoldingReference: IComparable, IEquatable /// A custom comparable method which can properly sort FoldingReference objects /// - public int CompareTo(FoldingReference that) { + public int CompareTo(FoldingReference that) + { // Initially look at the start line - if (this.StartLine < that.StartLine) { return -1; } - if (this.StartLine > that.StartLine) { return 1; } + if (StartLine < that.StartLine) { return -1; } + if (StartLine > that.StartLine) { return 1; } // They have the same start line so now consider the end line. // The biggest line range is sorted first - if (this.EndLine > that.EndLine) { return -1; } - if (this.EndLine < that.EndLine) { return 1; } + if (EndLine > that.EndLine) { return -1; } + if (EndLine < that.EndLine) { return 1; } // They have the same lines, but what about character offsets - if (this.StartCharacter < that.StartCharacter) { return -1; } - if (this.StartCharacter > that.StartCharacter) { return 1; } - if (this.EndCharacter < that.EndCharacter) { return -1; } - if (this.EndCharacter > that.EndCharacter) { return 1; } + if (StartCharacter < that.StartCharacter) { return -1; } + if (StartCharacter > that.StartCharacter) { return 1; } + if (EndCharacter < that.EndCharacter) { return -1; } + if (EndCharacter > that.EndCharacter) { return 1; } // They're the same range, but what about kind - if (this.Kind == null) + if (Kind == null) { if (that.Kind == null) { @@ -69,14 +70,14 @@ public int CompareTo(FoldingReference that) { if (that.Kind != null) { - return that.Kind.Value - this.Kind.Value; + return that.Kind.Value - Kind.Value; } // this has a kind but that doesn't. return -1; } - public bool Equals(FoldingReference other) => this.CompareTo(other) == 0; + public bool Equals(FoldingReference other) => CompareTo(other) == 0; } /// @@ -85,18 +86,12 @@ public int CompareTo(FoldingReference that) { /// internal class FoldingReferenceList { - private readonly Dictionary references = new Dictionary(); + private readonly Dictionary references = new(); /// /// Return all references in the list /// - public IEnumerable References - { - get - { - return references.Values; - } - } + public IEnumerable References => references.Values; /// /// Adds a FoldingReference to the list and enforces ordering rules e.g. Only one fold per start line @@ -121,7 +116,7 @@ public void SafeAdd(FoldingReference item) /// public FoldingReference[] ToArray() { - var result = new FoldingReference[references.Count]; + FoldingReference[] result = new FoldingReference[references.Count]; references.Values.CopyTo(result, 0); return result; } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DefinitionHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DefinitionHandler.cs index ec47f7716..decc1ea4a 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DefinitionHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DefinitionHandler.cs @@ -32,7 +32,7 @@ public PsesDefinitionHandler( _workspaceService = workspaceService; } - protected override DefinitionRegistrationOptions CreateRegistrationOptions(DefinitionCapability capability, ClientCapabilities clientCapabilities) => new DefinitionRegistrationOptions + protected override DefinitionRegistrationOptions CreateRegistrationOptions(DefinitionCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector }; @@ -47,7 +47,7 @@ public override async Task Handle(DefinitionParams requ request.Position.Line + 1, request.Position.Character + 1); - List definitionLocations = new List(); + List definitionLocations = new(); if (foundSymbol != null) { SymbolReference foundDefinition = await _symbolsService.GetDefinitionOfSymbolAsync( diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs index 66b436297..9a513f942 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentHighlightHandler.cs @@ -17,7 +17,7 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class PsesDocumentHighlightHandler : DocumentHighlightHandlerBase { - private static readonly DocumentHighlightContainer s_emptyHighlightContainer = new DocumentHighlightContainer(); + private static readonly DocumentHighlightContainer s_emptyHighlightContainer = new(); private readonly ILogger _logger; private readonly WorkspaceService _workspaceService; private readonly SymbolsService _symbolsService; @@ -33,7 +33,7 @@ public PsesDocumentHighlightHandler( _logger.LogInformation("highlight handler loaded"); } - protected override DocumentHighlightRegistrationOptions CreateRegistrationOptions(DocumentHighlightCapability capability, ClientCapabilities clientCapabilities) => new DocumentHighlightRegistrationOptions + protected override DocumentHighlightRegistrationOptions CreateRegistrationOptions(DocumentHighlightCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector }; @@ -54,7 +54,7 @@ public override Task Handle( return Task.FromResult(s_emptyHighlightContainer); } - var highlights = new DocumentHighlight[symbolOccurrences.Count]; + DocumentHighlight[] highlights = new DocumentHighlight[symbolOccurrences.Count]; for (int i = 0; i < symbolOccurrences.Count; i++) { highlights[i] = new DocumentHighlight diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentSymbolHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentSymbolHandler.cs index 949377764..d3c157497 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentSymbolHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/DocumentSymbolHandler.cs @@ -39,7 +39,7 @@ public PsesDocumentSymbolHandler(ILoggerFactory factory, ConfigurationService co }; } - protected override DocumentSymbolRegistrationOptions CreateRegistrationOptions(DocumentSymbolCapability capability, ClientCapabilities clientCapabilities) => new DocumentSymbolRegistrationOptions + protected override DocumentSymbolRegistrationOptions CreateRegistrationOptions(DocumentSymbolCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector }; @@ -49,16 +49,14 @@ public override Task Handle(Document ScriptFile scriptFile = _workspaceService.GetFile(request.TextDocument.Uri); IEnumerable foundSymbols = - this.ProvideDocumentSymbols(scriptFile); + ProvideDocumentSymbols(scriptFile); SymbolInformationOrDocumentSymbol[] symbols = null; string containerName = Path.GetFileNameWithoutExtension(scriptFile.FilePath); - if (foundSymbols != null) - { - symbols = - foundSymbols + symbols = foundSymbols != null + ? foundSymbols .Select(r => { return new SymbolInformationOrDocumentSymbol(new SymbolInformation @@ -73,12 +71,8 @@ public override Task Handle(Document Name = GetDecoratedSymbolName(r) }); }) - .ToArray(); - } - else - { - symbols = Array.Empty(); - } + .ToArray() + : Array.Empty(); return Task.FromResult(new SymbolInformationOrDocumentSymbolContainer(symbols)); @@ -88,7 +82,7 @@ private IEnumerable ProvideDocumentSymbols( ScriptFile scriptFile) { return - this.InvokeProviders(p => p.ProvideDocumentSymbols(scriptFile)) + InvokeProviders(p => p.ProvideDocumentSymbols(scriptFile)) .SelectMany(r => r); } @@ -104,10 +98,10 @@ private IEnumerable ProvideDocumentSymbols( protected IEnumerable InvokeProviders( Func invokeFunc) { - Stopwatch invokeTimer = new Stopwatch(); - List providerResults = new List(); + Stopwatch invokeTimer = new(); + List providerResults = new(); - foreach (var provider in this._providers) + foreach (IDocumentSymbolProvider provider in _providers) { try { @@ -117,12 +111,12 @@ protected IEnumerable InvokeProviders( invokeTimer.Stop(); - this._logger.LogTrace( + _logger.LogTrace( $"Invocation of provider '{provider.GetType().Name}' completed in {invokeTimer.ElapsedMilliseconds}ms."); } catch (Exception e) { - this._logger.LogException( + _logger.LogException( $"Exception caught while invoking provider {provider.GetType().Name}:", e); } @@ -133,25 +127,20 @@ protected IEnumerable InvokeProviders( private static SymbolKind GetSymbolKind(SymbolType symbolType) { - switch (symbolType) + return symbolType switch { - case SymbolType.Configuration: - case SymbolType.Function: - case SymbolType.Workflow: - return SymbolKind.Function; - - default: - return SymbolKind.Variable; - } + SymbolType.Configuration or SymbolType.Function or SymbolType.Workflow => SymbolKind.Function, + _ => SymbolKind.Variable, + }; } private static string GetDecoratedSymbolName(ISymbolReference symbolReference) { string name = symbolReference.SymbolName; - if (symbolReference.SymbolType == SymbolType.Configuration || - symbolReference.SymbolType == SymbolType.Function || - symbolReference.SymbolType == SymbolType.Workflow) + if (symbolReference.SymbolType is SymbolType.Configuration or + SymbolType.Function or + SymbolType.Workflow) { name += " { }"; } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/FoldingRangeHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/FoldingRangeHandler.cs index effe2af58..a6eaec1ff 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/FoldingRangeHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/FoldingRangeHandler.cs @@ -27,7 +27,7 @@ public PsesFoldingRangeHandler(ILoggerFactory factory, ConfigurationService conf _workspaceService = workspaceService; } - protected override FoldingRangeRegistrationOptions CreateRegistrationOptions(FoldingRangeCapability capability, ClientCapabilities clientCapabilities) => new FoldingRangeRegistrationOptions + protected override FoldingRangeRegistrationOptions CreateRegistrationOptions(FoldingRangeCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector }; @@ -50,19 +50,20 @@ public override Task> Handle(FoldingRangeRequestParam re // warrant the extra effort. if (!_workspaceService.TryGetFile(request.TextDocument.Uri, out ScriptFile scriptFile)) { return null; } - var result = new List(); + List result = new(); // If we're showing the last line, decrement the Endline of all regions by one. int endLineOffset = _configurationService.CurrentSettings.CodeFolding.ShowLastLine ? -1 : 0; foreach (FoldingReference fold in TokenOperations.FoldableReferences(scriptFile.ScriptTokens).References) { - result.Add(new FoldingRange { - EndCharacter = fold.EndCharacter, - EndLine = fold.EndLine + endLineOffset, - Kind = fold.Kind, + result.Add(new FoldingRange + { + EndCharacter = fold.EndCharacter, + EndLine = fold.EndLine + endLineOffset, + Kind = fold.Kind, StartCharacter = fold.StartCharacter, - StartLine = fold.StartLine + StartLine = fold.StartLine }); } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/HoverHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/HoverHandler.cs index 85c88f557..33db7975b 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/HoverHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/HoverHandler.cs @@ -31,7 +31,7 @@ public PsesHoverHandler( _workspaceService = workspaceService; } - protected override HoverRegistrationOptions CreateRegistrationOptions(HoverCapability capability, ClientCapabilities clientCapabilities) => new HoverRegistrationOptions + protected override HoverRegistrationOptions CreateRegistrationOptions(HoverCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector }; @@ -57,7 +57,7 @@ await _symbolsService.FindSymbolDetailsAtLocationAsync( return null; } - List symbolInfo = new List(); + List symbolInfo = new(); symbolInfo.Add(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 2ba3f37ef..4cb872a38 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/PsesSemanticTokensHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/PsesSemanticTokensHandler.cs @@ -18,7 +18,7 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { internal class PsesSemanticTokensHandler : SemanticTokensHandlerBase { - protected override SemanticTokensRegistrationOptions CreateRegistrationOptions(SemanticTokensCapability capability, ClientCapabilities clientCapabilities) => new SemanticTokensRegistrationOptions + protected override SemanticTokensRegistrationOptions CreateRegistrationOptions(SemanticTokensCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector, Legend = new SemanticTokensLegend(), @@ -72,7 +72,9 @@ internal static IEnumerable ConvertToSemanticTokens(Token token) foreach (Token t in stringExpandableToken.NestedTokens) { foreach (SemanticToken subToken in ConvertToSemanticTokens(t)) + { yield return subToken; + } } yield break; } @@ -155,9 +157,6 @@ private static SemanticTokenType MapSemanticTokenType(Token token) protected override Task GetSemanticTokensDocument( ITextDocumentIdentifierParams @params, - CancellationToken cancellationToken) - { - return Task.FromResult(new SemanticTokensDocument(RegistrationOptions.Legend)); - } + CancellationToken cancellationToken) => Task.FromResult(new SemanticTokensDocument(RegistrationOptions.Legend)); } } diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/ReferencesHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/ReferencesHandler.cs index ebce705d2..12c505a01 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/ReferencesHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/ReferencesHandler.cs @@ -16,7 +16,7 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { - class PsesReferencesHandler : ReferencesHandlerBase + internal class PsesReferencesHandler : ReferencesHandlerBase { private readonly ILogger _logger; private readonly SymbolsService _symbolsService; @@ -29,12 +29,12 @@ public PsesReferencesHandler(ILoggerFactory factory, SymbolsService symbolsServi _workspaceService = workspaceService; } - protected override ReferenceRegistrationOptions CreateRegistrationOptions(ReferenceCapability capability, ClientCapabilities clientCapabilities) => new ReferenceRegistrationOptions + protected override ReferenceRegistrationOptions CreateRegistrationOptions(ReferenceCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector }; - public async override Task Handle(ReferenceParams request, CancellationToken cancellationToken) + public override async Task Handle(ReferenceParams request, CancellationToken cancellationToken) { ScriptFile scriptFile = _workspaceService.GetFile(request.TextDocument.Uri); @@ -50,7 +50,7 @@ await _symbolsService.FindReferencesOfSymbol( _workspaceService.ExpandScriptReferences(scriptFile), _workspaceService).ConfigureAwait(false); - var locations = new List(); + List locations = new(); if (referencesResult != null) { diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/SignatureHelpHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/SignatureHelpHandler.cs index 689b762ca..2630cddc3 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/SignatureHelpHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/SignatureHelpHandler.cs @@ -35,7 +35,7 @@ public PsesSignatureHelpHandler( _executionService = executionService; } - protected override SignatureHelpRegistrationOptions CreateRegistrationOptions(SignatureHelpCapability capability, ClientCapabilities clientCapabilities) => new SignatureHelpRegistrationOptions + protected override SignatureHelpRegistrationOptions CreateRegistrationOptions(SignatureHelpCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector, // A sane default of " ". We may be able to include others like "-". @@ -63,10 +63,10 @@ await _symbolsService.FindParameterSetsInFileAsync( return new SignatureHelp(); } - var signatures = new SignatureInformation[parameterSets.Signatures.Length]; + SignatureInformation[] signatures = new SignatureInformation[parameterSets.Signatures.Length]; for (int i = 0; i < signatures.Length; i++) { - var parameters = new List(); + List parameters = new(); foreach (ParameterInfo param in parameterSets.Signatures[i].Parameters) { parameters.Add(CreateParameterInfo(param)); diff --git a/src/PowerShellEditorServices/Services/TextDocument/Handlers/TextDocumentHandler.cs b/src/PowerShellEditorServices/Services/TextDocument/Handlers/TextDocumentHandler.cs index d35de6850..0f18d27cb 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/Handlers/TextDocumentHandler.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/Handlers/TextDocumentHandler.cs @@ -17,9 +17,9 @@ namespace Microsoft.PowerShell.EditorServices.Handlers { - class PsesTextDocumentHandler : TextDocumentSyncHandlerBase + internal class PsesTextDocumentHandler : TextDocumentSyncHandlerBase { - private static readonly Uri s_fakeUri = new Uri("Untitled:fake"); + private static readonly Uri s_fakeUri = new("Untitled:fake"); private readonly ILogger _logger; private readonly AnalysisService _analysisService; @@ -59,7 +59,7 @@ public override Task Handle(DidChangeTextDocumentParams notification, Canc return Unit.Task; } - protected override TextDocumentSyncRegistrationOptions CreateRegistrationOptions(SynchronizationCapability capability, ClientCapabilities clientCapabilities) => new TextDocumentSyncRegistrationOptions() + protected override TextDocumentSyncRegistrationOptions CreateRegistrationOptions(SynchronizationCapability capability, ClientCapabilities clientCapabilities) => new() { DocumentSelector = LspUtils.PowerShellDocumentSelector, Change = Change, @@ -91,7 +91,7 @@ public override Task Handle(DidOpenTextDocumentParams notification, Cancel public override Task Handle(DidCloseTextDocumentParams notification, CancellationToken token) { // Find and close the file in the current session - var fileToClose = _workspaceService.GetFile(notification.TextDocument.Uri); + ScriptFile fileToClose = _workspaceService.GetFile(notification.TextDocument.Uri); if (fileToClose != null) { @@ -117,13 +117,16 @@ public override async Task Handle(DidSaveTextDocumentParams notification, return Unit.Value; } - public override TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri) => new TextDocumentAttributes(uri, "powershell"); + public override TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri) => new(uri, "powershell"); private static FileChange GetFileChangeDetails(Range changeRange, string insertString) { // The protocol's positions are zero-based so add 1 to all offsets - if (changeRange == null) return new FileChange { InsertString = insertString, IsReload = true }; + if (changeRange == null) + { + return new FileChange { InsertString = insertString, IsReload = true }; + } return new FileChange { diff --git a/src/PowerShellEditorServices/Services/TextDocument/ScriptFile.cs b/src/PowerShellEditorServices/Services/TextDocument/ScriptFile.cs index eb2569478..3c543d1b9 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/ScriptFile.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/ScriptFile.cs @@ -26,7 +26,7 @@ internal sealed class ScriptFile "\n" }; - private Version powerShellVersion; + private readonly Version powerShellVersion; #endregion @@ -37,11 +37,7 @@ internal sealed class ScriptFile /// this property returns a normalized version of the value stored /// in the FilePath property. /// - public string Id - { - // TODO: Is this why the drive letter changes? - get { return this.FilePath.ToLower(); } - } + public string Id => FilePath.ToLower(); /// /// Gets the path at which this file resides. @@ -69,13 +65,7 @@ public string Id /// /// Gets a string containing the full contents of the file. /// - public string Contents - { - get - { - return string.Join(Environment.NewLine, this.FileLines); - } - } + public string Contents => string.Join(Environment.NewLine, FileLines); /// /// Gets a BufferRange that represents the entire content @@ -187,10 +177,7 @@ internal ScriptFile( /// /// Input string to be split up into lines. /// The lines in the string. - internal static IList GetLines(string text) - { - return GetLinesInternal(text); - } + internal static IList GetLines(string text) => GetLinesInternal(text); /// /// Get the lines in a string. @@ -231,9 +218,9 @@ public string GetLine(int lineNumber) { Validate.IsWithinRange( "lineNumber", lineNumber, - 1, this.FileLines.Count + 1); + 1, FileLines.Count + 1); - return this.FileLines[lineNumber - 1]; + return FileLines[lineNumber - 1]; } /// @@ -243,17 +230,17 @@ public string GetLine(int lineNumber) /// An array of strings from the specified range of the file. public string[] GetLinesInRange(BufferRange bufferRange) { - this.ValidatePosition(bufferRange.Start); - this.ValidatePosition(bufferRange.End); + ValidatePosition(bufferRange.Start); + ValidatePosition(bufferRange.End); - List linesInRange = new List(); + List linesInRange = new(); int startLine = bufferRange.Start.Line, endLine = bufferRange.End.Line; for (int line = startLine; line <= endLine; line++) { - string currentLine = this.FileLines[line - 1]; + string currentLine = FileLines[line - 1]; int startColumn = line == startLine ? bufferRange.Start.Column @@ -281,7 +268,7 @@ public string[] GetLinesInRange(BufferRange bufferRange) /// The position in the buffer to be validated. public void ValidatePosition(BufferPosition bufferPosition) { - this.ValidatePosition( + ValidatePosition( bufferPosition.Line, bufferPosition.Column); } @@ -294,7 +281,7 @@ public void ValidatePosition(BufferPosition bufferPosition) /// The 1-based column to be validated. public void ValidatePosition(int line, int column) { - int maxLine = this.FileLines.Count; + int maxLine = FileLines.Count; if (line < 1 || line > maxLine) { throw new ArgumentOutOfRangeException($"Position {line}:{column} is outside of the line range of 1 to {maxLine}."); @@ -302,7 +289,7 @@ public void ValidatePosition(int line, int column) // The maximum column is either **one past** the length of the string // or 1 if the string is empty. - string lineString = this.FileLines[line - 1]; + string lineString = FileLines[line - 1]; int maxColumn = lineString.Length > 0 ? lineString.Length + 1 : 1; if (column < 1 || column > maxColumn) @@ -322,10 +309,10 @@ public void ApplyChange(FileChange fileChange) if (fileChange.IsReload) { - this.FileLines.Clear(); - foreach (var changeLine in changeLines) + FileLines.Clear(); + foreach (string changeLine in changeLines) { - this.FileLines.Add(changeLine); + FileLines.Add(changeLine); } } else @@ -333,43 +320,43 @@ public void ApplyChange(FileChange fileChange) // VSCode sometimes likes to give the change start line as (FileLines.Count + 1). // This used to crash EditorServices, but we now treat it as an append. // See https://github.com/PowerShell/vscode-powershell/issues/1283 - if (fileChange.Line == this.FileLines.Count + 1) + if (fileChange.Line == FileLines.Count + 1) { foreach (string addedLine in changeLines) { string finalLine = addedLine.TrimEnd('\r'); - this.FileLines.Add(finalLine); + FileLines.Add(finalLine); } } // Similarly, when lines are deleted from the end of the file, // VSCode likes to give the end line as (FileLines.Count + 1). - else if (fileChange.EndLine == this.FileLines.Count + 1 && String.Empty.Equals(fileChange.InsertString)) + else if (fileChange.EndLine == FileLines.Count + 1 && string.Empty.Equals(fileChange.InsertString)) { int lineIndex = fileChange.Line - 1; - this.FileLines.RemoveRange(lineIndex, this.FileLines.Count - lineIndex); + FileLines.RemoveRange(lineIndex, FileLines.Count - lineIndex); } // Otherwise, the change needs to go between existing content else { - this.ValidatePosition(fileChange.Line, fileChange.Offset); - this.ValidatePosition(fileChange.EndLine, fileChange.EndOffset); + ValidatePosition(fileChange.Line, fileChange.Offset); + ValidatePosition(fileChange.EndLine, fileChange.EndOffset); // Get the first fragment of the first line string firstLineFragment = - this.FileLines[fileChange.Line - 1] + FileLines[fileChange.Line - 1] .Substring(0, fileChange.Offset - 1); // Get the last fragment of the last line - string endLine = this.FileLines[fileChange.EndLine - 1]; + string endLine = FileLines[fileChange.EndLine - 1]; string lastLineFragment = endLine.Substring( fileChange.EndOffset - 1, - (this.FileLines[fileChange.EndLine - 1].Length - fileChange.EndOffset) + 1); + FileLines[fileChange.EndLine - 1].Length - fileChange.EndOffset + 1); // Remove the old lines for (int i = 0; i <= fileChange.EndLine - fileChange.Line; i++) { - this.FileLines.RemoveAt(fileChange.Line - 1); + FileLines.RemoveAt(fileChange.Line - 1); } // Build and insert the new lines @@ -389,17 +376,17 @@ public void ApplyChange(FileChange fileChange) if (changeIndex == changeLines.Length - 1) { // Append the last line fragment - finalLine = finalLine + lastLineFragment; + finalLine += lastLineFragment; } - this.FileLines.Insert(currentLineNumber - 1, finalLine); + FileLines.Insert(currentLineNumber - 1, finalLine); currentLineNumber++; } } } // Parse the script again to be up-to-date - this.ParseFileContents(); + ParseFileContents(); } /// @@ -411,7 +398,7 @@ 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, this.FileLines.Count + 1); + Validate.IsWithinRange("lineNumber", lineNumber, 1, FileLines.Count + 1); Validate.IsGreaterThan("columnNumber", columnNumber, 0); int offset = 0; @@ -426,7 +413,7 @@ public int GetOffsetAtPosition(int lineNumber, int columnNumber) else { // Add an offset to account for the current platform's newline characters - offset += this.FileLines[i].Length + Environment.NewLine.Length; + offset += FileLines[i].Length + Environment.NewLine.Length; } } @@ -449,9 +436,9 @@ public FilePosition CalculatePosition( int newLine = originalPosition.Line + lineOffset, newColumn = originalPosition.Column + columnOffset; - this.ValidatePosition(newLine, newColumn); + ValidatePosition(newLine, newColumn); - string scriptLine = this.FileLines[newLine - 1]; + string scriptLine = FileLines[newLine - 1]; newColumn = Math.Min(scriptLine.Length + 1, newColumn); return new FilePosition(this, newLine, newColumn); @@ -485,13 +472,13 @@ public BufferRange GetRangeBetweenOffsets(int startOffset, int endOffset) int currentOffset = 0; int searchedOffset = startOffset; - BufferPosition startPosition = new BufferPosition(0, 0); + BufferPosition startPosition = new(0, 0); BufferPosition endPosition = startPosition; int line = 0; - while (line < this.FileLines.Count) + while (line < FileLines.Count) { - if (searchedOffset <= currentOffset + this.FileLines[line].Length) + if (searchedOffset <= currentOffset + FileLines[line].Length) { int column = searchedOffset - currentOffset; @@ -525,7 +512,7 @@ public BufferRange GetRangeBetweenOffsets(int startOffset, int endOffset) } // Increase the current offset and include newline length - currentOffset += this.FileLines[line].Length + Environment.NewLine.Length; + currentOffset += FileLines[line].Length + Environment.NewLine.Length; line++; } @@ -540,10 +527,10 @@ private void SetFileContents(string fileContents) { // Split the file contents into lines and trim // any carriage returns from the strings. - this.FileLines = GetLinesInternal(fileContents); + FileLines = GetLinesInternal(fileContents); // Parse the contents to get syntax tree and errors - this.ParseFileContents(); + ParseFileContents(); } /// @@ -555,64 +542,58 @@ private void ParseFileContents() ParseError[] parseErrors = null; // First, get the updated file range - int lineCount = this.FileLines.Count; - if (lineCount > 0) - { - this.FileRange = - new BufferRange( + int lineCount = FileLines.Count; + FileRange = lineCount > 0 + ? new BufferRange( new BufferPosition(1, 1), new BufferPosition( lineCount + 1, - this.FileLines[lineCount - 1].Length + 1)); - } - else - { - this.FileRange = BufferRange.None; - } + FileLines[lineCount - 1].Length + 1)) + : BufferRange.None; try { Token[] scriptTokens; // This overload appeared with Windows 10 Update 1 - if (this.powerShellVersion.Major >= 6 || - (this.powerShellVersion.Major == 5 && this.powerShellVersion.Build >= 10586)) + if (powerShellVersion.Major >= 6 || + (powerShellVersion.Major == 5 && powerShellVersion.Build >= 10586)) { // Include the file path so that module relative // paths are evaluated correctly - this.ScriptAst = + ScriptAst = Parser.ParseInput( - this.Contents, - this.FilePath, + Contents, + FilePath, out scriptTokens, out parseErrors); } else { - this.ScriptAst = + ScriptAst = Parser.ParseInput( - this.Contents, + Contents, out scriptTokens, out parseErrors); } - this.ScriptTokens = scriptTokens; + ScriptTokens = scriptTokens; } catch (RuntimeException ex) { - var parseError = - new ParseError( + ParseError parseError = + new( null, ex.ErrorRecord.FullyQualifiedErrorId, ex.Message); parseErrors = new[] { parseError }; - this.ScriptTokens = Array.Empty(); - this.ScriptAst = null; + ScriptTokens = Array.Empty(); + ScriptAst = null; } // Translate parse errors into syntax markers - this.DiagnosticMarkers = + DiagnosticMarkers = parseErrors .Select(ScriptFileMarker.FromParseError) .ToList(); @@ -624,12 +605,12 @@ private void ParseFileContents() if (IsInMemory) { // Need to initialize the ReferencedFiles property to an empty array. - this.ReferencedFiles = Array.Empty(); + ReferencedFiles = Array.Empty(); return; } // Get all dot sourced referenced files and store them - this.ReferencedFiles = AstOperations.FindDotSourcedIncludes(this.ScriptAst, Path.GetDirectoryName(this.FilePath)); + ReferencedFiles = AstOperations.FindDotSourcedIncludes(ScriptAst, Path.GetDirectoryName(FilePath)); } #endregion diff --git a/src/PowerShellEditorServices/Services/TextDocument/ScriptFileMarker.cs b/src/PowerShellEditorServices/Services/TextDocument/ScriptFileMarker.cs index cd70271ae..8d7c24ca3 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/ScriptFileMarker.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/ScriptFileMarker.cs @@ -34,19 +34,19 @@ public enum ScriptFileMarkerLevel ///          /// Information: This warning is trivial, but may be useful. They are recommended by PowerShell best practice.         ///  -        Information = 0, +        Information = 0,         ///          /// WARNING: This warning may cause a problem or does not follow PowerShell's recommended guidelines.         ///  -        Warning = 1, +        Warning = 1,         ///          /// ERROR: This warning is likely to cause a problem or does not follow PowerShell's required guidelines.         ///  -        Error = 2, +        Error = 2,         ///          /// ERROR: This diagnostic is caused by an actual parsing error, and is generated only by the engine.         ///  -        ParseError = 3 +        ParseError = 3 }; /// @@ -123,11 +123,11 @@ internal static ScriptFileMarker FromDiagnosticRecord(PSObject psObject) // casting psobject to dynamic allows us to access // the diagnostic record's properties directly i.e. . // without having to go through PSObject's Members property. - var diagnosticRecord = psObject as dynamic; + dynamic diagnosticRecord = psObject; if (diagnosticRecord.SuggestedCorrections != null) { - var editRegions = new List(); + List editRegions = new(); string correctionMessage = null; foreach (dynamic suggestedCorrection in diagnosticRecord.SuggestedCorrections) { diff --git a/src/PowerShellEditorServices/Services/TextDocument/SemanticToken.cs b/src/PowerShellEditorServices/Services/TextDocument/SemanticToken.cs index 8a7151050..a3fe3f39e 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/SemanticToken.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/SemanticToken.cs @@ -17,7 +17,7 @@ public SemanticToken(string text, SemanticTokenType type, int line, int column, TokenModifiers = tokenModifiers; } - public string Text { get; set ;} + public string Text { get; set; } public int Line { get; set; } diff --git a/src/PowerShellEditorServices/Services/TextDocument/TokenOperations.cs b/src/PowerShellEditorServices/Services/TextDocument/TokenOperations.cs index 6f6c07d88..4d91038bf 100644 --- a/src/PowerShellEditorServices/Services/TextDocument/TokenOperations.cs +++ b/src/PowerShellEditorServices/Services/TextDocument/TokenOperations.cs @@ -20,9 +20,9 @@ internal static class TokenOperations // script. They are based on the defaults in the VS Code Language Configuration at; // https://github.com/Microsoft/vscode/blob/64186b0a26/extensions/powershell/language-configuration.json#L26-L31 // https://github.com/Microsoft/vscode/issues/49070 - static private readonly Regex s_startRegionTextRegex = new Regex( + private static readonly Regex s_startRegionTextRegex = new( @"^\s*#[rR]egion\b", RegexOptions.Compiled); - static private readonly Regex s_endRegionTextRegex = new Regex( + private static readonly Regex s_endRegionTextRegex = new( @"^\s*#[eE]nd[rR]egion\b", RegexOptions.Compiled); /// @@ -31,10 +31,10 @@ internal static class TokenOperations internal static FoldingReferenceList FoldableReferences( Token[] tokens) { - var refList = new FoldingReferenceList(); + FoldingReferenceList refList = new(); - Stack tokenCurlyStack = new Stack(); - Stack tokenParenStack = new Stack(); + Stack tokenCurlyStack = new(); + Stack tokenParenStack = new(); foreach (Token token in tokens) { switch (token.Kind) @@ -95,7 +95,7 @@ internal static FoldingReferenceList FoldableReferences( // // Find comments regions <# -> #> // Match the token start and end of kind TokenKind.Comment - var tokenCommentRegionStack = new Stack(); + Stack tokenCommentRegionStack = new(); Token blockStartToken = null; int blockNextLine = -1; @@ -156,19 +156,20 @@ internal static FoldingReferenceList FoldableReferences( /// Creates an instance of a FoldingReference object from a start and end langauge Token /// Returns null if the line range is invalid /// - static private FoldingReference CreateFoldingReference( + private static FoldingReference CreateFoldingReference( Token startToken, Token endToken, FoldingRangeKind? matchKind) { if (endToken.Extent.EndLineNumber == startToken.Extent.StartLineNumber) { return null; } // Extents are base 1, but LSP is base 0, so minus 1 off all lines and character positions - return new FoldingReference { - StartLine = startToken.Extent.StartLineNumber - 1, + return new FoldingReference + { + StartLine = startToken.Extent.StartLineNumber - 1, StartCharacter = startToken.Extent.StartColumnNumber - 1, - EndLine = endToken.Extent.EndLineNumber - 1, - EndCharacter = endToken.Extent.EndColumnNumber - 1, - Kind = matchKind + EndLine = endToken.Extent.EndLineNumber - 1, + EndCharacter = endToken.Extent.EndColumnNumber - 1, + Kind = matchKind }; } @@ -176,19 +177,20 @@ static private FoldingReference CreateFoldingReference( /// Creates an instance of a FoldingReference object from a start token and an end line /// Returns null if the line range is invalid /// - static private FoldingReference CreateFoldingReference( + private static FoldingReference CreateFoldingReference( Token startToken, int endLine, FoldingRangeKind? matchKind) { if (endLine == (startToken.Extent.StartLineNumber - 1)) { return null; } // Extents are base 1, but LSP is base 0, so minus 1 off all lines and character positions - return new FoldingReference { - StartLine = startToken.Extent.StartLineNumber - 1, + return new FoldingReference + { + StartLine = startToken.Extent.StartLineNumber - 1, StartCharacter = startToken.Extent.StartColumnNumber - 1, - EndLine = endLine, - EndCharacter = 0, - Kind = matchKind + EndLine = endLine, + EndCharacter = 0, + Kind = matchKind }; } @@ -199,7 +201,8 @@ static private FoldingReference CreateFoldingReference( /// - Token text must start with a '#'.false This is because comment regions /// start with '<#' but have the same TokenKind /// - static private bool IsBlockComment(int index, Token[] tokens) { + private static bool IsBlockComment(int index, Token[] tokens) + { Token thisToken = tokens[index]; if (thisToken.Kind != TokenKind.Comment) { return false; } if (index == 0) { return true; } diff --git a/src/PowerShellEditorServices/Services/Workspace/Handlers/WorkspaceSymbolsHandler.cs b/src/PowerShellEditorServices/Services/Workspace/Handlers/WorkspaceSymbolsHandler.cs index fa31308d0..ad36d25fc 100644 --- a/src/PowerShellEditorServices/Services/Workspace/Handlers/WorkspaceSymbolsHandler.cs +++ b/src/PowerShellEditorServices/Services/Workspace/Handlers/WorkspaceSymbolsHandler.cs @@ -23,17 +23,18 @@ internal class PsesWorkspaceSymbolsHandler : WorkspaceSymbolsHandlerBase private readonly SymbolsService _symbolsService; private readonly WorkspaceService _workspaceService; - public PsesWorkspaceSymbolsHandler(ILoggerFactory loggerFactory, SymbolsService symbols, WorkspaceService workspace) { + public PsesWorkspaceSymbolsHandler(ILoggerFactory loggerFactory, SymbolsService symbols, WorkspaceService workspace) + { _logger = loggerFactory.CreateLogger(); _symbolsService = symbols; _workspaceService = workspace; } - protected override WorkspaceSymbolRegistrationOptions CreateRegistrationOptions(WorkspaceSymbolCapability capability, ClientCapabilities clientCapabilities) => new WorkspaceSymbolRegistrationOptions { }; + protected override WorkspaceSymbolRegistrationOptions CreateRegistrationOptions(WorkspaceSymbolCapability capability, ClientCapabilities clientCapabilities) => new() { }; public override Task> Handle(WorkspaceSymbolParams request, CancellationToken cancellationToken) { - var symbols = new List(); + List symbols = new(); foreach (ScriptFile scriptFile in _workspaceService.GetOpenedFiles()) { @@ -51,7 +52,7 @@ public override Task> Handle(WorkspaceSymbolParams continue; } - var location = new Location + Location location = new() { Uri = DocumentUri.From(foundOccurrence.FilePath), Range = GetRangeFromScriptRegion(foundOccurrence.ScriptRegion) @@ -73,10 +74,7 @@ public override Task> Handle(WorkspaceSymbolParams #region private Methods - private static bool IsQueryMatch(string query, string symbolName) - { - return symbolName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0; - } + private static bool IsQueryMatch(string query, string symbolName) => symbolName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0; private static Range GetRangeFromScriptRegion(ScriptRegion scriptRegion) { @@ -99,9 +97,9 @@ private static string GetDecoratedSymbolName(SymbolReference symbolReference) { string name = symbolReference.SymbolName; - if (symbolReference.SymbolType == SymbolType.Configuration || - symbolReference.SymbolType == SymbolType.Function || - symbolReference.SymbolType == SymbolType.Workflow) + if (symbolReference.SymbolType is SymbolType.Configuration or + SymbolType.Function or + SymbolType.Workflow) { name += " { }"; } diff --git a/src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs b/src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs index 8e597e621..0e82efea5 100644 --- a/src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs +++ b/src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs @@ -56,7 +56,7 @@ internal class ScriptAnalysisSettings private readonly object updateLock = new(); public bool? Enable { get; set; } public string SettingsPath { get; set; } - public ScriptAnalysisSettings() { Enable = true; } + public ScriptAnalysisSettings() => Enable = true; public void Update( ScriptAnalysisSettings settings, @@ -86,7 +86,7 @@ public void Update( // In this case we should just log an error and let // the specified settings path go through even though // it will fail to load. - logger.LogError( "Could not resolve Script Analyzer settings path due to null or empty workspaceRootPath."); + logger.LogError("Could not resolve Script Analyzer settings path due to null or empty workspaceRootPath."); } else { @@ -252,24 +252,35 @@ private Hashtable GetCustomPSSASettingsHashtable(int tabSize, bool insertSpaces) { Hashtable ruleConfigurations = new() { - { "PSPlaceOpenBrace", new Hashtable { + { + "PSPlaceOpenBrace", + new Hashtable { { "Enable", true }, { "OnSameLine", OpenBraceOnSameLine }, { "NewLineAfter", NewLineAfterOpenBrace }, { "IgnoreOneLineBlock", IgnoreOneLineBlock } - }}, - { "PSPlaceCloseBrace", new Hashtable { + } + }, + { + "PSPlaceCloseBrace", + new Hashtable { { "Enable", true }, { "NewLineAfter", NewLineAfterCloseBrace }, { "IgnoreOneLineBlock", IgnoreOneLineBlock } - }}, - { "PSUseConsistentIndentation", new Hashtable { + } + }, + { + "PSUseConsistentIndentation", + new Hashtable { { "Enable", true }, { "IndentationSize", tabSize }, { "PipelineIndentation", PipelineIndentationStyle }, { "Kind", insertSpaces ? "space" : "tab" } - }}, - { "PSUseConsistentWhitespace", new Hashtable { + } + }, + { + "PSUseConsistentWhitespace", + new Hashtable { { "Enable", true }, { "CheckOpenBrace", WhitespaceBeforeOpenBrace }, { "CheckOpenParen", WhitespaceBeforeOpenParen }, @@ -279,17 +290,27 @@ private Hashtable GetCustomPSSASettingsHashtable(int tabSize, bool insertSpaces) { "CheckParameter", WhitespaceBetweenParameters }, { "CheckPipe", AddWhitespaceAroundPipe }, { "CheckPipeForRedundantWhitespace", TrimWhitespaceAroundPipe }, - }}, - { "PSAlignAssignmentStatement", new Hashtable { + } + }, + { + "PSAlignAssignmentStatement", + new Hashtable { { "Enable", true }, { "CheckHashtable", AlignPropertyValuePairs } - }}, - { "PSUseCorrectCasing", new Hashtable { + } + }, + { + "PSUseCorrectCasing", + new Hashtable { { "Enable", UseCorrectCasing } - }}, - { "PSAvoidUsingDoubleQuotesForConstantString", new Hashtable { + } + }, + { + "PSAvoidUsingDoubleQuotesForConstantString", + new Hashtable { { "Enable", UseConstantStrings } - }}, + } + }, }; if (AutoCorrectAliases) diff --git a/src/PowerShellEditorServices/Services/Workspace/RemoteFileManagerService.cs b/src/PowerShellEditorServices/Services/Workspace/RemoteFileManagerService.cs index 4ff1b98f6..4171d33e6 100644 --- a/src/PowerShellEditorServices/Services/Workspace/RemoteFileManagerService.cs +++ b/src/PowerShellEditorServices/Services/Workspace/RemoteFileManagerService.cs @@ -32,15 +32,15 @@ internal class RemoteFileManagerService { #region Fields - private ILogger logger; - private string remoteFilesPath; - private string processTempPath; + private readonly ILogger logger; + private readonly string remoteFilesPath; + private readonly string processTempPath; private readonly IRunspaceContext _runspaceContext; private readonly IInternalPowerShellExecutionService _executionService; - private IEditorOperations editorOperations; + private readonly IEditorOperations editorOperations; - private Dictionary filesPerComputer = - new Dictionary(); + private readonly Dictionary filesPerComputer = + new(); private const string RemoteSessionOpenFile = "PSESRemoteSessionOpenFile"; @@ -258,26 +258,26 @@ public RemoteFileManagerService( IInternalPowerShellExecutionService executionService, EditorOperationsService editorOperations) { - this.logger = factory.CreateLogger(); + logger = factory.CreateLogger(); _runspaceContext = runspaceContext; _executionService = executionService; _executionService.RunspaceChanged += HandleRunspaceChanged; this.editorOperations = editorOperations; - this.processTempPath = + processTempPath = Path.Combine( Path.GetTempPath(), "PSES-" + Process.GetCurrentProcess().Id); - this.remoteFilesPath = Path.Combine(this.processTempPath, "RemoteFiles"); + remoteFilesPath = Path.Combine(processTempPath, "RemoteFiles"); // Delete existing temporary file cache path if it already exists - this.TryDeleteTemporaryPath(); + TryDeleteTemporaryPath(); // TODO: Do this somewhere other than the constructor and make it async // Register the psedit function in the current runspace - this.RegisterPSEditFunctionAsync().HandleErrorsAsync(logger); + RegisterPSEditFunctionAsync().HandleErrorsAsync(logger); } #endregion @@ -306,8 +306,8 @@ public async Task FetchRemoteFileAsync( { try { - RemotePathMappings pathMappings = this.GetPathMappings(runspaceInfo); - localFilePath = this.GetMappedPath(remoteFilePath, runspaceInfo); + RemotePathMappings pathMappings = GetPathMappings(runspaceInfo); + localFilePath = GetMappedPath(remoteFilePath, runspaceInfo); if (!pathMappings.IsRemotePathOpened(remoteFilePath)) { @@ -330,7 +330,7 @@ public async Task FetchRemoteFileAsync( } byte[] fileContent = - (await this._executionService.ExecutePSCommandAsync(command, CancellationToken.None).ConfigureAwait(false)) + (await _executionService.ExecutePSCommandAsync(command, CancellationToken.None).ConfigureAwait(false)) .FirstOrDefault(); if (fileContent != null) @@ -339,7 +339,7 @@ public async Task FetchRemoteFileAsync( } else { - this.logger.LogWarning( + logger.LogWarning( $"Could not load contents of remote file '{remoteFilePath}'"); } } @@ -347,8 +347,8 @@ public async Task FetchRemoteFileAsync( } catch (IOException e) { - this.logger.LogError( - $"Caught {e.GetType().Name} while attempting to get remote file at path '{remoteFilePath}'\r\n\r\n{e.ToString()}"); + logger.LogError( + $"Caught {e.GetType().Name} while attempting to get remote file at path '{remoteFilePath}'\r\n\r\n{e}"); } } @@ -368,11 +368,11 @@ public async Task FetchRemoteFileAsync( public async Task SaveRemoteFileAsync(string localFilePath) { string remoteFilePath = - this.GetMappedPath( + GetMappedPath( localFilePath, _runspaceContext.CurrentRunspace); - this.logger.LogTrace( + logger.LogTrace( $"Saving remote file {remoteFilePath} (local path: {localFilePath})"); byte[] localFileContents = null; @@ -382,14 +382,14 @@ public async Task SaveRemoteFileAsync(string localFilePath) } catch (IOException e) { - this.logger.LogException( + logger.LogException( "Failed to read contents of local copy of remote file", e); return; } - PSCommand saveCommand = new PSCommand(); + PSCommand saveCommand = new(); saveCommand .AddScript(SetRemoteContentsScript) .AddParameter("RemoteFilePath", remoteFilePath) @@ -403,7 +403,7 @@ await _executionService.ExecutePSCommandAsync( } catch (Exception e) { - this.logger.LogError(e, "Remote file save failed"); + logger.LogError(e, "Remote file save failed"); } } @@ -423,19 +423,19 @@ await _executionService.ExecutePSCommandAsync( /// The full temporary path of the file if successful, null otherwise. public string CreateTemporaryFile(string fileName, string fileContents, IRunspaceInfo runspaceInfo) { - string temporaryFilePath = Path.Combine(this.processTempPath, fileName); + string temporaryFilePath = Path.Combine(processTempPath, fileName); try { File.WriteAllText(temporaryFilePath, fileContents); - RemotePathMappings pathMappings = this.GetPathMappings(runspaceInfo); + RemotePathMappings pathMappings = GetPathMappings(runspaceInfo); pathMappings.AddOpenedLocalPath(temporaryFilePath); } catch (IOException e) { - this.logger.LogError( - $"Caught {e.GetType().Name} while attempting to write temporary file at path '{temporaryFilePath}'\r\n\r\n{e.ToString()}"); + logger.LogError( + $"Caught {e.GetType().Name} while attempting to write temporary file at path '{temporaryFilePath}'\r\n\r\n{e}"); temporaryFilePath = null; } @@ -458,7 +458,7 @@ public string GetMappedPath( string filePath, IRunspaceInfo runspaceDetails) { - RemotePathMappings remotePathMappings = this.GetPathMappings(runspaceDetails); + RemotePathMappings remotePathMappings = GetPathMappings(runspaceDetails); return remotePathMappings.GetMappedPath(filePath); } @@ -473,7 +473,7 @@ public string GetMappedPath( public bool IsUnderRemoteTempPath(string filePath) { return filePath.StartsWith( - this.remoteFilesPath, + remoteFilesPath, System.StringComparison.CurrentCultureIgnoreCase); } @@ -486,7 +486,7 @@ private string StoreRemoteFile( byte[] fileContent, IRunspaceInfo runspaceInfo) { - RemotePathMappings pathMappings = this.GetPathMappings(runspaceInfo); + RemotePathMappings pathMappings = GetPathMappings(runspaceInfo); string localFilePath = pathMappings.GetMappedPath(remoteFilePath); RemoteFileManagerService.StoreRemoteFile( @@ -510,10 +510,10 @@ private RemotePathMappings GetPathMappings(IRunspaceInfo runspaceInfo) { string computerName = runspaceInfo.SessionDetails.ComputerName; - if (!this.filesPerComputer.TryGetValue(computerName, out RemotePathMappings remotePathMappings)) + if (!filesPerComputer.TryGetValue(computerName, out RemotePathMappings remotePathMappings)) { remotePathMappings = new RemotePathMappings(runspaceInfo, this); - this.filesPerComputer.Add(computerName, remotePathMappings); + filesPerComputer.Add(computerName, remotePathMappings); } return remotePathMappings; @@ -523,20 +523,19 @@ private void HandleRunspaceChanged(object sender, RunspaceChangedEventArgs e) { if (e.ChangeAction == RunspaceChangeAction.Enter) { - this.RegisterPSEditFunction(e.NewRunspace.Runspace); + RegisterPSEditFunction(e.NewRunspace.Runspace); return; } // Close any remote files that were opened if (ShouldTearDownRemoteFiles(e)) { - RemotePathMappings remotePathMappings; - if (this.filesPerComputer.TryGetValue(e.PreviousRunspace.SessionDetails.ComputerName, out remotePathMappings)) + if (filesPerComputer.TryGetValue(e.PreviousRunspace.SessionDetails.ComputerName, out RemotePathMappings remotePathMappings)) { - var fileCloseTasks = new List(); + List fileCloseTasks = new(); foreach (string remotePath in remotePathMappings.OpenedPaths) { - fileCloseTasks.Add(this.editorOperations?.CloseFileAsync(remotePath)); + fileCloseTasks.Add(editorOperations?.CloseFileAsync(remotePath)); } try @@ -545,14 +544,14 @@ private void HandleRunspaceChanged(object sender, RunspaceChangedEventArgs e) } catch (Exception ex) { - this.logger.LogError(ex, "Unable to close all files in closed runspace"); + logger.LogError(ex, "Unable to close all files in closed runspace"); } } } if (e.PreviousRunspace != null) { - this.RemovePSEditFunction(e.PreviousRunspace); + RemovePSEditFunction(e.PreviousRunspace); } } @@ -601,33 +600,25 @@ private async void HandlePSEventReceivedAsync(object sender, PSEventArgs args) if (args.SourceArgs.Length >= 2) { // Try to cast as a PSObject to get the BaseObject, if not, then try to case as a byte[] - PSObject sourceObj = args.SourceArgs[1] as PSObject; - if (sourceObj != null) - { - fileContent = sourceObj.BaseObject as byte[]; - } - else - { - fileContent = args.SourceArgs[1] as byte[]; - } + fileContent = args.SourceArgs[1] is PSObject sourceObj ? sourceObj.BaseObject as byte[] : args.SourceArgs[1] as byte[]; } // If fileContent is still null after trying to // unpack the contents, just return an empty byte // array. - fileContent = fileContent ?? Array.Empty(); + fileContent ??= Array.Empty(); if (remoteFilePath != null) { localFilePath = - this.StoreRemoteFile( + StoreRemoteFile( remoteFilePath, fileContent, _runspaceContext.CurrentRunspace); } else { - await (this.editorOperations?.NewFileAsync()).ConfigureAwait(false); + await (editorOperations?.NewFileAsync()).ConfigureAwait(false); EditorContext context = await (editorOperations?.GetEditorContextAsync()).ConfigureAwait(false); context?.CurrentFile.InsertText(Encoding.UTF8.GetString(fileContent, 0, fileContent.Length)); } @@ -641,16 +632,16 @@ private async void HandlePSEventReceivedAsync(object sender, PSEventArgs args) } // Open the file in the editor - await (this.editorOperations?.OpenFileAsync(localFilePath, preview)).ConfigureAwait(false); + await (editorOperations?.OpenFileAsync(localFilePath, preview)).ConfigureAwait(false); } } catch (NullReferenceException e) { - this.logger.LogException("Could not store null remote file content", e); + logger.LogException("Could not store null remote file content", e); } catch (Exception e) { - this.logger.LogException("Unable to handle remote file update", e); + logger.LogException("Unable to handle remote file update", e); } } @@ -674,7 +665,7 @@ private void RegisterPSEditFunction(Runspace runspace) .AddScript(CreatePSEditFunctionScript) .AddParameter("PSEditModule", PSEditModule); - var pwsh = SMA.PowerShell.Create(); + SMA.PowerShell pwsh = SMA.PowerShell.Create(); pwsh.Runspace = runspace; try { @@ -682,7 +673,7 @@ private void RegisterPSEditFunction(Runspace runspace) } catch (Exception e) { - this.logger.LogException("Could not create psedit function.", e); + logger.LogException("Could not create psedit function.", e); } finally { @@ -705,17 +696,15 @@ private void RemovePSEditFunction(IRunspaceInfo runspaceInfo) if (runspaceInfo.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) { - using (var powerShell = SMA.PowerShell.Create()) - { - powerShell.Runspace = runspaceInfo.Runspace; - powerShell.Commands.AddScript(RemovePSEditFunctionScript); - powerShell.Invoke(); - } + using SMA.PowerShell powerShell = SMA.PowerShell.Create(); + powerShell.Runspace = runspaceInfo.Runspace; + powerShell.Commands.AddScript(RemovePSEditFunctionScript); + powerShell.Invoke(); } } - catch (Exception e) when (e is RemoteException || e is PSInvalidOperationException) + catch (Exception e) when (e is RemoteException or PSInvalidOperationException) { - this.logger.LogException("Could not remove psedit function.", e); + logger.LogException("Could not remove psedit function.", e); } } @@ -723,17 +712,17 @@ private void TryDeleteTemporaryPath() { try { - if (Directory.Exists(this.processTempPath)) + if (Directory.Exists(processTempPath)) { - Directory.Delete(this.processTempPath, true); + Directory.Delete(processTempPath, true); } - Directory.CreateDirectory(this.processTempPath); + Directory.CreateDirectory(processTempPath); } catch (IOException e) { - this.logger.LogException( - $"Could not delete temporary folder for current process: {this.processTempPath}", e); + logger.LogException( + $"Could not delete temporary folder for current process: {processTempPath}", e); } } @@ -743,15 +732,12 @@ private void TryDeleteTemporaryPath() private class RemotePathMappings { - private IRunspaceInfo runspaceInfo; - private RemoteFileManagerService remoteFileManager; - private HashSet openedPaths = new HashSet(); - private Dictionary pathMappings = new Dictionary(); + private readonly IRunspaceInfo runspaceInfo; + private readonly RemoteFileManagerService remoteFileManager; + private readonly HashSet openedPaths = new(); + private readonly Dictionary pathMappings = new(); - public IEnumerable OpenedPaths - { - get { return openedPaths; } - } + public IEnumerable OpenedPaths => openedPaths; public RemotePathMappings( IRunspaceInfo runspaceInfo, @@ -764,35 +750,29 @@ public RemotePathMappings( public void AddPathMapping(string remotePath, string localPath) { // Add mappings in both directions - this.pathMappings[localPath.ToLower()] = remotePath; - this.pathMappings[remotePath.ToLower()] = localPath; + pathMappings[localPath.ToLower()] = remotePath; + pathMappings[remotePath.ToLower()] = localPath; } - public void AddOpenedLocalPath(string openedLocalPath) - { - this.openedPaths.Add(openedLocalPath); - } + public void AddOpenedLocalPath(string openedLocalPath) => openedPaths.Add(openedLocalPath); - public bool IsRemotePathOpened(string remotePath) - { - return this.openedPaths.Contains(remotePath); - } + public bool IsRemotePathOpened(string remotePath) => openedPaths.Contains(remotePath); public string GetMappedPath(string filePath) { string mappedPath = filePath; - if (!this.pathMappings.TryGetValue(filePath.ToLower(), out mappedPath)) + if (!pathMappings.TryGetValue(filePath.ToLower(), out mappedPath)) { // If the path isn't mapped yet, generate it - if (!filePath.StartsWith(this.remoteFileManager.remoteFilesPath)) + if (!filePath.StartsWith(remoteFileManager.remoteFilesPath)) { mappedPath = - this.MapRemotePathToLocal( + MapRemotePathToLocal( filePath, runspaceInfo.SessionDetails.ComputerName); - this.AddPathMapping(filePath, mappedPath); + AddPathMapping(filePath, mappedPath); } } @@ -810,12 +790,12 @@ private string MapRemotePathToLocal(string remotePath, string connectionString) // as the differentiator string in editors like VS Code when more than // one tab has the same filename. - var sessionDir = Directory.CreateDirectory(this.remoteFileManager.remoteFilesPath); - var pathHashDir = + DirectoryInfo sessionDir = Directory.CreateDirectory(remoteFileManager.remoteFilesPath); + DirectoryInfo pathHashDir = sessionDir.CreateSubdirectory( Path.GetDirectoryName(remotePath).GetHashCode().ToString()); - var remoteFileDir = pathHashDir.CreateSubdirectory(connectionString); + DirectoryInfo remoteFileDir = pathHashDir.CreateSubdirectory(connectionString); return Path.Combine( diff --git a/src/PowerShellEditorServices/Services/Workspace/WorkspaceFileSystemWrapper.cs b/src/PowerShellEditorServices/Services/Workspace/WorkspaceFileSystemWrapper.cs index fcf2ed9ce..4ffe8021b 100644 --- a/src/PowerShellEditorServices/Services/Workspace/WorkspaceFileSystemWrapper.cs +++ b/src/PowerShellEditorServices/Services/Workspace/WorkspaceFileSystemWrapper.cs @@ -19,7 +19,6 @@ namespace Microsoft.PowerShell.EditorServices.Services.Workspace /// internal class WorkspaceFileSystemWrapperFactory { - private readonly DirectoryInfoBase _rootDirectory; private readonly string[] _allowedExtensions; private readonly bool _ignoreReparsePoints; @@ -37,10 +36,7 @@ internal class WorkspaceFileSystemWrapperFactory /// Gets the directory where the factory is rooted. Only files and directories at this level, or deeper, will be visible /// by the wrapper /// - public DirectoryInfoBase RootDirectory - { - get { return _rootDirectory; } - } + public DirectoryInfoBase RootDirectory { get; } /// /// Creates a new FileWrapper Factory @@ -50,23 +46,23 @@ public DirectoryInfoBase RootDirectory /// An array of file extensions that will be visible from the factory. For example [".ps1", ".psm1"] /// Whether objects which are Reparse Points should be ignored. https://docs.microsoft.com/en-us/windows/desktop/fileio/reparse-points /// An ILogger implementation used for writing log messages. - public WorkspaceFileSystemWrapperFactory(String rootPath, int recursionDepthLimit, string[] allowedExtensions, bool ignoreReparsePoints, ILogger logger) + public WorkspaceFileSystemWrapperFactory(string rootPath, int recursionDepthLimit, string[] allowedExtensions, bool ignoreReparsePoints, ILogger logger) { MaxRecursionDepth = recursionDepthLimit; - _rootDirectory = new WorkspaceFileSystemDirectoryWrapper(this, new DirectoryInfo(rootPath), 0); + RootDirectory = new WorkspaceFileSystemDirectoryWrapper(this, new DirectoryInfo(rootPath), 0); _allowedExtensions = allowedExtensions; _ignoreReparsePoints = ignoreReparsePoints; Logger = logger; } /// - /// Creates a wrapped object from . + /// Creates a wrapped object from . /// internal DirectoryInfoBase CreateDirectoryInfoWrapper(DirectoryInfo dirInfo, int depth) => new WorkspaceFileSystemDirectoryWrapper(this, dirInfo, depth >= 0 ? depth : 0); /// - /// Creates a wrapped object from . + /// Creates a wrapped object from . /// internal FileInfoBase CreateFileInfoWrapper(FileInfo fileInfo, int depth) => new WorkspaceFileSystemFileInfoWrapper(this, fileInfo, depth >= 0 ? depth : 0); @@ -98,7 +94,7 @@ internal IEnumerable SafeEnumerateFileSystemInfos(DirectoryInfo yield break; } - catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) + catch (Exception e) when (e is SecurityException or UnauthorizedAccessException) { Logger.LogHandledException( $"Could not enumerate directories in the path '{dirInfo.FullName}' due to the path not being accessible", @@ -116,7 +112,7 @@ internal IEnumerable SafeEnumerateFileSystemInfos(DirectoryInfo } foreach (string dirPath in subDirs) { - var subDirInfo = new DirectoryInfo(dirPath); + DirectoryInfo subDirInfo = new(dirPath); if (_ignoreReparsePoints && (subDirInfo.Attributes & FileAttributes.ReparsePoint) != 0) { continue; } yield return subDirInfo; } @@ -143,7 +139,7 @@ internal IEnumerable SafeEnumerateFileSystemInfos(DirectoryInfo yield break; } - catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) + catch (Exception e) when (e is SecurityException or UnauthorizedAccessException) { Logger.LogHandledException( $"Could not enumerate files in the path '{dirInfo.FullName}' due to the path not being accessible", @@ -161,7 +157,7 @@ internal IEnumerable SafeEnumerateFileSystemInfos(DirectoryInfo } foreach (string filePath in filePaths) { - var fileInfo = new FileInfo(filePath); + FileInfo fileInfo = new(filePath); if (_allowedExtensions == null || _allowedExtensions.Length == 0) { yield return fileInfo; continue; } if (_ignoreReparsePoints && (fileInfo.Attributes & FileAttributes.ReparsePoint) != 0) { continue; } foreach (string extension in _allowedExtensions) @@ -173,8 +169,8 @@ internal IEnumerable SafeEnumerateFileSystemInfos(DirectoryInfo } /// - /// Wraps an instance of and provides implementation of - /// . + /// Wraps an instance of and provides implementation of + /// . /// Based on https://github.com/aspnet/Extensions/blob/c087cadf1dfdbd2b8785ef764e5ef58a1a7e5ed0/src/FileSystemGlobbing/src/Abstractions/DirectoryInfoWrapper.cs /// internal class WorkspaceFileSystemDirectoryWrapper : DirectoryInfoBase @@ -190,7 +186,7 @@ internal class WorkspaceFileSystemDirectoryWrapper : DirectoryInfoBase public WorkspaceFileSystemDirectoryWrapper(WorkspaceFileSystemWrapperFactory factory, DirectoryInfo directoryInfo, int depth) { _concreteDirectoryInfo = directoryInfo; - _isParentPath = (depth == 0); + _isParentPath = depth == 0; _fsWrapperFactory = factory; _depth = depth; } @@ -230,7 +226,7 @@ public override DirectoryInfoBase GetDirectory(string name) if (isParentPath) { return ParentDirectory; } - var dirs = _concreteDirectoryInfo.GetDirectories(name); + DirectoryInfo[] dirs = _concreteDirectoryInfo.GetDirectories(name); if (dirs.Length == 1) { return _fsWrapperFactory.CreateDirectoryInfoWrapper(dirs[0], _depth + 1); } if (dirs.Length == 0) { return null; } @@ -274,7 +270,7 @@ private DirectoryInfoBase SafeParentDirectory() $"Could not get parent of '{_concreteDirectoryInfo.FullName}' due to the path being too long", e); } - catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) + catch (Exception e) when (e is SecurityException or UnauthorizedAccessException) { _fsWrapperFactory.Logger.LogHandledException( $"Could not get parent of '{_concreteDirectoryInfo.FullName}' due to the path not being accessible", @@ -290,19 +286,13 @@ private DirectoryInfoBase SafeParentDirectory() } /// - /// Returns the parent directory. (Overrides ). + /// Returns the parent directory. (Overrides ). /// - public override DirectoryInfoBase ParentDirectory - { - get - { - return SafeParentDirectory(); - } - } + public override DirectoryInfoBase ParentDirectory => SafeParentDirectory(); } /// - /// Wraps an instance of to provide implementation of . + /// Wraps an instance of to provide implementation of . /// internal class WorkspaceFileSystemFileInfoWrapper : FileInfoBase { @@ -311,7 +301,7 @@ internal class WorkspaceFileSystemFileInfoWrapper : FileInfoBase private readonly int _depth; /// - /// Initializes instance of to wrap the specified object . + /// Initializes instance of to wrap the specified object . /// public WorkspaceFileSystemFileInfoWrapper(WorkspaceFileSystemWrapperFactory factory, FileInfo fileInfo, int depth) { @@ -321,12 +311,12 @@ public WorkspaceFileSystemFileInfoWrapper(WorkspaceFileSystemWrapperFactory fact } /// - /// The file name. (Overrides ). + /// The file name. (Overrides ). /// public override string Name => _concreteFileInfo.Name; /// - /// The full path of the file. (Overrides ). + /// The full path of the file. (Overrides ). /// public override string FullName => _concreteFileInfo.FullName; @@ -351,7 +341,7 @@ private DirectoryInfoBase SafeParentDirectory() $"Could not get parent of '{_concreteFileInfo.FullName}' due to the path being too long", e); } - catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) + catch (Exception e) when (e is SecurityException or UnauthorizedAccessException) { _fsWrapperFactory.Logger.LogHandledException( $"Could not get parent of '{_concreteFileInfo.FullName}' due to the path not being accessible", @@ -367,14 +357,8 @@ private DirectoryInfoBase SafeParentDirectory() } /// - /// The directory containing the file. (Overrides ). + /// The directory containing the file. (Overrides ). /// - public override DirectoryInfoBase ParentDirectory - { - get - { - return SafeParentDirectory(); - } - } + public override DirectoryInfoBase ParentDirectory => SafeParentDirectory(); } } diff --git a/src/PowerShellEditorServices/Services/Workspace/WorkspaceService.cs b/src/PowerShellEditorServices/Services/Workspace/WorkspaceService.cs index b999da6c4..9ecbb1137 100644 --- a/src/PowerShellEditorServices/Services/Workspace/WorkspaceService.cs +++ b/src/PowerShellEditorServices/Services/Workspace/WorkspaceService.cs @@ -45,14 +45,14 @@ internal class WorkspaceService }; // An array of globs which includes everything. - private static readonly string[] s_psIncludeAllGlob = new [] + private static readonly string[] s_psIncludeAllGlob = new[] { "**/*" }; private readonly ILogger logger; private readonly Version powerShellVersion; - private readonly ConcurrentDictionary workspaceFiles = new ConcurrentDictionary(); + private readonly ConcurrentDictionary workspaceFiles = new(); #endregion @@ -84,10 +84,10 @@ internal class WorkspaceService /// An ILogger implementation used for writing log messages. public WorkspaceService(ILoggerFactory factory) { - this.powerShellVersion = VersionUtils.PSVersion; - this.logger = factory.CreateLogger(); - this.ExcludeFilesGlob = new List(); - this.FollowSymlinks = true; + powerShellVersion = VersionUtils.PSVersion; + logger = factory.CreateLogger(); + ExcludeFilesGlob = new List(); + FollowSymlinks = true; } #endregion @@ -97,7 +97,7 @@ public WorkspaceService(ILoggerFactory factory) /// /// Gets an open file in the workspace. If the file isn't open but exists on the filesystem, load and return it. /// IMPORTANT: Not all documents have a backing file e.g. untitled: scheme documents. Consider using - /// instead. + /// instead. /// /// The file path at which the script resides. /// @@ -111,7 +111,7 @@ public WorkspaceService(ILoggerFactory factory) /// /// Gets an open file in the workspace. If the file isn't open but exists on the filesystem, load and return it. /// IMPORTANT: Not all documents have a backing file e.g. untitled: scheme documents. Consider using - /// instead. + /// instead. /// /// The file URI at which the script resides. /// @@ -125,7 +125,7 @@ public WorkspaceService(ILoggerFactory factory) /// /// Gets an open file in the workspace. If the file isn't open but exists on the filesystem, load and return it. /// IMPORTANT: Not all documents have a backing file e.g. untitled: scheme documents. Consider using - /// instead. + /// instead. /// /// The document URI at which the script resides. /// @@ -143,23 +143,23 @@ public ScriptFile GetFile(DocumentUri documentUri) : documentUri.ToString().ToLower(); // Make sure the file isn't already loaded into the workspace - if (!this.workspaceFiles.TryGetValue(keyName, out ScriptFile scriptFile)) + if (!workspaceFiles.TryGetValue(keyName, out ScriptFile scriptFile)) { // This method allows FileNotFoundException to bubble up // if the file isn't found. - using (FileStream fileStream = new FileStream(documentUri.GetFileSystemPath(), FileMode.Open, FileAccess.Read)) - using (StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8)) + using (FileStream fileStream = new(documentUri.GetFileSystemPath(), FileMode.Open, FileAccess.Read)) + using (StreamReader streamReader = new(fileStream, Encoding.UTF8)) { scriptFile = new ScriptFile( documentUri, streamReader, - this.powerShellVersion); + powerShellVersion); - this.workspaceFiles[keyName] = scriptFile; + workspaceFiles[keyName] = scriptFile; } - this.logger.LogDebug("Opened file on disk: " + documentUri.ToString()); + logger.LogDebug("Opened file on disk: " + documentUri.ToString()); } return scriptFile; @@ -208,15 +208,15 @@ public bool TryGetFile(DocumentUri documentUri, out ScriptFile scriptFile) return true; } catch (Exception e) when ( - e is NotSupportedException || - e is FileNotFoundException || - e is DirectoryNotFoundException || - e is PathTooLongException || - e is IOException || - e is SecurityException || - e is UnauthorizedAccessException) + e is NotSupportedException or + FileNotFoundException or + DirectoryNotFoundException or + PathTooLongException or + IOException or + SecurityException or + UnauthorizedAccessException) { - this.logger.LogWarning($"Failed to get file for fileUri: '{documentUri.ToString()}'", e); + logger.LogWarning($"Failed to get file for fileUri: '{documentUri}'", e); scriptFile = null; return false; } @@ -270,17 +270,17 @@ public ScriptFile GetFileBuffer(DocumentUri documentUri, string initialBuffer) : documentUri.ToString().ToLower(); // Make sure the file isn't already loaded into the workspace - if (!this.workspaceFiles.TryGetValue(keyName, out ScriptFile scriptFile) && initialBuffer != null) + if (!workspaceFiles.TryGetValue(keyName, out ScriptFile scriptFile) && initialBuffer != null) { scriptFile = new ScriptFile( documentUri, initialBuffer, - this.powerShellVersion); + powerShellVersion); - this.workspaceFiles[keyName] = scriptFile; + workspaceFiles[keyName] = scriptFile; - this.logger.LogDebug("Opened file as in-memory buffer: " + documentUri.ToString()); + logger.LogDebug("Opened file as in-memory buffer: " + documentUri.ToString()); } return scriptFile; @@ -290,10 +290,7 @@ public ScriptFile GetFileBuffer(DocumentUri documentUri, string initialBuffer) /// Gets an array of all opened ScriptFiles in the workspace. /// /// An array of all opened ScriptFiles in the workspace. - public ScriptFile[] GetOpenedFiles() - { - return workspaceFiles.Values.ToArray(); - } + public ScriptFile[] GetOpenedFiles() => workspaceFiles.Values.ToArray(); /// /// Closes a currently open script file with the given file path. @@ -303,7 +300,7 @@ public void CloseFile(ScriptFile scriptFile) { Validate.IsNotNull("scriptFile", scriptFile); - this.workspaceFiles.TryRemove(scriptFile.Id, out ScriptFile _); + workspaceFiles.TryRemove(scriptFile.Id, out ScriptFile _); } /// @@ -315,8 +312,8 @@ public void CloseFile(ScriptFile scriptFile) /// in the array is the "root file" of the search public ScriptFile[] ExpandScriptReferences(ScriptFile scriptFile) { - Dictionary referencedScriptFiles = new Dictionary(); - List expandedReferences = new List(); + Dictionary referencedScriptFiles = new(); + List expandedReferences = new(); // add original file so it's not searched for, then find all file references referencedScriptFiles.Add(scriptFile.Id, scriptFile); @@ -344,10 +341,10 @@ public string GetRelativePath(string filePath) { string resolvedPath = filePath; - if (!IsPathInMemory(filePath) && !string.IsNullOrEmpty(this.WorkspacePath)) + if (!IsPathInMemory(filePath) && !string.IsNullOrEmpty(WorkspacePath)) { - Uri workspaceUri = new Uri(this.WorkspacePath); - Uri fileUri = new Uri(filePath); + Uri workspaceUri = new(WorkspacePath); + Uri fileUri = new(filePath); resolvedPath = workspaceUri.MakeRelativeUri(fileUri).ToString(); @@ -391,23 +388,23 @@ bool ignoreReparsePoints yield break; } - var matcher = new Matcher(); + Matcher matcher = new(); foreach (string pattern in includeGlobs) { matcher.AddInclude(pattern); } foreach (string pattern in excludeGlobs) { matcher.AddExclude(pattern); } - var fsFactory = new WorkspaceFileSystemWrapperFactory( + WorkspaceFileSystemWrapperFactory fsFactory = new( WorkspacePath, maxDepth, VersionUtils.IsNetCore ? s_psFileExtensionsCoreFramework : s_psFileExtensionsFullFramework, ignoreReparsePoints, logger ); - var fileMatchResult = matcher.Execute(fsFactory.RootDirectory); + PatternMatchingResult fileMatchResult = matcher.Execute(fsFactory.RootDirectory); foreach (FilePatternMatch item in fileMatchResult.Files) { // item.Path always contains forward slashes in paths when it should be backslashes on Windows. // Since we're returning strings here, it's important to use the correct directory separator. - var path = VersionUtils.IsWindows ? item.Path.Replace('/', Path.DirectorySeparatorChar) : item.Path; + string path = VersionUtils.IsWindows ? item.Path.Replace('/', Path.DirectorySeparatorChar) : item.Path; yield return Path.Combine(WorkspacePath, path); } } @@ -433,7 +430,7 @@ private void RecursivelyFindReferences( foreach (string referencedFileName in scriptFile.ReferencedFiles) { string resolvedScriptPath = - this.ResolveRelativeScriptPath( + ResolveRelativeScriptPath( baseFilePath, referencedFileName); @@ -443,7 +440,7 @@ private void RecursivelyFindReferences( continue; } - this.logger.LogDebug( + logger.LogDebug( string.Format( "Resolved relative path '{0}' to '{1}'", referencedFileName, @@ -476,7 +473,7 @@ internal static bool IsPathInMemory(string filePath) { // File system absolute paths will have a URI scheme of file:. // Other schemes like "untitled:" and "gitlens-git:" will return false for IsFile. - var uri = new Uri(filePath); + Uri uri = new(filePath); isInMemory = !uri.IsFile; } catch (UriFormatException) @@ -487,7 +484,7 @@ internal static bool IsPathInMemory(string filePath) { Path.GetFullPath(filePath); } - catch (Exception ex) when (ex is ArgumentException || ex is NotSupportedException) + catch (Exception ex) when (ex is ArgumentException or NotSupportedException) { isInMemory = true; } @@ -500,10 +497,7 @@ internal static bool IsPathInMemory(string filePath) return isInMemory; } - internal string ResolveWorkspacePath(string path) - { - return ResolveRelativeScriptPath(WorkspacePath, path); - } + internal string ResolveWorkspacePath(string path) => ResolveRelativeScriptPath(WorkspacePath, path); internal string ResolveRelativeScriptPath(string baseFilePath, string relativePath) { @@ -543,11 +537,11 @@ internal string ResolveRelativeScriptPath(string baseFilePath, string relativePa if (resolveException != null) { - this.logger.LogError( + logger.LogError( $"Could not resolve relative script path\r\n" + $" baseFilePath = {baseFilePath}\r\n " + $" relativePath = {relativePath}\r\n\r\n" + - $"{resolveException.ToString()}"); + $"{resolveException}"); } return combinedPath; diff --git a/src/PowerShellEditorServices/Utility/AsyncUtils.cs b/src/PowerShellEditorServices/Utility/AsyncUtils.cs index 2fdff670d..c3f146bb7 100644 --- a/src/PowerShellEditorServices/Utility/AsyncUtils.cs +++ b/src/PowerShellEditorServices/Utility/AsyncUtils.cs @@ -19,10 +19,7 @@ internal static class AsyncUtils /// max count of one. /// /// A simple single handle . - internal static SemaphoreSlim CreateSimpleLockingSemaphore() - { - return new SemaphoreSlim(initialCount: 1, maxCount: 1); - } + internal static SemaphoreSlim CreateSimpleLockingSemaphore() => new(initialCount: 1, maxCount: 1); internal static Task HandleErrorsAsync( this Task task, diff --git a/src/PowerShellEditorServices/Utility/Extensions.cs b/src/PowerShellEditorServices/Utility/Extensions.cs index b26443100..9c6c6b2cf 100644 --- a/src/PowerShellEditorServices/Utility/Extensions.cs +++ b/src/PowerShellEditorServices/Utility/Extensions.cs @@ -39,7 +39,7 @@ public static string SafeToString(this object obj) /// An enumerable object of type T /// A comparer for ordering elements of type T. The comparer should handle null values. /// An object of type T. If the enumerable is empty or has all null elements, then the method returns null. - public static T MaxElement(this IEnumerable elements, Func comparer) where T:class + public static T MaxElement(this IEnumerable elements, Func comparer) where T : class { if (elements == null) { @@ -56,8 +56,8 @@ public static T MaxElement(this IEnumerable elements, Func compar return null; } - var maxElement = elements.First(); - foreach(var element in elements.Skip(1)) + T maxElement = elements.First(); + foreach (T element in elements.Skip(1)) { if (element != null && comparer(element, maxElement) > 0) { @@ -75,10 +75,7 @@ public static T MaxElement(this IEnumerable elements, Func compar /// An enumerable object of type T /// A comparer for ordering elements of type T. The comparer should handle null values. /// An object of type T. If the enumerable is empty or has all null elements, then the method returns null. - public static T MinElement(this IEnumerable elements, Func comparer) where T : class - { - return MaxElement(elements, (elementX, elementY) => -1 * comparer(elementX, elementY)); - } + public static T MinElement(this IEnumerable elements, Func comparer) where T : class => MaxElement(elements, (elementX, elementY) => -1 * comparer(elementX, elementY)); /// /// Compare extents with respect to their widths. @@ -106,8 +103,8 @@ public static int ExtentWidthComparer(this IScriptExtent extentX, IScriptExtent return -1; } - var extentWidthX = extentX.EndOffset - extentX.StartOffset; - var extentWidthY = extentY.EndOffset - extentY.StartOffset; + int extentWidthX = extentX.EndOffset - extentX.StartOffset; + int extentWidthY = extentY.EndOffset - extentY.StartOffset; if (extentWidthX > extentWidthY) { return 1; diff --git a/src/PowerShellEditorServices/Utility/IdempotentLatch.cs b/src/PowerShellEditorServices/Utility/IdempotentLatch.cs index 31c1a95d0..433b62a3d 100644 --- a/src/PowerShellEditorServices/Utility/IdempotentLatch.cs +++ b/src/PowerShellEditorServices/Utility/IdempotentLatch.cs @@ -9,10 +9,7 @@ internal class IdempotentLatch { private int _signaled; - public IdempotentLatch() - { - _signaled = 0; - } + public IdempotentLatch() => _signaled = 0; public bool IsSignaled => _signaled != 0; diff --git a/src/PowerShellEditorServices/Utility/IsExternalInit.cs b/src/PowerShellEditorServices/Utility/IsExternalInit.cs index 7d336fdc2..1f0f8f07c 100644 --- a/src/PowerShellEditorServices/Utility/IsExternalInit.cs +++ b/src/PowerShellEditorServices/Utility/IsExternalInit.cs @@ -11,5 +11,5 @@ namespace System.Runtime.CompilerServices /// So instead we define the type in our own code. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal class IsExternalInit{} + internal class IsExternalInit { } } diff --git a/src/PowerShellEditorServices/Utility/LspDebugUtils.cs b/src/PowerShellEditorServices/Utility/LspDebugUtils.cs index 254bc41a6..115689586 100644 --- a/src/PowerShellEditorServices/Utility/LspDebugUtils.cs +++ b/src/PowerShellEditorServices/Utility/LspDebugUtils.cs @@ -60,7 +60,7 @@ public static StackFrame CreateStackFrame( StackFrameDetails stackFrame, long id) { - var sourcePresentationHint = + SourcePresentationHint sourcePresentationHint = stackFrame.IsExternalCode ? SourcePresentationHint.Deemphasize : SourcePresentationHint.Normal; // When debugging an interactive session, the ScriptPath is which is not a valid source file. @@ -95,8 +95,8 @@ public static Scope CreateScope(VariableScope scope) Name = scope.Name, VariablesReference = scope.Id, // Temporary fix for #95 to get debug hover tips to work well at least for the local scope. - Expensive = ((scope.Name != VariableContainerDetails.LocalScopeName) && - (scope.Name != VariableContainerDetails.AutoVariablesName)) + Expensive = scope.Name is not VariableContainerDetails.LocalScopeName and + not VariableContainerDetails.AutoVariablesName }; } diff --git a/src/PowerShellEditorServices/Utility/LspUtils.cs b/src/PowerShellEditorServices/Utility/LspUtils.cs index 1412f8c53..68c5ffb0b 100644 --- a/src/PowerShellEditorServices/Utility/LspUtils.cs +++ b/src/PowerShellEditorServices/Utility/LspUtils.cs @@ -7,7 +7,7 @@ namespace Microsoft.PowerShell.EditorServices.Utility { internal static class LspUtils { - public static DocumentSelector PowerShellDocumentSelector => new DocumentSelector( + public static DocumentSelector PowerShellDocumentSelector => new( DocumentFilter.ForLanguage("powershell"), DocumentFilter.ForLanguage("pwsh"), diff --git a/src/PowerShellEditorServices/Utility/PSCommandExtensions.cs b/src/PowerShellEditorServices/Utility/PSCommandExtensions.cs index 0cd08927e..5b9763829 100644 --- a/src/PowerShellEditorServices/Utility/PSCommandExtensions.cs +++ b/src/PowerShellEditorServices/Utility/PSCommandExtensions.cs @@ -18,7 +18,7 @@ internal static class PSCommandHelpers static PSCommandHelpers() { - var ctor = typeof(Command).GetConstructor( + ConstructorInfo ctor = typeof(Command).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, binder: null, new[] { typeof(CommandInfo) }, @@ -42,7 +42,7 @@ static PSCommandHelpers() /// public static PSCommand AddCommand(this PSCommand command, CommandInfo commandInfo) { - var rsCommand = s_commandCtor(commandInfo); + Command rsCommand = s_commandCtor(commandInfo); return command.AddCommand(rsCommand); } @@ -93,7 +93,7 @@ public static PSCommand AddProfileLoadIfExists(this PSCommand psCommand, PSObjec public static string GetInvocationText(this PSCommand command) { Command currentCommand = command.Commands[0]; - var sb = new StringBuilder().AddCommandText(command.Commands[0]); + StringBuilder sb = new StringBuilder().AddCommandText(command.Commands[0]); for (int i = 1; i < command.Commands.Count; i++) { diff --git a/src/PowerShellEditorServices/Utility/PathUtils.cs b/src/PowerShellEditorServices/Utility/PathUtils.cs index 4342034b9..b97cc6cde 100644 --- a/src/PowerShellEditorServices/Utility/PathUtils.cs +++ b/src/PowerShellEditorServices/Utility/PathUtils.cs @@ -33,10 +33,7 @@ internal class PathUtils /// /// The path to normalize. /// The normalized path. - public static string NormalizePathSeparators(string path) - { - return string.IsNullOrWhiteSpace(path) ? path : path.Replace(AlternatePathSeparator, DefaultPathSeparator); - } + public static string NormalizePathSeparators(string path) => string.IsNullOrWhiteSpace(path) ? path : path.Replace(AlternatePathSeparator, DefaultPathSeparator); /// /// Return the given path with all PowerShell globbing characters escaped, @@ -47,7 +44,7 @@ public static string NormalizePathSeparators(string path) /// The path with *, ?, [, and ] escaped, including spaces if required internal static string WildcardEscapePath(string path, bool escapeSpaces = false) { - var wildcardEscapedPath = WildcardPattern.Escape(path); + string wildcardEscapedPath = WildcardPattern.Escape(path); if (escapeSpaces) { diff --git a/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs b/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs index 95efa48a9..ca6825928 100644 --- a/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs +++ b/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs @@ -22,10 +22,10 @@ namespace PowerShellEditorServices.Test.E2E public class DebugAdapterProtocolMessageTests : IAsyncLifetime { private const string TestOutputFileName = "__dapTestOutputFile.txt"; - private readonly static bool s_isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); - private readonly static string s_binDir = + private static readonly bool s_isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + private static readonly string s_binDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - private readonly static string s_testOutputPath = Path.Combine(s_binDir, TestOutputFileName); + private static readonly string s_testOutputPath = Path.Combine(s_binDir, TestOutputFileName); private readonly ITestOutputHelper _output; private DebugAdapterClient PsesDebugAdapterClient; @@ -33,18 +33,15 @@ public class DebugAdapterProtocolMessageTests : IAsyncLifetime public TaskCompletionSource Started { get; } = new TaskCompletionSource(); - public DebugAdapterProtocolMessageTests(ITestOutputHelper output) - { - _output = output; - } + public DebugAdapterProtocolMessageTests(ITestOutputHelper output) => _output = output; public async Task InitializeAsync() { - var factory = new LoggerFactory(); + LoggerFactory factory = new(); _psesProcess = new PsesStdioProcess(factory, true); await _psesProcess.Start().ConfigureAwait(false); - var initialized = new TaskCompletionSource(); + TaskCompletionSource initialized = new(); _psesProcess.ProcessExited += (sender, args) => { @@ -59,18 +56,21 @@ 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((client, token) => + { 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((client, request, response, token) => + { initialized.SetResult(true); return Task.CompletedTask; }); - options.OnUnhandledException = (exception) => { + options.OnUnhandledException = (exception) => + { initialized.SetException(exception); Started.SetException(exception); }; @@ -99,10 +99,10 @@ public async Task DisposeAsync() try { await PsesDebugAdapterClient.RequestDisconnect(new DisconnectArguments - { - Restart = false, - TerminateDebuggee = true - }).ConfigureAwait(false); + { + Restart = false, + TerminateDebuggee = true + }).ConfigureAwait(false); await _psesProcess.Stop().ConfigureAwait(false); PsesDebugAdapterClient?.Dispose(); } @@ -141,10 +141,7 @@ private string GenerateScriptFromLoggingStatements(params string[] logStatements return builder.ToString(); } - private static string[] GetLog() - { - return File.ReadLines(s_testOutputPath).ToArray(); - } + private static string[] GetLog() => File.ReadLines(s_testOutputPath).ToArray(); [Trait("Category", "DAP")] [Fact] @@ -211,7 +208,7 @@ public async Task CanSetBreakpointsAsync() SourceModified = false, }).ConfigureAwait(false); - var breakpoint = setBreakpointsResponse.Breakpoints.First(); + Breakpoint breakpoint = setBreakpointsResponse.Breakpoints.First(); Assert.True(breakpoint.Verified); Assert.Equal(filePath, breakpoint.Source.Path, ignoreCase: s_isWindows); Assert.Equal(2, breakpoint.Line); @@ -260,7 +257,7 @@ public async Task CanStepPastSystemWindowsForms() Skip.IfNot(PsesStdioProcess.IsWindowsPowerShell); Skip.If(PsesStdioProcess.RunningInConstainedLanguageMode); - string filePath = NewTestFile(string.Join(Environment.NewLine, new [] + string filePath = NewTestFile(string.Join(Environment.NewLine, new[] { "Add-Type -AssemblyName System.Windows.Forms", "$global:form = New-Object System.Windows.Forms.Form", @@ -269,14 +266,14 @@ public async Task CanStepPastSystemWindowsForms() await PsesDebugAdapterClient.LaunchScript(filePath, Started).ConfigureAwait(false); - var setBreakpointsResponse = await PsesDebugAdapterClient.SetFunctionBreakpoints( + SetFunctionBreakpointsResponse setBreakpointsResponse = await PsesDebugAdapterClient.SetFunctionBreakpoints( new SetFunctionBreakpointsArguments { Breakpoints = new FunctionBreakpoint[] { new FunctionBreakpoint { Name = "Write-Host", } } }).ConfigureAwait(false); - var breakpoint = setBreakpointsResponse.Breakpoints.First(); + Breakpoint breakpoint = setBreakpointsResponse.Breakpoints.First(); Assert.True(breakpoint.Verified); ConfigurationDoneResponse configDoneResponse = await PsesDebugAdapterClient.RequestConfigurationDone(new ConfigurationDoneArguments()).ConfigureAwait(false); @@ -285,13 +282,13 @@ public async Task CanStepPastSystemWindowsForms() // At this point the script should be running so lets give it time await Task.Delay(2000).ConfigureAwait(false); - var variablesResponse = await PsesDebugAdapterClient.RequestVariables( + VariablesResponse variablesResponse = await PsesDebugAdapterClient.RequestVariables( new VariablesArguments { VariablesReference = 1 }).ConfigureAwait(false); - var form = variablesResponse.Variables.FirstOrDefault(v => v.Name == "$form"); + Variable form = variablesResponse.Variables.FirstOrDefault(v => v.Name == "$form"); Assert.NotNull(form); Assert.Equal("System.Windows.Forms.Form, Text: ", form.Value); } diff --git a/test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs b/test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs index b01fff593..f386fd983 100644 --- a/test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs +++ b/test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs @@ -28,7 +28,7 @@ namespace PowerShellEditorServices.Test.E2E { public class LSPTestsFixture : IAsyncLifetime { - protected readonly static string s_binDir = + protected static readonly string s_binDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); private const bool IsDebugAdapterTests = false; @@ -43,7 +43,7 @@ public class LSPTestsFixture : IAsyncLifetime public async Task InitializeAsync() { - var factory = new LoggerFactory(); + LoggerFactory factory = new(); _psesProcess = new PsesStdioProcess(factory, IsDebugAdapterTests); await _psesProcess.Start().ConfigureAwait(false); @@ -59,7 +59,7 @@ public async Task InitializeAsync() .WithOutput(_psesProcess.InputStream) .WithRootUri(DocumentUri.FromFileSystemPath(testdir.FullName)) .OnPublishDiagnostics(diagnosticParams => Diagnostics.AddRange(diagnosticParams.Diagnostics.Where(d => d != null))) - .OnLogMessage(logMessageParams => Output?.WriteLine($"{logMessageParams.Type.ToString()}: {logMessageParams.Message}")) + .OnLogMessage(logMessageParams => Output?.WriteLine($"{logMessageParams.Type}: {logMessageParams.Message}")) .OnTelemetryEvent(telemetryEventParams => TelemetryEvents.Add( new PsesTelemetryEvent { @@ -69,7 +69,7 @@ public async Task InitializeAsync() // Enable all capabilities this this is for testing. // This will be a built in feature of the Omnisharp client at some point. - var capabilityTypes = typeof(ICapability).Assembly.GetExportedTypes() + IEnumerable capabilityTypes = typeof(ICapability).Assembly.GetExportedTypes() .Where(z => typeof(ICapability).IsAssignableFrom(z) && z.IsClass && !z.IsAbstract); foreach (Type capabilityType in capabilityTypes) { diff --git a/test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs b/test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs index a59e19446..5214d8cf5 100644 --- a/test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs +++ b/test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs @@ -35,7 +35,7 @@ public class LanguageServerProtocolMessageTests : IClassFixture // Borrowed from `VersionUtils` which can't be used here due to an initialization problem. private static bool IsLinux { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - private readonly static string s_binDir = + private static readonly string s_binDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); private readonly ILanguageClient PsesLanguageClient; @@ -101,7 +101,7 @@ private async Task WaitForDiagnosticsAsync() private async Task WaitForTelemetryEventsAsync() { // Wait for PSSA to finish. - for ( int i = 0; TelemetryEvents.Count == 0; i++) + for (int i = 0; TelemetryEvents.Count == 0; i++) { if (i >= 10) { @@ -189,7 +189,7 @@ public async Task CanReceiveDiagnosticsFromFileChangedAsync() PsesLanguageClient.SendNotification("textDocument/didChange", new DidChangeTextDocumentParams { // Include several content changes to test against duplicate Diagnostics showing up. - ContentChanges = new Container(new [] + ContentChanges = new Container(new[] { new TextDocumentContentChangeEvent { @@ -258,7 +258,7 @@ public async Task CanReceiveDiagnosticsFromConfigurationChangeAsync() }); await WaitForTelemetryEventsAsync().ConfigureAwait(true); - var telemetryEvent = Assert.Single(TelemetryEvents); + PsesTelemetryEvent telemetryEvent = Assert.Single(TelemetryEvents); Assert.Equal("NonDefaultPsesFeatureConfiguration", telemetryEvent.EventName); Assert.False((bool)telemetryEvent.Data.GetValue("ScriptAnalysis")); @@ -386,16 +386,16 @@ public async Task CanSendRangeFormattingRequestAsync() { Range = new Range { - Start = new Position - { - Line = 2, - Character = 0 - }, - End = new Position - { - Line = 3, - Character = 0 - } + Start = new Position + { + Line = 2, + Character = 0 + }, + End = new Position + { + Line = 3, + Character = 0 + } }, TextDocument = new TextDocumentIdentifier { @@ -440,7 +440,8 @@ await PsesLanguageClient .Returning(CancellationToken.None).ConfigureAwait(true); Assert.Collection(symbolInformationOrDocumentSymbols, - symInfoOrDocSym => { + symInfoOrDocSym => + { Range range = symInfoOrDocSym.SymbolInformation.Location.Range; Assert.Equal(1, range.Start.Line); @@ -550,7 +551,7 @@ await PsesLanguageClient [Fact] public async Task CanSendPowerShellGetPSHostProcessesRequestAsync() { - var process = new Process(); + Process process = new(); process.StartInfo.FileName = PwshExe; process.StartInfo.ArgumentList.Add("-NoProfile"); process.StartInfo.ArgumentList.Add("-NoLogo"); @@ -591,7 +592,7 @@ await PsesLanguageClient [Fact] public async Task CanSendPowerShellGetRunspaceRequestAsync() { - var process = new Process(); + Process process = new(); process.StartInfo.FileName = PwshExe; process.StartInfo.ArgumentList.Add("-NoProfile"); process.StartInfo.ArgumentList.Add("-NoLogo"); @@ -1150,7 +1151,7 @@ await PsesLanguageClient [Fact] public async Task CanSendEvaluateRequestAsync() { - using var cancellationSource = new CancellationTokenSource(millisecondsDelay: 5000); + using CancellationTokenSource cancellationSource = new(millisecondsDelay: 5000); EvaluateResponseBody evaluateResponseBody = await PsesLanguageClient @@ -1221,7 +1222,7 @@ await PsesLanguageClient // More information about how this data is generated can be found at // https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L71 - var expectedArr = new int[5] + int[] expectedArr = new int[5] { // line, index, token length, token type, token modifiers 0, 0, scriptContent.Length, 1, 0 //function token: line 0, index 0, length of script, type 1 = keyword, no modifiers diff --git a/test/PowerShellEditorServices.Test.E2E/Processes/LoggingStream.cs b/test/PowerShellEditorServices.Test.E2E/Processes/LoggingStream.cs index dc5b2e2a5..1a0151ec1 100644 --- a/test/PowerShellEditorServices.Test.E2E/Processes/LoggingStream.cs +++ b/test/PowerShellEditorServices.Test.E2E/Processes/LoggingStream.cs @@ -14,10 +14,7 @@ internal class LoggingStream : Stream private readonly Stream _underlyingStream; - public LoggingStream(Stream underlyingStream) - { - _underlyingStream = underlyingStream; - } + public LoggingStream(Stream underlyingStream) => _underlyingStream = underlyingStream; public override bool CanRead => _underlyingStream.CanRead; diff --git a/test/PowerShellEditorServices.Test.E2E/Processes/PsesStdioProcess.cs b/test/PowerShellEditorServices.Test.E2E/Processes/PsesStdioProcess.cs index fd243a6bb..305ce7560 100644 --- a/test/PowerShellEditorServices.Test.E2E/Processes/PsesStdioProcess.cs +++ b/test/PowerShellEditorServices.Test.E2E/Processes/PsesStdioProcess.cs @@ -15,30 +15,29 @@ namespace PowerShellEditorServices.Test.E2E /// public class PsesStdioProcess : StdioServerProcess { - protected readonly static string s_binDir = + protected static readonly string s_binDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); #region private static or constants members - private readonly static string s_bundledModulePath = new FileInfo(Path.Combine( + private static readonly string s_bundledModulePath = new FileInfo(Path.Combine( s_binDir, "..", "..", "..", "..", "..", "module")).FullName; - private readonly static string s_sessionDetailsPath = Path.Combine( + private static readonly string s_sessionDetailsPath = Path.Combine( s_binDir, $"pses_test_sessiondetails_{Path.GetRandomFileName()}"); - private readonly static string s_logPath = Path.Combine( + private static readonly string s_logPath = Path.Combine( Environment.GetEnvironmentVariable("BUILD_ARTIFACTSTAGINGDIRECTORY") ?? s_binDir, $"pses_test_logs_{Path.GetRandomFileName()}"); - - const string s_logLevel = "Diagnostic"; - readonly static string[] s_featureFlags = { "PSReadLine" }; - const string s_hostName = "TestHost"; - const string s_hostProfileId = "TestHost"; - const string s_hostVersion = "1.0.0"; - private readonly static string[] s_additionalModules = { "PowerShellEditorServices.VSCode" }; + private const string s_logLevel = "Diagnostic"; + private static readonly string[] s_featureFlags = { "PSReadLine" }; + private const string s_hostName = "TestHost"; + private const string s_hostProfileId = "TestHost"; + private const string s_hostVersion = "1.0.0"; + private static readonly string[] s_additionalModules = { "PowerShellEditorServices.VSCode" }; #endregion @@ -63,7 +62,7 @@ public PsesStdioProcess(ILoggerFactory loggerFactory, bool isDebugAdapter) : bas private static ProcessStartInfo GeneratePsesStartInfo(bool isDebugAdapter) { - ProcessStartInfo processStartInfo = new ProcessStartInfo + ProcessStartInfo processStartInfo = new() { FileName = PwshExe }; @@ -78,19 +77,28 @@ private static ProcessStartInfo GeneratePsesStartInfo(bool isDebugAdapter) private static string[] GeneratePsesArguments(bool isDebugAdapter) { - List args = new List + List args = new() { "&", SingleQuoteEscape(Path.Combine(s_bundledModulePath, "PowerShellEditorServices", "Start-EditorServices.ps1")), - "-LogPath", SingleQuoteEscape(s_logPath), - "-LogLevel", s_logLevel, - "-SessionDetailsPath", SingleQuoteEscape(s_sessionDetailsPath), - "-FeatureFlags", string.Join(',', s_featureFlags), - "-HostName", s_hostName, - "-HostProfileId", s_hostProfileId, - "-HostVersion", s_hostVersion, - "-AdditionalModules", string.Join(',', s_additionalModules), - "-BundledModulesPath", SingleQuoteEscape(s_bundledModulePath), + "-LogPath", + SingleQuoteEscape(s_logPath), + "-LogLevel", + s_logLevel, + "-SessionDetailsPath", + SingleQuoteEscape(s_sessionDetailsPath), + "-FeatureFlags", + string.Join(',', s_featureFlags), + "-HostName", + s_hostName, + "-HostProfileId", + s_hostProfileId, + "-HostVersion", + s_hostVersion, + "-AdditionalModules", + string.Join(',', s_additionalModules), + "-BundledModulesPath", + SingleQuoteEscape(s_bundledModulePath), "-Stdio" }; @@ -111,10 +119,7 @@ private static string[] GeneratePsesArguments(bool isDebugAdapter) }; } - private static string SingleQuoteEscape(string str) - { - return $"'{str.Replace("'", "''")}'"; - } + private static string SingleQuoteEscape(string str) => $"'{str.Replace("'", "''")}'"; #endregion } diff --git a/test/PowerShellEditorServices.Test.E2E/Processes/ServerProcess.cs b/test/PowerShellEditorServices.Test.E2E/Processes/ServerProcess.cs index ca7360cb8..020ee8779 100644 --- a/test/PowerShellEditorServices.Test.E2E/Processes/ServerProcess.cs +++ b/test/PowerShellEditorServices.Test.E2E/Processes/ServerProcess.cs @@ -28,12 +28,7 @@ public abstract class ServerProcess : IDisposable /// protected ServerProcess(ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - LoggerFactory = loggerFactory; + LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); Log = LoggerFactory.CreateLogger(categoryName: GetType().FullName); ServerStartCompletion = new TaskCompletionSource(); @@ -58,10 +53,7 @@ protected ServerProcess(ILoggerFactory loggerFactory) /// /// Dispose of resources being used by the launcher. /// - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); /// /// Dispose of resources being used by the launcher. diff --git a/test/PowerShellEditorServices.Test.E2E/Processes/StdioServerProcess.cs b/test/PowerShellEditorServices.Test.E2E/Processes/StdioServerProcess.cs index 8ced05c6d..736a1fccc 100644 --- a/test/PowerShellEditorServices.Test.E2E/Processes/StdioServerProcess.cs +++ b/test/PowerShellEditorServices.Test.E2E/Processes/StdioServerProcess.cs @@ -18,12 +18,12 @@ public class StdioServerProcess : ServerProcess /// /// A that describes how to start the server. /// - readonly ProcessStartInfo _serverStartInfo; + private readonly ProcessStartInfo _serverStartInfo; /// /// The current server process (if any). /// - Process _serverProcess; + private Process _serverProcess; /// /// Create a new . @@ -35,27 +35,14 @@ public class StdioServerProcess : ServerProcess /// A that describes how to start the server. /// public StdioServerProcess(ILoggerFactory loggerFactory, ProcessStartInfo serverStartInfo) - : base(loggerFactory) - { - if (serverStartInfo == null) - { - throw new ArgumentNullException(nameof(serverStartInfo)); - } - - _serverStartInfo = serverStartInfo; - } + : base(loggerFactory) => _serverStartInfo = serverStartInfo ?? throw new ArgumentNullException(nameof(serverStartInfo)); public int ProcessId => _serverProcess.Id; /// /// The process ID of the server process, useful for attaching a debugger. /// - public int Id - { - get { - return _serverProcess.Id; - } - } + public int Id => _serverProcess.Id; /// /// Dispose of resources being used by the launcher. @@ -150,11 +137,11 @@ public override Task Stop() /// /// The event arguments. /// - void ServerProcess_Exit(object sender, EventArgs args) + private void ServerProcess_Exit(object sender, EventArgs args) { Log.LogDebug("Server process has exited."); - var serverProcess = (Process)sender; + Process serverProcess = (Process)sender; int exitCode = serverProcess.ExitCode; string errorMsg = serverProcess.StandardError.ReadToEnd(); diff --git a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInMultiSymbolFile.cs b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInMultiSymbolFile.cs index 14b1cd449..95efed4a9 100644 --- a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInMultiSymbolFile.cs +++ b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInMultiSymbolFile.cs @@ -8,7 +8,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared.Symbols public class FindSymbolsInMultiSymbolFile { public static readonly ScriptRegion SourceDetails = - new ScriptRegion( + new( file: TestUtilities.NormalizePath("Symbols/MultipleSymbols.ps1"), text: string.Empty, startLineNumber: 0, diff --git a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInNoSymbolsFile.cs b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInNoSymbolsFile.cs index 162ef3d16..7847cfbfe 100644 --- a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInNoSymbolsFile.cs +++ b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInNoSymbolsFile.cs @@ -8,7 +8,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared.Symbols public class FindSymbolsInNoSymbolsFile { public static readonly ScriptRegion SourceDetails = - new ScriptRegion( + new( file: TestUtilities.NormalizePath("Symbols/NoSymbols.ps1"), text: string.Empty, startLineNumber: 0, diff --git a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPSDFile.cs b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPSDFile.cs index b0478a761..40aa0878b 100644 --- a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPSDFile.cs +++ b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPSDFile.cs @@ -8,7 +8,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared.Symbols public class FindSymbolsInPSDFile { public static readonly ScriptRegion SourceDetails = - new ScriptRegion( + new( file: TestUtilities.NormalizePath("Symbols/PowerShellDataFile.psd1"), text: string.Empty, startLineNumber: 0, diff --git a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPesterFile.cs b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPesterFile.cs index d5ee466ee..c69825afd 100644 --- a/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPesterFile.cs +++ b/test/PowerShellEditorServices.Test.Shared/Symbols/FindSymbolsInPesterFile.cs @@ -8,7 +8,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared.Symbols public class FindSymbolsInPesterFile { public static readonly ScriptRegion SourceDetails = - new ScriptRegion( + new( file: TestUtilities.NormalizePath("Symbols/PesterFile.tests.ps1"), text: string.Empty, startLineNumber: 0, diff --git a/test/PowerShellEditorServices.Test.Shared/TestUtilities/TestUtilities.cs b/test/PowerShellEditorServices.Test.Shared/TestUtilities/TestUtilities.cs index 1441b56a6..94513f666 100644 --- a/test/PowerShellEditorServices.Test.Shared/TestUtilities/TestUtilities.cs +++ b/test/PowerShellEditorServices.Test.Shared/TestUtilities/TestUtilities.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Shared /// public static class TestUtilities { - private static readonly char[] s_unixNewlines = new [] { '\n' }; + private static readonly char[] s_unixNewlines = new[] { '\n' }; /// /// Takes a UNIX-style path and converts it to the path appropriate to the platform. @@ -65,7 +65,7 @@ public static string NormalizeNewlines(string unixString) if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - return String.Join(Environment.NewLine, unixString.Split(s_unixNewlines)); + return string.Join(Environment.NewLine, unixString.Split(s_unixNewlines)); } return unixString; @@ -76,10 +76,7 @@ public static string NormalizeNewlines(string unixString) /// /// The string to normalize for the platform, given with UNIX-specific separators. /// The same string but separated by platform-appropriate directory and newline separators. - public static string PlatformNormalize(string unixString) - { - return NormalizeNewlines(NormalizePath(unixString)); - } + public static string PlatformNormalize(string unixString) => NormalizeNewlines(NormalizePath(unixString)); /// /// Not for use in production -- convenience code for debugging tests. diff --git a/test/PowerShellEditorServices.Test/Debugging/DebugServiceTests.cs b/test/PowerShellEditorServices.Test/Debugging/DebugServiceTests.cs index 538ff489f..cf11f3cdc 100644 --- a/test/PowerShellEditorServices.Test/Debugging/DebugServiceTests.cs +++ b/test/PowerShellEditorServices.Test/Debugging/DebugServiceTests.cs @@ -75,15 +75,9 @@ public void Dispose() /// /// /// - private void OnDebuggerStopped(object sender, DebuggerStoppedEventArgs e) - { - debuggerStoppedQueue.Add(e); - } + private void OnDebuggerStopped(object sender, DebuggerStoppedEventArgs e) => debuggerStoppedQueue.Add(e); - private ScriptFile GetDebugScript(string fileName) - { - return workspace.GetFile(TestUtilities.GetSharedPath(Path.Combine("Debugging", fileName))); - } + private ScriptFile GetDebugScript(string fileName) => workspace.GetFile(TestUtilities.GetSharedPath(Path.Combine("Debugging", fileName))); private VariableDetailsBase[] GetVariables(string scopeName) { @@ -106,7 +100,7 @@ private Task ExecutePowerShellCommand(string command, params string[] args) private void AssertDebuggerPaused() { - var eventArgs = debuggerStoppedQueue.Take(new CancellationTokenSource(5000).Token); + DebuggerStoppedEventArgs eventArgs = debuggerStoppedQueue.Take(new CancellationTokenSource(5000).Token); Assert.Empty(eventArgs.OriginalEvent.Breakpoints); } @@ -115,7 +109,7 @@ private void AssertDebuggerStopped( int lineNumber = -1, CommandBreakpointDetails commandBreakpointDetails = default) { - var eventArgs = debuggerStoppedQueue.Take(new CancellationTokenSource(5000).Token); + DebuggerStoppedEventArgs eventArgs = debuggerStoppedQueue.Take(new CancellationTokenSource(5000).Token); Assert.True(psesHost.DebugContext.IsStopped); @@ -170,7 +164,7 @@ await debugService.SetCommandBreakpointsAsync( // NOTE: This assertion will fail if any error occurs. Notably this happens in testing // when the assembly path changes and the commands definition file can't be found. VariableDetailsBase[] variables = GetVariables(VariableContainerDetails.GlobalScopeName); - var var = Array.Find(variables, v => v.Name == "$Error"); + VariableDetailsBase var = Array.Find(variables, v => v.Name == "$Error"); Assert.NotNull(var); Assert.True(var.IsExpandable); Assert.Equal("[ArrayList: 0]", var.ValueString); @@ -211,7 +205,7 @@ public async Task DebuggerAcceptsScriptArgs(string[] args) VariableDetailsBase[] variables = GetVariables(VariableContainerDetails.LocalScopeName); - var var = Array.Find(variables, v => v.Name == "$Param1"); + VariableDetailsBase var = Array.Find(variables, v => v.Name == "$Param1"); Assert.NotNull(var); Assert.Equal("\"Foo\"", var.ValueString); Assert.False(var.IsExpandable); @@ -220,7 +214,7 @@ public async Task DebuggerAcceptsScriptArgs(string[] args) Assert.NotNull(var); Assert.True(var.IsExpandable); - var childVars = debugService.GetVariables(var.Id); + VariableDetailsBase[] childVars = debugService.GetVariables(var.Id); // 2 variables plus "Raw View" Assert.Equal(3, childVars.Length); Assert.Equal("\"Bar\"", childVars[0].ValueString); @@ -280,7 +274,7 @@ public async Task DebuggerStopsOnFunctionBreakpoints() VariableDetailsBase[] variables = GetVariables(VariableContainerDetails.LocalScopeName); // Verify the function breakpoint broke at Write-Host and $i is 1 - var i = Array.Find(variables, v => v.Name == "$i"); + VariableDetailsBase i = Array.Find(variables, v => v.Name == "$i"); Assert.NotNull(i); Assert.False(i.IsExpandable); Assert.Equal("1", i.ValueString); @@ -309,7 +303,7 @@ await debugService.SetLineBreakpointsAsync( BreakpointDetails.Create(debugScriptFile.FilePath, 10) }).ConfigureAwait(true); - var confirmedBreakpoints = await GetConfirmedBreakpoints(debugScriptFile).ConfigureAwait(true); + IReadOnlyList confirmedBreakpoints = await GetConfirmedBreakpoints(debugScriptFile).ConfigureAwait(true); Assert.Equal(2, confirmedBreakpoints.Count); Assert.Equal(5, breakpoints[0].LineNumber); @@ -327,7 +321,7 @@ await debugService.SetLineBreakpointsAsync( debugScriptFile, Array.Empty()).ConfigureAwait(true); - var remainingBreakpoints = await GetConfirmedBreakpoints(debugScriptFile).ConfigureAwait(true); + IReadOnlyList remainingBreakpoints = await GetConfirmedBreakpoints(debugScriptFile).ConfigureAwait(true); Assert.Empty(remainingBreakpoints); } @@ -365,7 +359,7 @@ await debugService.SetLineBreakpointsAsync( VariableDetailsBase[] variables = GetVariables(VariableContainerDetails.LocalScopeName); // Verify the breakpoint only broke at the condition ie. $i -eq breakpointValue1 - var i = Array.Find(variables, v => v.Name == "$i"); + VariableDetailsBase i = Array.Find(variables, v => v.Name == "$i"); Assert.NotNull(i); Assert.False(i.IsExpandable); Assert.Equal($"{breakpointValue1}", i.ValueString); @@ -401,7 +395,7 @@ await debugService.SetLineBreakpointsAsync( VariableDetailsBase[] variables = GetVariables(VariableContainerDetails.LocalScopeName); // Verify the breakpoint only broke at the condition ie. $i -eq breakpointValue1 - var i = Array.Find(variables, v => v.Name == "$i"); + VariableDetailsBase i = Array.Find(variables, v => v.Name == "$i"); Assert.NotNull(i); Assert.False(i.IsExpandable); Assert.Equal($"{hitCount}", i.ValueString); @@ -422,7 +416,7 @@ await debugService.SetLineBreakpointsAsync( VariableDetailsBase[] variables = GetVariables(VariableContainerDetails.LocalScopeName); // Verify the breakpoint only broke at the condition ie. $i -eq breakpointValue1 - var i = Array.Find(variables, v => v.Name == "$i"); + VariableDetailsBase i = Array.Find(variables, v => v.Name == "$i"); Assert.NotNull(i); Assert.False(i.IsExpandable); // Condition is even numbers ($i starting at 1) should end up on 10 with a hit count of 5. @@ -482,7 +476,7 @@ await debugService.SetLineBreakpointsAsync( [Fact] public async Task DebuggerBreaksWhenRequested() { - var confirmedBreakpoints = await GetConfirmedBreakpoints(debugScriptFile).ConfigureAwait(true); + IReadOnlyList confirmedBreakpoints = await GetConfirmedBreakpoints(debugScriptFile).ConfigureAwait(true); Assert.Equal(0, confirmedBreakpoints.Count); Task _ = ExecuteDebugFile(); // NOTE: This must be run on a separate thread so the async event handlers can fire. @@ -516,7 +510,7 @@ await debugService.SetLineBreakpointsAsync( VariableDetailsBase[] variables = GetVariables(VariableContainerDetails.LocalScopeName); - var var = Array.Find(variables, v => v.Name == "$strVar"); + VariableDetailsBase var = Array.Find(variables, v => v.Name == "$strVar"); Assert.NotNull(var); Assert.Equal("\"Hello\"", var.ValueString); Assert.False(var.IsExpandable); @@ -535,38 +529,38 @@ await debugService.SetLineBreakpointsAsync( VariableDetailsBase[] variables = GetVariables(VariableContainerDetails.LocalScopeName); // TODO: Add checks for correct value strings as well - var strVar = Array.Find(variables, v => v.Name == "$strVar"); + VariableDetailsBase strVar = Array.Find(variables, v => v.Name == "$strVar"); Assert.NotNull(strVar); Assert.False(strVar.IsExpandable); - var objVar = Array.Find(variables, v => v.Name == "$assocArrVar"); + VariableDetailsBase objVar = Array.Find(variables, v => v.Name == "$assocArrVar"); Assert.NotNull(objVar); Assert.True(objVar.IsExpandable); - var objChildren = debugService.GetVariables(objVar.Id); + VariableDetailsBase[] objChildren = debugService.GetVariables(objVar.Id); // Two variables plus "Raw View" Assert.Equal(3, objChildren.Length); - var arrVar = Array.Find(variables, v => v.Name == "$arrVar"); + VariableDetailsBase arrVar = Array.Find(variables, v => v.Name == "$arrVar"); Assert.NotNull(arrVar); Assert.True(arrVar.IsExpandable); - var arrChildren = debugService.GetVariables(arrVar.Id); + VariableDetailsBase[] arrChildren = debugService.GetVariables(arrVar.Id); Assert.Equal(5, arrChildren.Length); - var classVar = Array.Find(variables, v => v.Name == "$classVar"); + VariableDetailsBase classVar = Array.Find(variables, v => v.Name == "$classVar"); Assert.NotNull(classVar); Assert.True(classVar.IsExpandable); - var classChildren = debugService.GetVariables(classVar.Id); + VariableDetailsBase[] classChildren = debugService.GetVariables(classVar.Id); Assert.Equal(2, classChildren.Length); - var trueVar = Array.Find(variables, v => v.Name == "$trueVar"); + VariableDetailsBase trueVar = Array.Find(variables, v => v.Name == "$trueVar"); Assert.NotNull(trueVar); Assert.Equal("boolean", trueVar.Type); Assert.Equal("$true", trueVar.ValueString); - var falseVar = Array.Find(variables, v => v.Name == "$falseVar"); + VariableDetailsBase falseVar = Array.Find(variables, v => v.Name == "$falseVar"); Assert.NotNull(falseVar); Assert.Equal("boolean", falseVar.Type); Assert.Equal("$false", falseVar.ValueString); @@ -611,17 +605,17 @@ await debugService.SetLineBreakpointsAsync( // Test set of a local string variable (not strongly typed) variables = GetVariables(VariableContainerDetails.LocalScopeName); - var strVar = Array.Find(variables, v => v.Name == "$strVar"); + VariableDetailsBase strVar = Array.Find(variables, v => v.Name == "$strVar"); Assert.Equal(newStrValue, strVar.ValueString); // Test set of script scope int variable (not strongly typed) variables = GetVariables(VariableContainerDetails.ScriptScopeName); - var intVar = Array.Find(variables, v => v.Name == "$scriptInt"); + VariableDetailsBase intVar = Array.Find(variables, v => v.Name == "$scriptInt"); Assert.Equal(newIntValue, intVar.ValueString); // Test set of global scope int variable (not strongly typed) variables = GetVariables(VariableContainerDetails.GlobalScopeName); - var intGlobalVar = Array.Find(variables, v => v.Name == "$MaximumHistoryCount"); + VariableDetailsBase intGlobalVar = Array.Find(variables, v => v.Name == "$MaximumHistoryCount"); Assert.Equal(newGlobalIntValue, intGlobalVar.ValueString); } @@ -667,17 +661,17 @@ await debugService.SetLineBreakpointsAsync( // Test set of a local string variable (not strongly typed but force conversion) variables = GetVariables(VariableContainerDetails.LocalScopeName); - var strVar = Array.Find(variables, v => v.Name == "$strVar2"); + VariableDetailsBase strVar = Array.Find(variables, v => v.Name == "$strVar2"); Assert.Equal(newStrValue, strVar.ValueString); // Test set of script scope bool variable (strongly typed) variables = GetVariables(VariableContainerDetails.ScriptScopeName); - var boolVar = Array.Find(variables, v => v.Name == "$scriptBool"); + VariableDetailsBase boolVar = Array.Find(variables, v => v.Name == "$scriptBool"); Assert.Equal(newBoolValue, boolVar.ValueString); // Test set of global scope ActionPreference variable (strongly typed) variables = GetVariables(VariableContainerDetails.GlobalScopeName); - var globalVar = Array.Find(variables, v => v.Name == "$VerbosePreference"); + VariableDetailsBase globalVar = Array.Find(variables, v => v.Name == "$VerbosePreference"); Assert.Equal(newGlobalValue, globalVar.ValueString); } @@ -695,7 +689,7 @@ await debugService.SetLineBreakpointsAsync( StackFrameDetails[] stackFrames = await debugService.GetStackFramesAsync().ConfigureAwait(true); VariableDetailsBase[] variables = debugService.GetVariables(stackFrames[0].AutoVariables.Id); - var var = Array.Find(variables, v => v.Name == "$enumVar"); + VariableDetailsBase var = Array.Find(variables, v => v.Name == "$enumVar"); Assert.NotNull(var); Assert.Equal("Continue", var.ValueString); Assert.False(var.IsExpandable); @@ -748,7 +742,7 @@ await debugService.SetLineBreakpointsAsync( StackFrameDetails[] stackFrames = await debugService.GetStackFramesAsync().ConfigureAwait(true); VariableDetailsBase[] variables = debugService.GetVariables(stackFrames[0].AutoVariables.Id); - var nullStringVar = Array.Find(variables, v => v.Name == "$nullString"); + VariableDetailsBase nullStringVar = Array.Find(variables, v => v.Name == "$nullString"); Assert.NotNull(nullStringVar); Assert.Equal("[NullString]", nullStringVar.ValueString); Assert.True(nullStringVar.IsExpandable); @@ -768,7 +762,7 @@ await debugService.SetLineBreakpointsAsync( StackFrameDetails[] stackFrames = await debugService.GetStackFramesAsync().ConfigureAwait(true); VariableDetailsBase[] variables = debugService.GetVariables(stackFrames[0].AutoVariables.Id); - var psObjVar = Array.Find(variables, v => v.Name == "$psObjVar"); + VariableDetailsBase psObjVar = Array.Find(variables, v => v.Name == "$psObjVar"); Assert.NotNull(psObjVar); Assert.True("@{Age=75; Name=John}".Equals(psObjVar.ValueString) || "@{Name=John; Age=75}".Equals(psObjVar.ValueString)); Assert.True(psObjVar.IsExpandable); @@ -879,7 +873,7 @@ public async Task DebuggerDerivedDictionaryPropertyInRawView() Assert.Empty(rawDetailsView.ValueString); VariableDetailsBase[] rawViewChildren = rawDetailsView.GetChildren(NullLogger.Instance); Assert.Equal(4, rawViewChildren.Length); - Assert.NotNull(Array.Find(rawViewChildren, v => v .Name == "Comparer")); + Assert.NotNull(Array.Find(rawViewChildren, v => v.Name == "Comparer")); } [Fact] @@ -896,12 +890,12 @@ await debugService.SetLineBreakpointsAsync( StackFrameDetails[] stackFrames = await debugService.GetStackFramesAsync().ConfigureAwait(true); VariableDetailsBase[] variables = debugService.GetVariables(stackFrames[0].AutoVariables.Id); - var var = Array.Find(variables, v => v.Name == "$psCustomObjVar"); + VariableDetailsBase var = Array.Find(variables, v => v.Name == "$psCustomObjVar"); Assert.NotNull(var); Assert.Equal("@{Name=Paul; Age=73}", var.ValueString); Assert.True(var.IsExpandable); - var childVars = debugService.GetVariables(var.Id); + VariableDetailsBase[] childVars = debugService.GetVariables(var.Id); Assert.Equal(2, childVars.Length); Assert.Equal("Name", childVars[0].Name); Assert.Equal("\"Paul\"", childVars[0].ValueString); @@ -925,12 +919,12 @@ await debugService.SetLineBreakpointsAsync( StackFrameDetails[] stackFrames = await debugService.GetStackFramesAsync().ConfigureAwait(true); VariableDetailsBase[] variables = debugService.GetVariables(stackFrames[0].AutoVariables.Id); - var var = Array.Find(variables, v => v.Name == "$procVar"); + VariableDetailsBase var = Array.Find(variables, v => v.Name == "$procVar"); Assert.NotNull(var); Assert.StartsWith("System.Diagnostics.Process", var.ValueString); Assert.True(var.IsExpandable); - var childVars = debugService.GetVariables(var.Id); + VariableDetailsBase[] childVars = debugService.GetVariables(var.Id); Assert.Equal(53, childVars.Length); } } diff --git a/test/PowerShellEditorServices.Test/Extensions/ExtensionCommandTests.cs b/test/PowerShellEditorServices.Test/Extensions/ExtensionCommandTests.cs index cf972bde7..ee2163024 100644 --- a/test/PowerShellEditorServices.Test/Extensions/ExtensionCommandTests.cs +++ b/test/PowerShellEditorServices.Test/Extensions/ExtensionCommandTests.cs @@ -47,8 +47,8 @@ public void Dispose() public async Task CanRegisterAndInvokeCommandWithCmdletName() { string filePath = TestUtilities.NormalizePath("C:\\Temp\\Test.ps1"); - var currentFile = new ScriptFile(new Uri(filePath), "This is a test file", new Version("7.0")); - var editorContext = new EditorContext( + ScriptFile currentFile = new(new Uri(filePath), "This is a test file", new Version("7.0")); + EditorContext editorContext = new( editorOperations: null, currentFile, new BufferPosition(line: 1, column: 1), @@ -83,8 +83,8 @@ await psesHost.ExecutePSCommandAsync( public async Task CanRegisterAndInvokeCommandWithScriptBlock() { string filePath = TestUtilities.NormalizePath("C:\\Temp\\Test.ps1"); - var currentFile = new ScriptFile(new Uri(filePath), "This is a test file", new Version("7.0")); - var editorContext = new EditorContext( + ScriptFile currentFile = new(new Uri(filePath), "This is a test file", new Version("7.0")); + EditorContext editorContext = new( editorOperations: null, currentFile, new BufferPosition(line: 1, column: 1), @@ -144,8 +144,8 @@ await psesHost.ExecutePSCommandAsync( public async Task CanUnregisterCommand() { string filePath = TestUtilities.NormalizePath("C:\\Temp\\Test.ps1"); - var currentFile = new ScriptFile(new Uri(filePath), "This is a test file", new Version("7.0")); - var editorContext = new EditorContext( + ScriptFile currentFile = new(new Uri(filePath), "This is a test file", new Version("7.0")); + EditorContext editorContext = new( editorOperations: null, currentFile, new BufferPosition(line: 1, column: 1), diff --git a/test/PowerShellEditorServices.Test/Language/SemanticTokenTest.cs b/test/PowerShellEditorServices.Test/Language/SemanticTokenTest.cs index 2111a5e88..d41c7fc0d 100644 --- a/test/PowerShellEditorServices.Test/Language/SemanticTokenTest.cs +++ b/test/PowerShellEditorServices.Test/Language/SemanticTokenTest.cs @@ -25,7 +25,7 @@ function Get-Sum { return $a + $b } "; - ScriptFile scriptFile = new ScriptFile( + ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), text, @@ -33,7 +33,7 @@ function Get-Sum { foreach (Token t in scriptFile.ScriptTokens) { - List mappedTokens = new List(PsesSemanticTokensHandler.ConvertToSemanticTokens(t)); + List mappedTokens = new(PsesSemanticTokensHandler.ConvertToSemanticTokens(t)); switch (t.Text) { case "function": @@ -62,14 +62,14 @@ function Get-Sum { public void TokenizesStringExpansion() { string text = "Write-Host \"$(Test-Property Get-Whatever) $(Get-Whatever)\""; - ScriptFile scriptFile = new ScriptFile( + ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), text, Version.Parse("5.0")); Token commandToken = scriptFile.ScriptTokens[0]; - List mappedTokens = new List(PsesSemanticTokensHandler.ConvertToSemanticTokens(commandToken)); + List mappedTokens = new(PsesSemanticTokensHandler.ConvertToSemanticTokens(commandToken)); Assert.Single(mappedTokens, sToken => SemanticTokenType.Function == sToken.Type); Token stringExpandableToken = scriptFile.ScriptTokens[1]; @@ -89,7 +89,7 @@ function Get-A*A { } Get-A*A "; - ScriptFile scriptFile = new ScriptFile( + ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), text, @@ -97,7 +97,7 @@ function Get-A*A { foreach (Token t in scriptFile.ScriptTokens) { - List mappedTokens = new List(PsesSemanticTokensHandler.ConvertToSemanticTokens(t)); + List mappedTokens = new(PsesSemanticTokensHandler.ConvertToSemanticTokens(t)); switch (t.Text) { case "function": @@ -114,7 +114,7 @@ function Get-A*A { public void RecognizesArrayPropertyInExpandableString() { string text = "\"$(@($Array).Count) OtherText\""; - ScriptFile scriptFile = new ScriptFile( + ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), text, @@ -122,7 +122,7 @@ public void RecognizesArrayPropertyInExpandableString() foreach (Token t in scriptFile.ScriptTokens) { - List mappedTokens = new List(PsesSemanticTokensHandler.ConvertToSemanticTokens(t)); + List mappedTokens = new(PsesSemanticTokensHandler.ConvertToSemanticTokens(t)); switch (t.Text) { case "$Array": @@ -139,27 +139,27 @@ public void RecognizesArrayPropertyInExpandableString() public void RecognizesCurlyQuotedString() { string text = "“^[-'a-z]*”"; - ScriptFile scriptFile = new ScriptFile( + ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), text, Version.Parse("5.0")); - List mappedTokens = new List(PsesSemanticTokensHandler.ConvertToSemanticTokens(scriptFile.ScriptTokens[0])); + List mappedTokens = new(PsesSemanticTokensHandler.ConvertToSemanticTokens(scriptFile.ScriptTokens[0])); Assert.Single(mappedTokens, sToken => SemanticTokenType.String == sToken.Type); } [Fact] public void RecognizeEnum() { - string text = @" + string text = @" enum MyEnum{ one two three } "; - ScriptFile scriptFile = new ScriptFile( + ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), text, @@ -167,7 +167,7 @@ enum MyEnum{ foreach (Token t in scriptFile.ScriptTokens) { - List mappedTokens = new List(PsesSemanticTokensHandler.ConvertToSemanticTokens(t)); + List mappedTokens = new(PsesSemanticTokensHandler.ConvertToSemanticTokens(t)); switch (t.Text) { case "enum": diff --git a/test/PowerShellEditorServices.Test/Language/SymbolsServiceTests.cs b/test/PowerShellEditorServices.Test/Language/SymbolsServiceTests.cs index 3e68491ac..594400925 100644 --- a/test/PowerShellEditorServices.Test/Language/SymbolsServiceTests.cs +++ b/test/PowerShellEditorServices.Test/Language/SymbolsServiceTests.cs @@ -26,7 +26,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Language { [Trait("Category", "Symbols")] - public class SymbolsServiceTests: IDisposable + public class SymbolsServiceTests : IDisposable { private readonly PsesInternalHost psesHost; private readonly WorkspaceService workspace; diff --git a/test/PowerShellEditorServices.Test/Language/TokenOperationsTests.cs b/test/PowerShellEditorServices.Test/Language/TokenOperationsTests.cs index 53b4be337..f92b8d93e 100644 --- a/test/PowerShellEditorServices.Test/Language/TokenOperationsTests.cs +++ b/test/PowerShellEditorServices.Test/Language/TokenOperationsTests.cs @@ -15,14 +15,15 @@ public class TokenOperationsTests /// /// Helper method to create a stub script file and then call FoldableRegions /// - private static FoldingReference[] GetRegions(string text) { - ScriptFile scriptFile = new ScriptFile( + private static FoldingReference[] GetRegions(string text) + { + ScriptFile scriptFile = new( // Use any absolute path. Even if it doesn't exist. DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), text, Version.Parse("5.0")); - var result = TokenOperations.FoldableReferences(scriptFile.ScriptTokens).ToArray(); + FoldingReference[] result = TokenOperations.FoldableReferences(scriptFile.ScriptTokens).ToArray(); // The foldable regions need to be deterministic for testing so sort the array. Array.Sort(result); return result; @@ -31,13 +32,15 @@ private static FoldingReference[] GetRegions(string text) { /// /// Helper method to create FoldingReference objects with less typing /// - private static FoldingReference CreateFoldingReference(int startLine, int startCharacter, int endLine, int endCharacter, FoldingRangeKind? matchKind) { - return new FoldingReference { - StartLine = startLine, + private static FoldingReference CreateFoldingReference(int startLine, int startCharacter, int endLine, int endCharacter, FoldingRangeKind? matchKind) + { + return new FoldingReference + { + StartLine = startLine, StartCharacter = startCharacter, - EndLine = endLine, - EndCharacter = endCharacter, - Kind = matchKind + EndLine = endLine, + EndCharacter = endCharacter, + Kind = matchKind }; } @@ -131,7 +134,7 @@ double quoted herestrings should also fold $foo = 'bar' #EnDReGion "; - private FoldingReference[] expectedAllInOneScriptFolds = { + private readonly FoldingReference[] expectedAllInOneScriptFolds = { CreateFoldingReference(0, 0, 4, 10, FoldingRangeKind.Region), CreateFoldingReference(1, 0, 3, 2, FoldingRangeKind.Comment), CreateFoldingReference(10, 0, 15, 2, FoldingRangeKind.Comment), @@ -166,7 +169,8 @@ private static void AssertFoldingReferenceArrays( [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithLF() { + public void LaguageServiceFindsFoldablRegionsWithLF() + { // Remove and CR characters string testString = allInOneScript.Replace("\r", ""); // Ensure that there are no CR characters in the string @@ -177,11 +181,13 @@ public void LaguageServiceFindsFoldablRegionsWithLF() { [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithCRLF() { + public void LaguageServiceFindsFoldablRegionsWithCRLF() + { // The Foldable regions should be the same regardless of line ending type // Enforce CRLF line endings, if none exist string testString = allInOneScript; - if (testString.IndexOf("\r\n") == -1) { + if (!testString.Contains("\r\n")) + { testString = testString.Replace("\n", "\r\n"); } // Ensure that there are CRLF characters in the string @@ -192,7 +198,8 @@ public void LaguageServiceFindsFoldablRegionsWithCRLF() { [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithMismatchedRegions() { + public void LaguageServiceFindsFoldablRegionsWithMismatchedRegions() + { string testString = @"#endregion should not fold - mismatched @@ -212,7 +219,8 @@ public void LaguageServiceFindsFoldablRegionsWithMismatchedRegions() { [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithDuplicateRegions() { + public void LaguageServiceFindsFoldablRegionsWithDuplicateRegions() + { string testString = @"# This script causes duplicate/overlapping ranges due to the `(` and `{` characters $AnArray = @(Get-ChildItem -Path C:\ -Include *.ps1 -File).Where({ @@ -233,7 +241,8 @@ public void LaguageServiceFindsFoldablRegionsWithDuplicateRegions() { // ( -> ), @( -> ) and $( -> ) does not confuse the folder [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithSameEndToken() { + public void LaguageServiceFindsFoldablRegionsWithSameEndToken() + { string testString = @"foreach ($1 in $2) { @@ -260,7 +269,8 @@ public void LaguageServiceFindsFoldablRegionsWithSameEndToken() { // A simple PowerShell Classes test [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithClasses() { + public void LaguageServiceFindsFoldablRegionsWithClasses() + { string testString = @"class TestClass { [string[]] $TestProperty = @( @@ -287,7 +297,8 @@ [string] TestMethod() { // This tests DSC style keywords and param blocks [Trait("Category", "Folding")] [Fact] - public void LaguageServiceFindsFoldablRegionsWithDSC() { + public void LaguageServiceFindsFoldablRegionsWithDSC() + { string testString = @"Configuration Example { diff --git a/test/PowerShellEditorServices.Test/PsesHostFactory.cs b/test/PowerShellEditorServices.Test/PsesHostFactory.cs index 84c4e5ee5..3f7ab95b9 100644 --- a/test/PowerShellEditorServices.Test/PsesHostFactory.cs +++ b/test/PowerShellEditorServices.Test/PsesHostFactory.cs @@ -32,7 +32,7 @@ public static PsesInternalHost Create(ILoggerFactory loggerFactory) { // We intentionally use `CreateDefault2()` as it loads `Microsoft.PowerShell.Core` only, // which is a more minimal and therefore safer state. - var initialSessionState = InitialSessionState.CreateDefault2(); + InitialSessionState initialSessionState = InitialSessionState.CreateDefault2(); // We set the process scope's execution policy (which is really the runspace's scope) to // `Bypass` so we can import our bundled modules. This is equivalent in scope to the CLI @@ -59,7 +59,7 @@ public static PsesInternalHost Create(ILoggerFactory loggerFactory) usesLegacyReadLine: false, bundledModulePath: BundledModulePath); - var psesHost = new PsesInternalHost(loggerFactory, null, testHostDetails); + PsesInternalHost psesHost = new(loggerFactory, null, testHostDetails); // NOTE: Because this is used by constructors it can't use await. if (psesHost.TryStartAsync(new HostStartOptions { LoadProfiles = false }, CancellationToken.None).GetAwaiter().GetResult()) diff --git a/test/PowerShellEditorServices.Test/Services/Symbols/AstOperationsTests.cs b/test/PowerShellEditorServices.Test/Services/Symbols/AstOperationsTests.cs index c35bba787..75fa1c4f4 100644 --- a/test/PowerShellEditorServices.Test/Services/Symbols/AstOperationsTests.cs +++ b/test/PowerShellEditorServices.Test/Services/Symbols/AstOperationsTests.cs @@ -36,7 +36,7 @@ function FunctionWithExtraSpace FunctionNameOnDifferentLine "; - private static readonly ScriptBlockAst s_ast = (ScriptBlockAst) ScriptBlock.Create(s_scriptString).Ast; + private static readonly ScriptBlockAst s_ast = (ScriptBlockAst)ScriptBlock.Create(s_scriptString).Ast; [Theory] [InlineData(2, 3, "BasicFunction")] diff --git a/test/PowerShellEditorServices.Test/Session/PsesInternalHostTests.cs b/test/PowerShellEditorServices.Test/Session/PsesInternalHostTests.cs index 1598c10e2..d534f13a9 100644 --- a/test/PowerShellEditorServices.Test/Session/PsesInternalHostTests.cs +++ b/test/PowerShellEditorServices.Test/Session/PsesInternalHostTests.cs @@ -21,10 +21,7 @@ public class PsesInternalHostTests : IDisposable { private readonly PsesInternalHost psesHost; - public PsesInternalHostTests() - { - psesHost = PsesHostFactory.Create(NullLoggerFactory.Instance); - } + public PsesInternalHostTests() => psesHost = PsesHostFactory.Create(NullLoggerFactory.Instance); public void Dispose() { @@ -36,9 +33,9 @@ public void Dispose() public async Task CanExecutePSCommand() { Assert.True(psesHost.IsRunning); - var command = new PSCommand().AddScript("$a = \"foo\"; $a"); - var task = psesHost.ExecutePSCommandAsync(command, CancellationToken.None); - var result = await task.ConfigureAwait(true); + PSCommand command = new PSCommand().AddScript("$a = \"foo\"; $a"); + Task> task = psesHost.ExecutePSCommandAsync(command, CancellationToken.None); + IReadOnlyList result = await task.ConfigureAwait(true); Assert.Equal("foo", result[0]); } @@ -97,7 +94,7 @@ await Assert.ThrowsAsync(() => [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD003:Avoid awaiting foreign Tasks", Justification = "Explicitly checking task cancellation status.")] public async Task CanCancelExecutionWithMethod() { - var executeTask = psesHost.ExecutePSCommandAsync( + Task executeTask = psesHost.ExecutePSCommandAsync( new PSCommand().AddScript("Start-Sleep 10"), CancellationToken.None); @@ -132,7 +129,7 @@ public async Task CanResolveAndLoadProfilesForHostId() "$($profile.CurrentUserCurrentHost) " + "$(Assert-ProfileLoaded)\""); - var result = await psesHost.ExecutePSCommandAsync(psCommand, CancellationToken.None).ConfigureAwait(true); + IReadOnlyList result = await psesHost.ExecutePSCommandAsync(psCommand, CancellationToken.None).ConfigureAwait(true); string expectedString = string.Format( diff --git a/test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs b/test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs index 91b6a1e14..32b6992a3 100644 --- a/test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs +++ b/test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs @@ -16,9 +16,9 @@ public class ScriptFileChangeTests { #if CoreCLR - private static readonly Version PowerShellVersion = new Version(7, 2); + private static readonly Version PowerShellVersion = new(7, 2); #else - private static readonly Version PowerShellVersion = new Version(5, 1); + private static readonly Version PowerShellVersion = new(5, 1); #endif [Trait("Category", "ScriptFile")] @@ -180,25 +180,23 @@ public void CanAppendToEndOfFile() public void FindsDotSourcedFiles() { string exampleScriptContents = TestUtilities.PlatformNormalize( - ". ./athing.ps1\n"+ - ". ./somefile.ps1\n"+ - ". ./somefile.ps1\n"+ - "Do-Stuff $uri\n"+ + ". ./athing.ps1\n" + + ". ./somefile.ps1\n" + + ". ./somefile.ps1\n" + + "Do-Stuff $uri\n" + ". simpleps.ps1"); - using (StringReader stringReader = new StringReader(exampleScriptContents)) - { - ScriptFile scriptFile = - new ScriptFile( - // Use any absolute path. Even if it doesn't exist. - DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), - stringReader, - PowerShellVersion); - - Assert.Equal(3, scriptFile.ReferencedFiles.Length); - System.Console.Write("a" + scriptFile.ReferencedFiles[0]); - Assert.Equal(TestUtilities.NormalizePath("./athing.ps1"), scriptFile.ReferencedFiles[0]); - } + using StringReader stringReader = new(exampleScriptContents); + ScriptFile scriptFile = + new( + // Use any absolute path. Even if it doesn't exist. + DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), + stringReader, + PowerShellVersion); + + Assert.Equal(3, scriptFile.ReferencedFiles.Length); + System.Console.Write("a" + scriptFile.ReferencedFiles[0]); + Assert.Equal(TestUtilities.NormalizePath("./athing.ps1"), scriptFile.ReferencedFiles[0]); } [Trait("Category", "ScriptFile")] @@ -242,18 +240,16 @@ public void CanDeleteFromEndOfFile() internal static ScriptFile CreateScriptFile(string initialString) { - using (StringReader stringReader = new StringReader(initialString)) - { - // Create an in-memory file from the StringReader - ScriptFile fileToChange = - new ScriptFile( - // Use any absolute path. Even if it doesn't exist. - DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), - stringReader, - PowerShellVersion); - - return fileToChange; - } + using StringReader stringReader = new(initialString); + // Create an in-memory file from the StringReader + ScriptFile fileToChange = + new( + // Use any absolute path. Even if it doesn't exist. + DocumentUri.FromFileSystemPath(Path.Combine(Path.GetTempPath(), "TestFile.ps1")), + stringReader, + PowerShellVersion); + + return fileToChange; } private static void AssertFileChange( @@ -284,9 +280,9 @@ public class ScriptFileGetLinesTests private static readonly string[] s_testStringLines_trailingNewline = TestString_TrailingNewline.Split(s_newLines, StringSplitOptions.None); - private ScriptFile _scriptFile_trailingNewline; + private readonly ScriptFile _scriptFile_trailingNewline; - private ScriptFile _scriptFile_noTrailingNewline; + private readonly ScriptFile _scriptFile_noTrailingNewline; public ScriptFileGetLinesTests() { @@ -382,23 +378,17 @@ public void CanGetRangeAtLineBoundaries() [Trait("Category", "ScriptFile")] [Fact] - public void CanSplitLines_NoTrailingNewline() - { - Assert.Equal(s_testStringLines_noTrailingNewline, _scriptFile_noTrailingNewline.FileLines); - } + public void CanSplitLines_NoTrailingNewline() => Assert.Equal(s_testStringLines_noTrailingNewline, _scriptFile_noTrailingNewline.FileLines); [Trait("Category", "ScriptFile")] [Fact] - public void CanSplitLines_TrailingNewline() - { - Assert.Equal(s_testStringLines_trailingNewline, _scriptFile_trailingNewline.FileLines); - } + public void CanSplitLines_TrailingNewline() => Assert.Equal(s_testStringLines_trailingNewline, _scriptFile_trailingNewline.FileLines); [Trait("Category", "ScriptFile")] [Fact] public void CanGetSameLinesWithUnixLineBreaks() { - var unixFile = ScriptFileChangeTests.CreateScriptFile(TestString_NoTrailingNewline.Replace("\r\n", "\n")); + ScriptFile unixFile = ScriptFileChangeTests.CreateScriptFile(TestString_NoTrailingNewline.Replace("\r\n", "\n")); Assert.Equal(_scriptFile_noTrailingNewline.FileLines, unixFile.FileLines); } @@ -406,7 +396,7 @@ public void CanGetSameLinesWithUnixLineBreaks() [Fact] public void CanGetLineForEmptyString() { - var emptyFile = ScriptFileChangeTests.CreateScriptFile(string.Empty); + ScriptFile emptyFile = ScriptFileChangeTests.CreateScriptFile(string.Empty); Assert.Single(emptyFile.FileLines); Assert.Equal(string.Empty, emptyFile.FileLines[0]); } @@ -415,7 +405,7 @@ public void CanGetLineForEmptyString() [Fact] public void CanGetLineForSpace() { - var spaceFile = ScriptFileChangeTests.CreateScriptFile(" "); + ScriptFile spaceFile = ScriptFileChangeTests.CreateScriptFile(" "); Assert.Single(spaceFile.FileLines); Assert.Equal(" ", spaceFile.FileLines[0]); } @@ -423,11 +413,11 @@ public void CanGetLineForSpace() public class ScriptFilePositionTests { - private ScriptFile scriptFile; + private readonly ScriptFile scriptFile; public ScriptFilePositionTests() { - this.scriptFile = + scriptFile = ScriptFileChangeTests.CreateScriptFile(@" First line Second line is longer @@ -439,12 +429,12 @@ Third line [Fact] public void CanOffsetByLine() { - this.AssertNewPosition( + AssertNewPosition( 1, 1, 2, 0, 3, 1); - this.AssertNewPosition( + AssertNewPosition( 3, 1, -2, 0, 1, 1); @@ -454,12 +444,12 @@ public void CanOffsetByLine() [Fact] public void CanOffsetByColumn() { - this.AssertNewPosition( + AssertNewPosition( 2, 1, 0, 2, 2, 3); - this.AssertNewPosition( + AssertNewPosition( 2, 5, 0, -3, 2, 2); @@ -510,7 +500,7 @@ public void ThrowsWhenPositionOutOfRange() [Fact] public void CanFindBeginningOfLine() { - this.AssertNewPosition( + AssertNewPosition( 4, 12, pos => pos.GetLineStart(), 4, 5); @@ -520,7 +510,7 @@ public void CanFindBeginningOfLine() [Fact] public void CanFindEndOfLine() { - this.AssertNewPosition( + AssertNewPosition( 4, 12, pos => pos.GetLineEnd(), 4, 15); @@ -530,7 +520,7 @@ public void CanFindEndOfLine() [Fact] public void CanComposePositionOperations() { - this.AssertNewPosition( + AssertNewPosition( 4, 12, pos => pos.AddOffset(-1, 1).GetLineStart(), 3, 3); @@ -541,7 +531,7 @@ private void AssertNewPosition( int lineOffset, int columnOffset, int expectedLine, int expectedColumn) { - this.AssertNewPosition( + AssertNewPosition( originalLine, originalColumn, pos => pos.AddOffset(lineOffset, columnOffset), expectedLine, expectedColumn); @@ -552,10 +542,10 @@ private void AssertNewPosition( Func positionOperation, int expectedLine, int expectedColumn) { - var newPosition = + FilePosition newPosition = positionOperation( new FilePosition( - this.scriptFile, + scriptFile, originalLine, originalColumn)); @@ -566,15 +556,15 @@ private void AssertNewPosition( public class ScriptFileConstructorTests { - private static readonly Version PowerShellVersion = new Version("5.0"); + private static readonly Version PowerShellVersion = new("5.0"); [Trait("Category", "ScriptFile")] [Fact] public void PropertiesInitializedCorrectlyForFile() { // Use any absolute path. Even if it doesn't exist. - var path = Path.Combine(Path.GetTempPath(), "TestFile.ps1"); - var scriptFile = ScriptFileChangeTests.CreateScriptFile(""); + string path = Path.Combine(Path.GetTempPath(), "TestFile.ps1"); + ScriptFile scriptFile = ScriptFileChangeTests.CreateScriptFile(""); Assert.Equal(path, scriptFile.FilePath, ignoreCase: !VersionUtils.IsLinux); Assert.True(scriptFile.IsAnalysisEnabled); @@ -589,27 +579,25 @@ public void PropertiesInitializedCorrectlyForFile() [Fact] public void PropertiesInitializedCorrectlyForUntitled() { - var path = "untitled:untitled-1"; + string path = "untitled:untitled-1"; // 3 lines and 10 tokens in this script. - var script = @"function foo() { + string script = @"function foo() { 'foo' }"; - using (StringReader stringReader = new StringReader(script)) - { - // Create an in-memory file from the StringReader - var scriptFile = new ScriptFile(DocumentUri.From(path), stringReader, PowerShellVersion); - - Assert.Equal(path, scriptFile.FilePath); - Assert.Equal(path, scriptFile.DocumentUri); - Assert.True(scriptFile.IsAnalysisEnabled); - Assert.True(scriptFile.IsInMemory); - Assert.Empty(scriptFile.ReferencedFiles); - Assert.Empty(scriptFile.DiagnosticMarkers); - Assert.Equal(10, scriptFile.ScriptTokens.Length); - Assert.Equal(3, scriptFile.FileLines.Count); - } + using StringReader stringReader = new(script); + // Create an in-memory file from the StringReader + ScriptFile scriptFile = new(DocumentUri.From(path), stringReader, PowerShellVersion); + + Assert.Equal(path, scriptFile.FilePath); + Assert.Equal(path, scriptFile.DocumentUri); + Assert.True(scriptFile.IsAnalysisEnabled); + Assert.True(scriptFile.IsInMemory); + Assert.Empty(scriptFile.ReferencedFiles); + Assert.Empty(scriptFile.DiagnosticMarkers); + Assert.Equal(10, scriptFile.ScriptTokens.Length); + Assert.Equal(3, scriptFile.FileLines.Count); } [Trait("Category", "ScriptFile")] @@ -618,7 +606,7 @@ public void DocumentUriRetunsCorrectStringForAbsolutePath() { string path; ScriptFile scriptFile; - var emptyStringReader = new StringReader(""); + StringReader emptyStringReader = new(""); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { @@ -664,9 +652,6 @@ public void DocumentUriRetunsCorrectStringForAbsolutePath() [InlineData("vscode-notebook-cell:/Users/me/Documents/test.ps1#0001", true)] [InlineData("https://microsoft.com", true)] [InlineData("Untitled:Untitled-1", true)] - public void IsUntitledFileIsCorrect(string path, bool expected) - { - Assert.Equal(expected, ScriptFile.IsUntitledPath(path)); - } + public void IsUntitledFileIsCorrect(string path, bool expected) => Assert.Equal(expected, ScriptFile.IsUntitledPath(path)); } } diff --git a/test/PowerShellEditorServices.Test/Session/WorkspaceTests.cs b/test/PowerShellEditorServices.Test/Session/WorkspaceTests.cs index f3cc5bbee..e617e53ab 100644 --- a/test/PowerShellEditorServices.Test/Session/WorkspaceTests.cs +++ b/test/PowerShellEditorServices.Test/Session/WorkspaceTests.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.EditorServices.Test.Session { public class WorkspaceTests { - private static readonly Lazy s_lazyDriveLetter = new Lazy(() => Path.GetFullPath("\\").Substring(0, 1)); + private static readonly Lazy s_lazyDriveLetter = new(() => Path.GetFullPath("\\").Substring(0, 1)); public static string CurrentDriveLetter => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? s_lazyDriveLetter.Value @@ -29,7 +29,7 @@ public void CanResolveWorkspaceRelativePath() string testPathOutside = TestUtilities.NormalizePath("c:/Test/PeerPath/FilePath.ps1"); string testPathAnotherDrive = TestUtilities.NormalizePath("z:/TryAndFindMe/FilePath.ps1"); - WorkspaceService workspace = new WorkspaceService(NullLoggerFactory.Instance); + WorkspaceService workspace = new(NullLoggerFactory.Instance); // Test without a workspace path Assert.Equal(testPathOutside, workspace.GetRelativePath(testPathOutside)); @@ -46,17 +46,18 @@ public void CanResolveWorkspaceRelativePath() internal static WorkspaceService FixturesWorkspace() { - return new WorkspaceService(NullLoggerFactory.Instance) { + return new WorkspaceService(NullLoggerFactory.Instance) + { WorkspacePath = TestUtilities.NormalizePath("Fixtures/Workspace") }; } // These are the default values for the EnumeratePSFiles() method // in Microsoft.PowerShell.EditorServices.Workspace class - private static string[] s_defaultExcludeGlobs = Array.Empty(); - private static string[] s_defaultIncludeGlobs = new [] { "**/*" }; - private static int s_defaultMaxDepth = 64; - private static bool s_defaultIgnoreReparsePoints = false; + 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; internal static List ExecuteEnumeratePSFiles( WorkspaceService workspace, @@ -66,13 +67,13 @@ internal static List ExecuteEnumeratePSFiles( bool ignoreReparsePoints ) { - var result = workspace.EnumeratePSFiles( + IEnumerable result = workspace.EnumeratePSFiles( excludeGlobs: excludeGlobs, includeGlobs: includeGlobs, maxDepth: maxDepth, ignoreReparsePoints: ignoreReparsePoints ); - var fileList = new List(); + List fileList = new(); foreach (string file in result) { fileList.Add(file); } // Assume order is not important from EnumeratePSFiles and sort the array so we can use deterministic asserts fileList.Sort(); @@ -84,8 +85,8 @@ bool ignoreReparsePoints [Trait("Category", "Workspace")] public void CanRecurseDirectoryTree() { - var workspace = FixturesWorkspace(); - var fileList = ExecuteEnumeratePSFiles( + WorkspaceService workspace = FixturesWorkspace(); + List fileList = ExecuteEnumeratePSFiles( workspace: workspace, excludeGlobs: s_defaultExcludeGlobs, includeGlobs: s_defaultIncludeGlobs, @@ -119,8 +120,8 @@ public void CanRecurseDirectoryTree() [Trait("Category", "Workspace")] public void CanRecurseDirectoryTreeWithLimit() { - var workspace = FixturesWorkspace(); - var fileList = ExecuteEnumeratePSFiles( + WorkspaceService workspace = FixturesWorkspace(); + List fileList = ExecuteEnumeratePSFiles( workspace: workspace, excludeGlobs: s_defaultExcludeGlobs, includeGlobs: s_defaultIncludeGlobs, @@ -128,7 +129,7 @@ public void CanRecurseDirectoryTreeWithLimit() ignoreReparsePoints: s_defaultIgnoreReparsePoints ); - Assert.Equal(1, fileList.Count); + Assert.Single(fileList); Assert.Equal(Path.Combine(workspace.WorkspacePath, "rootfile.ps1"), fileList[0]); } @@ -136,11 +137,11 @@ public void CanRecurseDirectoryTreeWithLimit() [Trait("Category", "Workspace")] public void CanRecurseDirectoryTreeWithGlobs() { - var workspace = FixturesWorkspace(); - var fileList = ExecuteEnumeratePSFiles( + WorkspaceService workspace = FixturesWorkspace(); + List fileList = ExecuteEnumeratePSFiles( workspace: workspace, - excludeGlobs: new [] {"**/donotfind*"}, // Exclude any files starting with donotfind - includeGlobs: new [] {"**/*.ps1", "**/*.psd1"}, // Only include PS1 and PSD1 files + excludeGlobs: new[] { "**/donotfind*" }, // Exclude any files starting with donotfind + includeGlobs: new[] { "**/*.ps1", "**/*.psd1" }, // Only include PS1 and PSD1 files maxDepth: s_defaultMaxDepth, ignoreReparsePoints: s_defaultIgnoreReparsePoints ); diff --git a/test/PowerShellEditorServices.Test/Utility/VersionUtilsTests.cs b/test/PowerShellEditorServices.Test/Utility/VersionUtilsTests.cs index 5d13982c0..bc95053b8 100644 --- a/test/PowerShellEditorServices.Test/Utility/VersionUtilsTests.cs +++ b/test/PowerShellEditorServices.Test/Utility/VersionUtilsTests.cs @@ -10,13 +10,12 @@ public class VersionUtilsTests { [Trait("Category", "VersionUtils")] [Fact] - public void IsNetCoreTest() - { + public void IsNetCoreTest() => #if CoreCLR Assert.True(VersionUtils.IsNetCore); #else Assert.False(VersionUtils.IsNetCore); #endif - } + } }