Skip to content

Add support for a "Show Documentation" quick fix menu entry #789

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 5 commits into from
Nov 15, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
89 changes: 56 additions & 33 deletions src/PowerShellEditorServices.Protocol/Server/LanguageServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ namespace Microsoft.PowerShell.EditorServices.Protocol.Server
{
public class LanguageServer
{
private static CancellationTokenSource existingRequestCancellation;
private static CancellationTokenSource s_existingRequestCancellation;

private static readonly Location[] s_emptyLocationResult = new Location[0];

Expand All @@ -48,6 +48,7 @@ public class LanguageServer
private LanguageServerEditorOperations editorOperations;
private LanguageServerSettings currentSettings = new LanguageServerSettings();

// The outer key is the file's uri, the inner key is a unique id for the diagnostic
private Dictionary<string, Dictionary<string, MarkerCorrection>> codeActionsPerFile =
new Dictionary<string, Dictionary<string, MarkerCorrection>>();

Expand Down Expand Up @@ -1182,6 +1183,7 @@ private bool IsQueryMatch(string query, string symbolName)
return symbolName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0;
}

// https://microsoft.github.io/language-server-protocol/specification#textDocument_codeAction
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

omg we should have comments like this all over... so great! (not in this PR 😄 )

protected async Task HandleCodeActionRequest(
CodeActionParams codeActionParams,
RequestContext<CodeActionCommand[]> requestContext)
Expand All @@ -1194,8 +1196,17 @@ protected async Task HandleCodeActionRequest(
{
foreach (var diagnostic in codeActionParams.Context.Diagnostics)
{
if (!string.IsNullOrEmpty(diagnostic.Code) &&
markerIndex.TryGetValue(diagnostic.Code, out correction))
if (string.IsNullOrEmpty(diagnostic.Code))
{
this.Logger.Write(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

LogLevel.Warning,
$"textDocument/codeAction skipping diagnostic with empty Code field: {diagnostic.Source} {diagnostic.Message}");

continue;
}

string diagnosticId = GetUniqueIdFromDiagnostic(diagnostic);
if (markerIndex.TryGetValue(diagnosticId, out correction))
{
codeActionCommands.Add(
new CodeActionCommand
Expand All @@ -1205,6 +1216,17 @@ protected async Task HandleCodeActionRequest(
Arguments = JArray.FromObject(correction.Edits)
});
}

if (string.Equals(diagnostic.Source, "PSScriptAnalyzer", StringComparison.OrdinalIgnoreCase))
{
codeActionCommands.Add(
new CodeActionCommand
{
Title = $"Show documentation for \"{diagnostic.Code}\"",
Command = "PowerShell.ShowCodeActionDocumentation",
Arguments = JArray.FromObject(new[] { diagnostic.Code })
});
}
}
}

Expand Down Expand Up @@ -1454,15 +1476,15 @@ private Task RunScriptDiagnostics(
// If there's an existing task, attempt to cancel it
try
{
if (existingRequestCancellation != null)
if (s_existingRequestCancellation != null)
{
// Try to cancel the request
existingRequestCancellation.Cancel();
s_existingRequestCancellation.Cancel();

// If cancellation didn't throw an exception,
// clean up the existing token
existingRequestCancellation.Dispose();
existingRequestCancellation = null;
s_existingRequestCancellation.Dispose();
s_existingRequestCancellation = null;
}
}
catch (Exception e)
Expand All @@ -1479,11 +1501,17 @@ private Task RunScriptDiagnostics(
return cancelTask.Task;
}

// If filesToAnalzye is empty, nothing to do so return early.
if (filesToAnalyze.Length == 0)
{
return Task.FromResult(true);
}

// Create a fresh cancellation token and then start the task.
// We create this on a different TaskScheduler so that we
// don't block the main message loop thread.
// TODO: Is there a better way to do this?
existingRequestCancellation = new CancellationTokenSource();
s_existingRequestCancellation = new CancellationTokenSource();
Task.Factory.StartNew(
() =>
DelayThenInvokeDiagnostics(
Expand All @@ -1494,36 +1522,14 @@ private Task RunScriptDiagnostics(
editorSession,
eventSender,
this.Logger,
existingRequestCancellation.Token),
s_existingRequestCancellation.Token),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default);

return Task.FromResult(true);
}

private static async Task DelayThenInvokeDiagnostics(
int delayMilliseconds,
ScriptFile[] filesToAnalyze,
bool isScriptAnalysisEnabled,
Dictionary<string, Dictionary<string, MarkerCorrection>> correctionIndex,
EditorSession editorSession,
EventContext eventContext,
ILogger Logger,
CancellationToken cancellationToken)
{
await DelayThenInvokeDiagnostics(
delayMilliseconds,
filesToAnalyze,
isScriptAnalysisEnabled,
correctionIndex,
editorSession,
eventContext.SendEvent,
Logger,
cancellationToken);
}


private static async Task DelayThenInvokeDiagnostics(
int delayMilliseconds,
ScriptFile[] filesToAnalyze,
Expand All @@ -1534,6 +1540,12 @@ private static async Task DelayThenInvokeDiagnostics(
ILogger Logger,
CancellationToken cancellationToken)
{
// If filesToAnalzye is empty, nothing to do so return early.
if (filesToAnalyze.Length == 0)
{
return;
}

// First of all, wait for the desired delay period before
// analyzing the provided list of files
try
Expand Down Expand Up @@ -1620,7 +1632,8 @@ private static async Task PublishScriptDiagnostics(
Diagnostic markerDiagnostic = GetDiagnosticFromMarker(marker);
if (marker.Correction != null)
{
fileCorrections.Add(markerDiagnostic.Code, marker.Correction);
string diagnosticId = GetUniqueIdFromDiagnostic(markerDiagnostic);
fileCorrections.Add(diagnosticId, marker.Correction);
}

diagnostics.Add(markerDiagnostic);
Expand All @@ -1639,13 +1652,23 @@ await eventSender(
});
}

private static string GetUniqueIdFromDiagnostic(Diagnostic diagnostic)
{
string source = diagnostic.Source ?? "?";
string code = diagnostic.Code ?? "?";
string severity = diagnostic.Severity != null ? diagnostic.Severity.ToString() : "?";
Position start = diagnostic.Range.Start;
Position end = diagnostic.Range.End;
return $"{source}_{code}_{severity}_{start.Line}:{start.Character}-{end.Line}:{end.Character}";
}

private static Diagnostic GetDiagnosticFromMarker(ScriptFileMarker scriptFileMarker)
{
return new Diagnostic
{
Severity = MapDiagnosticSeverity(scriptFileMarker.Level),
Message = scriptFileMarker.Message,
Code = scriptFileMarker.Source + Guid.NewGuid().ToString(),
Code = scriptFileMarker.RuleName,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is so much nicer!

Source = scriptFileMarker.Source,
Range = new Range
{
Expand Down
9 changes: 7 additions & 2 deletions src/PowerShellEditorServices/Workspace/ScriptFileMarker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ public class ScriptFileMarker
/// Gets or sets the marker's message string.
/// </summary>
public string Message { get; set; }

/// <summary>
/// Gets or sets the ruleName associated with this marker.
/// </summary>
public string RuleName { get; set; }

/// <summary>
/// Gets or sets the marker's message level.
Expand Down Expand Up @@ -130,7 +135,6 @@ internal static ScriptFileMarker FromDiagnosticRecord(PSObject psObject)
// the diagnostic record's properties directly i.e. <instance>.<propertyName>
// without having to go through PSObject's Members property.
var diagnosticRecord = psObject as dynamic;
string ruleName = diagnosticRecord.RuleName as string;

if (diagnosticRecord.SuggestedCorrections != null)
{
Expand Down Expand Up @@ -160,7 +164,8 @@ internal static ScriptFileMarker FromDiagnosticRecord(PSObject psObject)

return new ScriptFileMarker
{
Message = $"{diagnosticRecord.Message as string} ({ruleName})",
Message = $"{diagnosticRecord.Message as string}",
RuleName = $"{diagnosticRecord.RuleName as string}",
Level = GetMarkerLevelFromDiagnosticSeverity((diagnosticRecord.Severity as Enum).ToString()),
ScriptRegion = ScriptRegion.Create(diagnosticRecord.Extent as IScriptExtent),
Correction = correction,
Expand Down