Skip to content

Code clean-up and fixing end-to-end tests #2000

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ dotnet_diagnostic.CS0649.severity = error
# CS1570: Parameter has no matching param tag in the XML comment
dotnet_diagnostic.CS1570.severity = silent
# CS1574: XML comment has cref attribute that could not be resolved.
dotnet_diagnostic.CS1574.severity = suggestion
dotnet_diagnostic.CS1574.severity = silent
# CS1591: Missing XML comment for publicly visible type or member
dotnet_diagnostic.CS1591.severity = silent
# CS1998: This async method lacks 'await' operators and will run synchronously
Expand Down
4 changes: 2 additions & 2 deletions PowerShellEditorServices.build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ Task TestE2E Build, SetupHelpForTests, {
Set-Location .\test\PowerShellEditorServices.Test.E2E\

$env:PWSH_EXE_NAME = if ($IsCoreCLR) { "pwsh" } else { "powershell" }
Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetRuntime.PS72 }
Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetRuntime.PS73 }

if (!$script:IsNix) {
if (-not [Security.Principal.WindowsIdentity]::GetCurrent().Owner.IsWellKnown("BuiltInAdministratorsSid")) {
Expand All @@ -214,7 +214,7 @@ Task TestE2E Build, SetupHelpForTests, {
try {
Write-Host "Running end-to-end tests in Constrained Language Mode."
[System.Environment]::SetEnvironmentVariable("__PSLockdownPolicy", "0x80000007", [System.EnvironmentVariableTarget]::Machine);
Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetRuntime.PS72 }
Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetRuntime.PS73 }
} finally {
[System.Environment]::SetEnvironmentVariable("__PSLockdownPolicy", $null, [System.EnvironmentVariableTarget]::Machine);
}
Expand Down
19 changes: 4 additions & 15 deletions src/PowerShellEditorServices/Extensions/EditorContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,26 +86,15 @@ public void SetSelection(
/// </summary>
/// <param name="startPosition">The starting position of the selection.</param>
/// <param name="endPosition">The ending position of the selection.</param>
public void SetSelection(
FilePosition startPosition,
FilePosition endPosition)
{
SetSelection(
new FileRange(
startPosition,
endPosition));
}
public void SetSelection(FilePosition startPosition, FilePosition endPosition) => SetSelection(new FileRange(startPosition, endPosition));

/// <summary>
/// Sets a selection in the host editor's active buffer.
/// </summary>
/// <param name="selectionRange">The range of the selection.</param>
public void SetSelection(FileRange selectionRange)
{
editorOperations
.SetSelectionAsync(selectionRange.ToBufferRange())
.Wait();
}
#pragma warning disable VSTHRD002
public void SetSelection(FileRange selectionRange) => editorOperations.SetSelectionAsync(selectionRange.ToBufferRange()).Wait();
#pragma warning restore VSTHRD002

#endregion
}
Expand Down
8 changes: 4 additions & 4 deletions src/PowerShellEditorServices/Extensions/EditorFileRanges.cs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ public interface ILspCurrentFileContext : IFileContext
ILspFileRange SelectionRange { get; }
}

internal struct OmnisharpLspPosition : ILspFilePosition, IEquatable<OmnisharpLspPosition>
internal readonly struct OmnisharpLspPosition : ILspFilePosition, IEquatable<OmnisharpLspPosition>
{
private readonly Position _position;

Expand All @@ -287,7 +287,7 @@ internal struct OmnisharpLspPosition : ILspFilePosition, IEquatable<OmnisharpLsp
public bool Equals(OmnisharpLspPosition other) => _position == other._position;
}

internal struct OmnisharpLspRange : ILspFileRange, IEquatable<OmnisharpLspRange>
internal readonly struct OmnisharpLspRange : ILspFileRange, IEquatable<OmnisharpLspRange>
{
private readonly Range _range;

Expand All @@ -300,7 +300,7 @@ internal struct OmnisharpLspRange : ILspFileRange, IEquatable<OmnisharpLspRange>
public bool Equals(OmnisharpLspRange other) => _range == other._range;
}

internal struct BufferFilePosition : IFilePosition, IEquatable<BufferFilePosition>
internal readonly struct BufferFilePosition : IFilePosition, IEquatable<BufferFilePosition>
{
private readonly BufferPosition _position;

Expand All @@ -317,7 +317,7 @@ public bool Equals(BufferFilePosition other)
}
}

internal struct BufferFileRange : IFileRange, IEquatable<BufferFileRange>
internal readonly struct BufferFileRange : IFileRange, IEquatable<BufferFileRange>
{
private readonly BufferRange _range;

Expand Down
2 changes: 2 additions & 0 deletions src/PowerShellEditorServices/Extensions/EditorObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ internal EditorObject(
/// at the time this method is invoked.
/// </summary>
/// <returns>A instance of the EditorContext class.</returns>
#pragma warning disable VSTHRD002, VSTHRD104
public EditorContext GetEditorContext() => _editorOperations.GetEditorContextAsync().Result;
#pragma warning restore VSTHRD002, VSTHRD104

internal void SetAsStaticInstance()
{
Expand Down
2 changes: 2 additions & 0 deletions src/PowerShellEditorServices/Extensions/EditorWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ internal EditorWindow(IEditorOperations editorOperations)
#endregion

#region Public Methods
#pragma warning disable VSTHRD002 // These are public APIs that use async internal methods.

/// <summary>
/// Shows an informational message to the user.
Expand Down Expand Up @@ -71,6 +72,7 @@ internal EditorWindow(IEditorOperations editorOperations)
/// <param name="timeout">A timeout in milliseconds for how long the message should remain visible.</param>
public void SetStatusBarMessage(string message, int timeout) => editorOperations.SetStatusBarMessageAsync(message, timeout).Wait();

#pragma warning restore VSTHRD002
#endregion
}
}
2 changes: 2 additions & 0 deletions src/PowerShellEditorServices/Extensions/EditorWorkspace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public sealed class EditorWorkspace
#endregion

#region Public Methods
#pragma warning disable VSTHRD002 // These are public APIs that use async internal methods.

/// <summary>
/// Creates a new file in the editor
Expand All @@ -53,6 +54,7 @@ public sealed class EditorWorkspace
/// <param name="preview">Determines wether the file is opened as a preview or as a durable editor.</param>
public void OpenFile(string filePath, bool preview) => editorOperations.OpenFileAsync(filePath, preview).Wait();

#pragma warning restore VSTHRD002
#endregion
}
}
6 changes: 5 additions & 1 deletion src/PowerShellEditorServices/Extensions/FileContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,12 +209,14 @@ public void InsertText(
/// </summary>
/// <param name="textToInsert">The text string to insert.</param>
/// <param name="insertRange">The buffer range which will be replaced by the string.</param>
#pragma warning disable VSTHRD002
public void InsertText(string textToInsert, IFileRange insertRange)
{
editorOperations
.InsertTextAsync(scriptFile.DocumentUri.ToString(), textToInsert, insertRange.ToBufferRange())
.Wait();
}
#pragma warning restore VSTHRD002

#endregion

Expand All @@ -232,6 +234,7 @@ public void InsertText(string textToInsert, IFileRange insertRange)
/// the path where the file should be saved,
/// including the file name with extension as the leaf
/// </param>
#pragma warning disable VSTHRD002
public void SaveAs(string newFilePath)
{
// Do some validation here so that we can provide a helpful error if the path won't work
Expand All @@ -244,8 +247,9 @@ public void SaveAs(string newFilePath)
throw new IOException(string.Format("The file '{0}' already exists", absolutePath));
}

editorOperations.SaveFileAsync(scriptFile.FilePath, newFilePath);
editorOperations.SaveFileAsync(scriptFile.FilePath, newFilePath).Wait();
}
#pragma warning restore VSTHRD002

#endregion
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public static EditorServicesServerFactory Create(string logPath, int minimumLogL
/// <param name="inputStream">The protocol transport input stream.</param>
/// <param name="outputStream">The protocol transport output stream.</param>
/// <param name="hostStartupInfo">The host details configuration for Editor Services
/// instantation.</param>
/// instantiation.</param>
/// <returns>A new, unstarted language server instance.</returns>
public PsesLanguageServer CreateLanguageServer(
Stream inputStream,
Expand Down
1 change: 1 addition & 0 deletions src/PowerShellEditorServices/Logging/LoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace Microsoft.PowerShell.EditorServices.Logging
{
internal static class LoggerExtensions
{
// TODO: These need to be fixed (and used consistently).
public static void LogException(
this ILogger logger,
string message,
Expand Down
13 changes: 0 additions & 13 deletions src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -559,19 +559,6 @@ public StackFrameDetails[] GetStackFrames()
}
}

internal StackFrameDetails[] GetStackFrames(CancellationToken cancellationToken)
{
debugInfoHandle.Wait(cancellationToken);
try
{
return stackFrameDetails;
}
finally
{
debugInfoHandle.Release();
}
}

internal async Task<StackFrameDetails[]> GetStackFramesAsync()
{
await debugInfoHandle.WaitAsync().ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ public class InvalidPowerShellExpressionException : Exception
/// Initializes a new instance of the SetVariableExpressionException class.
/// </summary>
/// <param name="message">Message indicating why the expression is invalid.</param>
public InvalidPowerShellExpressionException(string message)
: base(message)
{
}
public InvalidPowerShellExpressionException(string message) : base(message) { }

public InvalidPowerShellExpressionException() { }

public InvalidPowerShellExpressionException(string message, Exception innerException) : base(message, innerException) { }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,19 @@ internal class StackTraceHandler : IStackTraceHandler

public StackTraceHandler(DebugService debugService) => _debugService = debugService;

public Task<StackTraceResponse> Handle(StackTraceArguments request, CancellationToken cancellationToken)
public async Task<StackTraceResponse> Handle(StackTraceArguments request, CancellationToken cancellationToken)
{
StackFrameDetails[] stackFrameDetails =
_debugService.GetStackFrames(cancellationToken);
StackFrameDetails[] stackFrameDetails = await _debugService.GetStackFramesAsync(cancellationToken).ConfigureAwait(false);

// Handle a rare race condition where the adapter requests stack frames before they've
// begun building.
if (stackFrameDetails == null)
if (stackFrameDetails is null)
{
return Task.FromResult(new StackTraceResponse
return new StackTraceResponse
{
StackFrames = Array.Empty<StackFrame>(),
TotalFrames = 0
});
};
}

List<StackFrame> newStackFrames = new();
Expand All @@ -52,19 +51,14 @@ public Task<StackTraceResponse> Handle(StackTraceArguments request, Cancellation
{
// Create the new StackFrame object with an ID that can
// be referenced back to the current list of stack frames
//newStackFrames.Add(
// StackFrame.Create(
// stackFrameDetails[i],
// i));
newStackFrames.Add(
LspDebugUtils.CreateStackFrame(stackFrameDetails[i], id: i));
newStackFrames.Add(LspDebugUtils.CreateStackFrame(stackFrameDetails[i], id: i));
}

return Task.FromResult(new StackTraceResponse
return new StackTraceResponse
{
StackFrames = newStackFrames,
TotalFrames = newStackFrames.Count
});
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public static Task<DscBreakpointCapability> GetDscCapabilityAsync(
return Task.FromResult<DscBreakpointCapability>(null);
}

Func<SMA.PowerShell, CancellationToken, DscBreakpointCapability> getDscBreakpointCapabilityFunc = (pwsh, _) =>
DscBreakpointCapability getDscBreakpointCapabilityFunc(SMA.PowerShell pwsh, CancellationToken _)
{
PSInvocationSettings invocationSettings = new()
{
Expand Down Expand Up @@ -159,7 +159,7 @@ public static Task<DscBreakpointCapability> GetDscCapabilityAsync(
logger.LogTrace($"DSC resources found: {resourcePaths.Count}");

return capability;
};
}

return psesHost.ExecuteDelegateAsync(
nameof(getDscBreakpointCapabilityFunc),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ namespace Microsoft.PowerShell.EditorServices.Handlers
{
internal class GetVersionHandler : IGetVersionHandler
{
public async Task<PowerShellVersion> Handle(GetVersionParams request, CancellationToken cancellationToken)
public Task<PowerShellVersion> Handle(GetVersionParams request, CancellationToken cancellationToken)
{
return new PowerShellVersion
return Task.FromResult(new PowerShellVersion
{
Version = VersionUtils.PSVersionString,
Edition = VersionUtils.PSEdition,
Commit = VersionUtils.GitCommitId,
Architecture = VersionUtils.Architecture
};
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,7 @@ public async Task<RunspaceResponse[]> Handle(GetRunspaceParams request, Cancella
{
IEnumerable<PSObject> runspaces = null;

if (request.ProcessId == null)
{
request.ProcessId = "current";
}
request.ProcessId ??= "current";

// If the processId is a valid int, we need to run Get-Runspace within that process
// otherwise just use the current runspace.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -241,7 +242,7 @@ public static async Task<AliasMap> GetAliasesAsync(
.AddParameter("CommandType", CommandTypes.Alias),
cancellationToken).ConfigureAwait(false);

foreach (AliasInfo aliasInfo in aliases)
foreach (AliasInfo aliasInfo in aliases.Cast<AliasInfo>())
{
// TODO: When we move to netstandard2.1, we can use another overload which generates
// static delegates and thus reduces allocations.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,7 @@ public PsesCodeActionHandler(ILoggerFactory factory, AnalysisService analysisSer
CodeActionKinds = new CodeActionKind[] { CodeActionKind.QuickFix }
};

// TODO: Either fix or ignore "method lacks 'await'" warning.
public override async Task<CodeAction> Handle(CodeAction request, CancellationToken cancellationToken)
{
// TODO: How on earth do we handle a CodeAction? This is new...
if (cancellationToken.IsCancellationRequested)
{
_logger.LogDebug("CodeAction request canceled for: {Title}", request.Title);
}
return request;
}
public override Task<CodeAction> Handle(CodeAction request, CancellationToken cancellationToken) => Task.FromResult(request);

public override async Task<CommandOrCodeActionContainer> Handle(CodeActionParams request, CancellationToken cancellationToken)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ internal static FoldingReferenceList FoldableReferences(Token[] tokens)
refList.SafeAdd(CreateFoldingReference(blockStartToken, blockNextLine - 1, FoldingRangeKind.Comment));
blockStartToken = token;
}
if (blockStartToken == null) { blockStartToken = token; }
blockStartToken ??= token;
blockNextLine = thisLine + 1;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public override async Task<Container<SymbolInformation>> Handle(WorkspaceSymbolP

foreach (ScriptFile scriptFile in _workspaceService.GetOpenedFiles())
{
_logger.LogDebug($"Handling workspace symbols request for: {request.Query}");
IEnumerable<SymbolReference> foundSymbols = _symbolsService.FindSymbolsInFile(scriptFile);

// TODO: Need to compute a relative path that is based on common path for all workspace files
Expand Down Expand Up @@ -89,7 +90,7 @@ public override async Task<Container<SymbolInformation>> Handle(WorkspaceSymbolP
});
}
}
_logger.LogWarning("Logging in a handler works now.");

return new Container<SymbolInformation>(symbols);
}

Expand Down
Loading