This repository has been archived by the owner on Apr 14, 2023. It is now read-only.
/
vsUtils.ts
312 lines (272 loc) · 8 KB
/
vsUtils.ts
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import * as path from "path";
import * as which from "which";
import * as fs from "fs";
import * as request from "request-promise-native";
import { execFile } from "child_process";
import * as vscode from "vscode";
// If `customPath` contains `${workspaceFolder}`, replaces it with the workspace that `file` comes from.
// Return `null` if `customPath` contains `${workspaceFolder}` and `file` is _not_ part of the workspace.
function replaceWorkspaceFolder(logger: vscode.OutputChannel, customPath: string, file: vscode.TextDocument): string | null {
customPath = path.normalize(customPath);
const workspaceFolder = vscode.workspace.getWorkspaceFolder(file.uri);
if (workspaceFolder) {
return customPath.replace(
"${workspaceFolder}",
workspaceFolder.uri.fsPath
);
}
logger.appendLine(`Not running Vale on file '${file.uri}' as it is not contained within the workspace`);
return null;
}
export const readBinaryLocation = (logger: vscode.OutputChannel, file: vscode.TextDocument): string | null => {
const configuration = vscode.workspace.getConfiguration();
let customBinaryPath = configuration.get<string>("vale.valeCLI.path");
if (customBinaryPath) {
return replaceWorkspaceFolder(logger, customBinaryPath, file);
}
return which.sync("vale");
};
export const readFileLocation = (logger: vscode.OutputChannel, file: vscode.TextDocument): string | null => {
const configuration = vscode.workspace.getConfiguration();
let customConfigPath = configuration.get<string>("vale.valeCLI.config");
if (customConfigPath) {
return replaceWorkspaceFolder(logger, customConfigPath, file);
}
return "";
};
/**
* Convert a Vale severity string to a code diagnostic severity.
*
* @param severity The severity to convert
*/
export const toSeverity = (
severity: ValeSeverity
): vscode.DiagnosticSeverity => {
switch (severity) {
case "suggestion":
return vscode.DiagnosticSeverity.Information;
case "warning":
return vscode.DiagnosticSeverity.Warning;
case "error":
return vscode.DiagnosticSeverity.Error;
}
};
/**
* Create an action title from a given alert and suggestion.
*
* @param alert The Vale-created alert
* @param suggestion The vsengine-calculated suggestion
*/
export const toTitle = (alert: IValeErrorJSON, suggestion: string): string => {
switch (alert.Action.Name) {
case "remove":
return "Remove '" + alert.Match + "'";
}
return "Replace with '" + suggestion + "'";
};
/**
* Whether a given document is elligible for linting.
*
* A document is elligible if it's in a supported format and saved to disk.
*
* @param document The document to check
* @return Whether the document is elligible
*/
export const isElligibleDocument = (document: vscode.TextDocument): boolean => {
if (document.isDirty) {
vscode.window.showErrorMessage("Please save the file before linting.");
return false;
}
return vscode.languages.match({ scheme: "file" }, document) > 0;
};
/**
* Convert a Vale error to a code diagnostic.
*
* @param alert The alert to convert
*/
export const toDiagnostic = (
alert: IValeErrorJSON,
styles: string,
backend: string,
offset: number
): vscode.Diagnostic => {
const range = new vscode.Range(
alert.Line - 1 + offset,
alert.Span[0] - 1,
alert.Line - 1 + offset,
alert.Span[1]
);
const diagnostic = new vscode.Diagnostic(
range,
alert.Message,
toSeverity(alert.Severity)
);
diagnostic.source = backend;
if (alert.Link.length > 0) {
diagnostic.code = {
value: alert.Check,
target: vscode.Uri.parse(alert.Link)
};
} else {
diagnostic.code = alert.Check;
}
const name = alert.Check.split(".");
const rule = vscode.Uri.file(path.join(styles, name[0], name[1] + ".yml"));
if (fs.existsSync(rule.fsPath)) {
diagnostic.relatedInformation = [
new vscode.DiagnosticRelatedInformation(
new vscode.Location(rule, new vscode.Position(0, 0)),
"View rule"
),
];
}
return diagnostic;
};
/**
* Run a command in a given workspace folder and get its standard output.
*
* If the workspace folder is undefined run the command in the working directory
* of the current vscode instance.
*
* @param folder The workspace
* @param command The command array
* @return The standard output of the program
*/
export const runInWorkspace = (
folder: string | undefined,
command: ReadonlyArray<string>
): Promise<string> =>
new Promise((resolve, reject) => {
const cwd = folder ? folder : process.cwd();
const maxBuffer = 10 * 1024 * 1024; // 10MB buffer for large results
execFile(
command[0],
command.slice(1),
{ cwd, maxBuffer },
(error, stdout, stderr) => {
if (error) {
resolve(stderr);
} else {
resolve(stdout);
}
}
);
});
const extractParagraph = (editor: vscode.TextEditor): vscode.Range => {
let startLine = editor.selection.start.line;
let endLine = editor.selection.end.line;
while (
startLine > 0 &&
!editor.document.lineAt(startLine - 1).isEmptyOrWhitespace
) {
startLine -= 1;
}
while (
endLine < editor.document.lineCount - 1 &&
!editor.document.lineAt(endLine + 1).isEmptyOrWhitespace
) {
endLine += 1;
}
const startCharacter = 0;
const endCharacter = editor.document.lineAt(endLine).text.length;
return new vscode.Range(startLine, startCharacter, endLine, endCharacter);
};
export const findContext = (): IEditorContext => {
const editor = vscode.window.activeTextEditor;
let context: IEditorContext = { Content: "", Offset: 0 };
if (!editor) {
return context;
}
const range = extractParagraph(editor);
context.Content = editor.document.getText(range);
context.Offset = range.start.line;
return context;
};
export const postFile = async (doc: vscode.TextDocument): Promise<string> => {
let server: string = vscode.workspace
.getConfiguration()
.get("vale.server.serverURL", "http://localhost:7777");
let response: string = "";
await request
.post({
uri: server + "/file",
qs: {
file: doc.fileName,
path: path.dirname(doc.fileName),
},
json: true,
})
.catch((error) => {
vscode.window.showErrorMessage(
`Vale Server could not connect: ${error}.`
);
})
.then((body) => {
response = fs.readFileSync(body.path).toString();
});
return response;
};
export const postString = async (
content: string,
ext: string
): Promise<string> => {
let server: string = vscode.workspace
.getConfiguration()
.get("vale.server.serverURL", "http://localhost:7777");
let response: string = "";
await request
.post({
uri: server + "/vale",
qs: {
text: content,
format: ext,
},
json: false,
})
.catch((error) => {
vscode.window.showErrorMessage(
`Vale Server could not connect: ${error}.`
);
})
.then((body) => {
response = body;
});
return response;
};
export const getStylesPath = async (): Promise<string> => {
const configuration = vscode.workspace.getConfiguration();
let path: string = "";
let server: string = configuration.get(
"vale.server.serverURL",
"http://localhost:7777"
);
await request
.get({ uri: server + "/path", json: true })
.catch((error) => {
throw new Error(`Vale Server could not connect: ${error}.`);
})
.then((body) => {
path = body.path;
});
return path;
};
export const buildCommand = (
exe: string,
config: string,
path: string
): Array<string> => {
const configuration = vscode.workspace.getConfiguration();
let command: Array<string> = [exe, "--no-exit"];
if (config !== "") {
command = command.concat(["--config", config]);
}
let minAlertLevel: string = configuration.get<string>(
"vale.valeCLI.minAlertLevel",
"inherited"
);
if (minAlertLevel !== "inherited") {
command = command.concat(["--minAlertLevel", minAlertLevel]);
}
command = command.concat(["--output", "JSON", path]);
return command;
};