forked from microsoft/VSExtensibility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinterUtilities.cs
226 lines (198 loc) · 8.11 KB
/
LinterUtilities.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace MarkdownLinter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Provider;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.VisualStudio.Extensibility.Editor;
using Microsoft.VisualStudio.Extensibility.Languages;
using Microsoft.VisualStudio.RpcContracts;
using Microsoft.VisualStudio.RpcContracts.DiagnosticManagement;
using Microsoft.VisualStudio.Threading;
/// <summary>
/// Helper class for running linter on a string or file.
/// </summary>
internal static class LinterUtilities
{
private static readonly Regex LinterOutputRegex = new(@"(?<File>[^:]+):(?<Line>\d*)(:(?<Column>\d*))? (?<Error>.*)/(?<Description>.*)", RegexOptions.Compiled);
/// <summary>
/// Runs markdown linter on a file uri and returns diagnostic entries.
/// </summary>
/// <param name="fileUri">File uri to run markdown linter on.</param>
/// <returns>an enumeration of <see cref="DocumentDiagnostic"/> entries for warnings in the markdown file.</returns>
public static async Task<IEnumerable<DocumentDiagnostic>> RunLinterOnFileAsync(Uri fileUri)
{
using var linter = new Process();
var lineQueue = new AsyncQueue<string>();
linter.StartInfo = new ProcessStartInfo()
{
FileName = "node.exe",
Arguments = $"\"{Environment.ExpandEnvironmentVariables("%APPDATA%\\npm\\node_modules\\markdownlint-cli\\markdownlint.js")}\" \"{fileUri.LocalPath}\"",
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
linter.EnableRaisingEvents = true;
linter.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (e.Data is not null)
{
lineQueue.Enqueue(e.Data);
}
else
{
lineQueue.Complete();
}
});
try
{
linter.Start();
linter.BeginErrorReadLine();
}
catch (Win32Exception ex)
{
throw new InvalidOperationException(message: ex.Message, innerException: ex);
}
var markdownDiagnostics = await ProcessLinterQueueAsync(lineQueue);
return CreateDocumentDiagnosticsForClosedDocument(fileUri, markdownDiagnostics);
}
/// <summary>
/// Runs markdown linter on a given text document and returns diagnostic entries.
/// </summary>
/// <param name="textDocument">Document to run markdown linter on.</param>
/// <returns>an enumeration of <see cref="DocumentDiagnostic"/> entries for warnings in the markdown file.</returns>
public static async Task<IEnumerable<DocumentDiagnostic>> RunLinterOnDocumentAsync(ITextDocumentSnapshot textDocument)
{
using var linter = new Process();
var lineQueue = new AsyncQueue<string>();
var content = textDocument.Text.CopyToString();
linter.StartInfo = new ProcessStartInfo()
{
FileName = "cmd.exe",
Arguments = $"/k \"{Environment.ExpandEnvironmentVariables("%APPDATA%\\npm\\markdownlint.cmd")}\" -s",
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true,
};
linter.EnableRaisingEvents = true;
linter.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (e.Data is not null)
{
lineQueue.Enqueue(e.Data);
}
else
{
lineQueue.Complete();
}
});
try
{
linter.Start();
linter.BeginErrorReadLine();
linter.StandardInput.AutoFlush = true;
await linter.StandardInput.WriteAsync(content);
linter.StandardInput.Close();
}
catch (Win32Exception ex)
{
throw new InvalidOperationException(message: ex.Message, innerException: ex);
}
var markdownDiagnostics = await ProcessLinterQueueAsync(lineQueue);
return CreateDocumentDiagnosticsForOpenDocument(textDocument, markdownDiagnostics);
}
/// <summary>
/// Checks if the given path is a valid markdown file.
/// </summary>
/// <param name="localPath">Local file path to verify.</param>
/// <returns>true if file is a markdown file, false otherwise.</returns>
public static bool IsValidMarkdownFile(string localPath)
{
return localPath is not null && Path.GetExtension(localPath).Equals(".md", StringComparison.OrdinalIgnoreCase);
}
private static IEnumerable<DocumentDiagnostic> CreateDocumentDiagnosticsForOpenDocument(ITextDocumentSnapshot document, IEnumerable<MarkdownDiagnosticInfo> diagnostics)
{
foreach (var diagnostic in diagnostics)
{
var startindex = document.Lines[diagnostic.Range.StartLine].Text.Start.Offset;
if (diagnostic.Range.StartColumn >= 0)
{
startindex += diagnostic.Range.StartColumn;
}
var endIndex = document.Lines[diagnostic.Range.EndLine].Text.Start.Offset;
if (diagnostic.Range.EndColumn >= 0)
{
endIndex += diagnostic.Range.EndColumn;
}
yield return new DocumentDiagnostic(new TextRange(document, startindex, endIndex - startindex), diagnostic.Message)
{
ErrorCode = diagnostic.ErrorCode,
Severity = DiagnosticSeverity.Warning,
ProviderName = "Markdown Linter",
};
}
}
private static IEnumerable<DocumentDiagnostic> CreateDocumentDiagnosticsForClosedDocument(Uri fileUri, IEnumerable<MarkdownDiagnosticInfo> diagnostics)
{
foreach (var diagnostic in diagnostics)
{
yield return new DocumentDiagnostic(fileUri, diagnostic.Range, diagnostic.Message)
{
ErrorCode = diagnostic.ErrorCode,
Severity = DiagnosticSeverity.Warning,
ProviderName = "Markdown Linter",
};
}
}
private static async Task<IEnumerable<MarkdownDiagnosticInfo>> ProcessLinterQueueAsync(AsyncQueue<string> lineQueue)
{
Requires.NotNull(lineQueue, nameof(lineQueue));
List<MarkdownDiagnosticInfo> diagnostics = new List<MarkdownDiagnosticInfo>();
while (!(lineQueue.IsCompleted && lineQueue.IsEmpty))
{
string? line;
try
{
line = await lineQueue.DequeueAsync();
}
catch (OperationCanceledException)
{
break;
}
var diagnostic = line is not null ? GetDiagnosticFromLinterOutput(line) : null;
if (diagnostic is not null)
{
diagnostics.Add(diagnostic);
}
else
{
// Something went wrong so break and return the current set.
break;
}
}
return diagnostics;
}
private static MarkdownDiagnosticInfo? GetDiagnosticFromLinterOutput(string outputLine)
{
Requires.NotNull(outputLine, nameof(outputLine));
var match = LinterOutputRegex.Match(outputLine);
if (!match.Success)
{
return null;
}
int line = int.Parse(match.Groups["Line"].Value, CultureInfo.InvariantCulture) - 1;
int column = match.Groups.ContainsKey("Column") && !string.IsNullOrEmpty(match.Groups["Column"].Value) ? (int.Parse(match.Groups["Column"].Value, CultureInfo.InvariantCulture) - 1) : -1;
return new MarkdownDiagnosticInfo(
range: new Microsoft.VisualStudio.RpcContracts.Utilities.Range(startLine: line, startColumn: column),
message: match.Groups["Description"].Value,
errorCode: match.Groups["Error"].Value);
}
}