-
Notifications
You must be signed in to change notification settings - Fork 236
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
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7c2cc1f
Add support for a "Show Documentation" quick fix menu entry
rkeithhill ede6866
Address PR comments by switching to StringBuilder
rkeithhill c0df728
Remove extra filesToAnalyze empty array check per PR feedback
rkeithhill dd73d26
Address PR feedback on StringBuilder
rkeithhill 96e83e6
Fix indentation issue as per PR feedback
rkeithhill File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,6 +17,7 @@ | |
using System.Linq; | ||
using System.Management.Automation; | ||
using System.Management.Automation.Language; | ||
using System.Text; | ||
using System.Text.RegularExpressions; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
@@ -27,7 +28,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]; | ||
|
||
|
@@ -48,6 +49,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>>(); | ||
|
||
|
@@ -1182,6 +1184,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 | ||
protected async Task HandleCodeActionRequest( | ||
CodeActionParams codeActionParams, | ||
RequestContext<CodeActionCommand[]> requestContext) | ||
|
@@ -1190,12 +1193,22 @@ protected async Task HandleCodeActionRequest( | |
Dictionary<string, MarkerCorrection> markerIndex = null; | ||
List<CodeActionCommand> codeActionCommands = new List<CodeActionCommand>(); | ||
|
||
// If there are any code fixes, send these commands first so they appear at top of "Code Fix" menu in the client UI. | ||
if (this.codeActionsPerFile.TryGetValue(codeActionParams.TextDocument.Uri, out markerIndex)) | ||
{ | ||
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( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
@@ -1208,8 +1221,30 @@ protected async Task HandleCodeActionRequest( | |
} | ||
} | ||
|
||
await requestContext.SendResult( | ||
codeActionCommands.ToArray()); | ||
// Add "show documentation" commands last so they appear at the bottom of the client UI. | ||
// These commands do not require code fixes. Sometimes we get a batch of diagnostics | ||
// to create commands for. No need to create multiple show doc commands for the same rule. | ||
var ruleNamesProcessed = new HashSet<string>(); | ||
foreach (var diagnostic in codeActionParams.Context.Diagnostics) | ||
{ | ||
if (string.IsNullOrEmpty(diagnostic.Code)) { continue; } | ||
|
||
if (string.Equals(diagnostic.Source, "PSScriptAnalyzer", StringComparison.OrdinalIgnoreCase) && | ||
!ruleNamesProcessed.Contains(diagnostic.Code)) | ||
{ | ||
ruleNamesProcessed.Add(diagnostic.Code); | ||
|
||
codeActionCommands.Add( | ||
new CodeActionCommand | ||
{ | ||
Title = $"Show documentation for \"{diagnostic.Code}\"", | ||
Command = "PowerShell.ShowCodeActionDocumentation", | ||
Arguments = JArray.FromObject(new[] { diagnostic.Code }) | ||
}); | ||
} | ||
} | ||
|
||
await requestContext.SendResult(codeActionCommands.ToArray()); | ||
} | ||
|
||
protected async Task HandleDocumentFormattingRequest( | ||
|
@@ -1454,15 +1489,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) | ||
|
@@ -1479,11 +1514,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); | ||
TylerLeonhardt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
// 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( | ||
SeeminglyScience marked this conversation as resolved.
Show resolved
Hide resolved
|
||
() => | ||
DelayThenInvokeDiagnostics( | ||
|
@@ -1494,36 +1535,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, | ||
|
@@ -1573,6 +1592,7 @@ private static async Task DelayThenInvokeDiagnostics( | |
|
||
await PublishScriptDiagnostics( | ||
scriptFile, | ||
// Concat script analysis errors to any existing parse errors | ||
scriptFile.SyntaxMarkers.Concat(semanticMarkers).ToArray(), | ||
correctionIndex, | ||
eventSender); | ||
|
@@ -1620,7 +1640,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); | ||
|
@@ -1639,13 +1660,39 @@ await eventSender( | |
}); | ||
} | ||
|
||
// Generate a unique id that is used as a key to look up the associated code action (code fix) when | ||
// we receive and process the textDocument/codeAction message. | ||
private static string GetUniqueIdFromDiagnostic(Diagnostic diagnostic) | ||
{ | ||
Position start = diagnostic.Range.Start; | ||
Position end = diagnostic.Range.End; | ||
|
||
var sb = new StringBuilder(256) | ||
.Append(diagnostic.Source ?? "?") | ||
.Append("_") | ||
.Append(diagnostic.Code ?? "?") | ||
.Append("_") | ||
.Append(diagnostic.Severity?.ToString() ?? "?") | ||
.Append("_") | ||
.Append(start.Line) | ||
.Append(":") | ||
.Append(start.Character) | ||
.Append("-") | ||
.Append(end.Line) | ||
.Append(":") | ||
.Append(end.Character); | ||
|
||
var id = sb.ToString(); | ||
return id; | ||
} | ||
|
||
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, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is so much nicer! |
||
Source = scriptFileMarker.Source, | ||
Range = new Range | ||
{ | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 😄 )