-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathextension.ts
More file actions
281 lines (255 loc) · 9.55 KB
/
Copy pathextension.ts
File metadata and controls
281 lines (255 loc) · 9.55 KB
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
import fs = require("fs");
import path = require("path");
import vscode = require("vscode");
let diagnosticCollectionRubocop: vscode.DiagnosticCollection;
let config: vscode.WorkspaceConfiguration;
let rubocopPath: string;
let rubocopConfigFile: string;
let cookbookPaths: Array<string> = [];
let fileCount: number;
let cookstyleVersionChecked: boolean = false;
const MINIMUM_COOKSTYLE_VERSION = "8.6.10";
export function activate(context: vscode.ExtensionContext): void {
diagnosticCollectionRubocop = vscode.languages.createDiagnosticCollection("rubocop");
context.subscriptions.push(diagnosticCollectionRubocop);
// Find Cookstyle executable in multiple candidate locations
// Supports both Chef Workstation 25 (omnibus) and 26 (habitat)
const customPath = vscode.workspace.getConfiguration("rubocop").path;
if (customPath !== "") {
// User-configured custom path takes priority
rubocopPath = customPath;
console.log("Using custom Rubocop path: " + rubocopPath);
} else {
// Auto-detect Cookstyle by checking candidate paths in priority order
let candidatePaths: string[] = [];
if (process.platform === "win32") {
candidatePaths = [
"C:\\hab\\bin\\cookstyle.bat", // CW26 habitat
"C:\\opscode\\chef-workstation\\bin\\cookstyle.bat" // CW25 omnibus
];
} else if (process.platform === "darwin") {
candidatePaths = [
"/usr/local/bin/cookstyle", // CW26 symlink (habitat wrapper)
"/opt/chef-workstation/bin/cookstyle" // CW25 omnibus direct path
];
} else {
// Linux and other Unix platforms
candidatePaths = [
"/usr/bin/cookstyle", // CW26 symlink (common on Linux)
"/usr/local/bin/cookstyle", // CW26 symlink (some distros)
"/opt/chef-workstation/bin/cookstyle" // CW25 omnibus direct path
];
}
// Find first existing executable
rubocopPath = "";
for (const candidatePath of candidatePaths) {
if (fs.existsSync(candidatePath)) {
rubocopPath = candidatePath;
break;
}
}
// Fallback to first candidate if none found
// checkCookstyleVersion() will handle the error and show appropriate warning
if (!rubocopPath) {
rubocopPath = candidatePaths[0];
}
}
if (vscode.workspace.getConfiguration("rubocop").configFile === "") {
console.log("No explicit config file set for Rubocop.");
} else {
rubocopConfigFile = vscode.workspace.getConfiguration("rubocop").configFile;
console.log("Using custom Rubocop config from: " + rubocopConfigFile);
}
if (vscode.workspace.getConfiguration("rubocop").enable) {
checkCookstyleVersion();
updateRubyFileCountAndValidate(true);
context.subscriptions.push(startLintingOnSaveWatcher());
context.subscriptions.push(startLintingOnConfigurationChangeWatcher());
}
// Even if disabled, allow the user to manually validate the entire workspace.
const command = "chef.validateEntireWorkspace";
const commandHandler = () => {
console.log("Called chef.validateEntireWorkspace command handler");
validateEntireWorkspace();
};
context.subscriptions.push(vscode.commands.registerCommand(command, commandHandler));
}
function checkCookstyleVersion(): void {
if (cookstyleVersionChecked) {
return;
}
// Avoid executing workspace-provided binaries in untrusted workspaces
if (!vscode.workspace.isTrusted) {
return;
}
try {
let spawn = require("child_process").spawnSync;
let result = spawn(rubocopPath, ["--version"], { encoding: "utf-8", timeout: 5000, windowsHide: true });
if (result.error || result.status !== 0) {
throw (result.error ?? new Error(`Cookstyle --version failed with status ${result.status}`));
}
if (result.stdout) {
let versionMatch = result.stdout.match(/(\d+\.\d+\.\d+)/);
if (versionMatch) {
let version = versionMatch[1];
console.log(`Detected Cookstyle version: ${version}`);
// Parse version components
let parts = version.split('.').map(Number);
let minParts = MINIMUM_COOKSTYLE_VERSION.split('.').map(Number);
// Check if version is below minimum
let isOldVersion = false;
for (let i = 0; i < 3; i++) {
if (parts[i] < minParts[i]) {
isOldVersion = true;
break;
} else if (parts[i] > minParts[i]) {
break;
}
}
if (isOldVersion) {
vscode.window.showWarningMessage(
`Chef extension detected Cookstyle ${version}. Version ${MINIMUM_COOKSTYLE_VERSION}+ is required. Please upgrade to the latest Chef Workstation for best results.`,
"Upgrade Instructions"
).then(selection => {
if (selection === "Upgrade Instructions") {
vscode.env.openExternal(vscode.Uri.parse("https://docs.chef.io/workstation/install/"));
}
});
} else {
console.log(`Cookstyle version ${version} is compatible (minimum: ${MINIMUM_COOKSTYLE_VERSION})`);
}
}
}
cookstyleVersionChecked = true;
} catch (err) {
console.log("Could not check Cookstyle version:", err);
vscode.window.showWarningMessage(
`Chef extension could not detect Cookstyle at: ${rubocopPath}. Verify the path in rubocop.path setting or install Chef Workstation.`,
"Download Chef Workstation"
).then(selection => {
if (selection === "Download Chef Workstation") {
vscode.env.openExternal(vscode.Uri.parse("https://docs.chef.io/workstation/install/"));
}
});
}
}
function convertSeverity(severity: string): vscode.DiagnosticSeverity {
switch (severity) {
case "fatal":
case "error":
return vscode.DiagnosticSeverity.Error;
case "warning":
return vscode.DiagnosticSeverity.Warning;
case "convention":
case "refactor":
return vscode.DiagnosticSeverity.Information;
default:
return vscode.DiagnosticSeverity.Warning;
}
}
function updateRubyFileCountAndValidate(warn: boolean = false): void {
// OK for this to be approximate
let stopAt = vscode.workspace.getConfiguration("rubocop").fileCountThreshold + 1
fileCount = 0
let uriCounter = (u:vscode.Uri) => {
fileCount++;
}
let countAndValidate = (uri_array:Array<vscode.Uri>) => {
uri_array.forEach(uriCounter)
validate(warn);
}
vscode.workspace.findFiles("**/*.rb", null, stopAt)
.then(countAndValidate)
}
function validate(warn:boolean = false): void {
console.log("Saw at least " + fileCount + " Ruby files in Workspace");
if (fileCount < vscode.workspace.getConfiguration("rubocop").fileCountThreshold) {
validateEntireWorkspace();
} else {
if (warn) {
let msg: string = "There are a large number of Ruby files in your workspace. " +
"The Chef Infra Extension will only lint open files rather than " +
"the entire workspace to avoid becoming unresponsive."
vscode.window.showWarningMessage(msg,"Ok");
}
validateOpenFiles();
}
}
function validateOpenFiles(): void {
let relPaths: Array<string> = [];
vscode.window.visibleTextEditors.forEach((text_editor: vscode.TextEditor) => {
if (text_editor.document.languageId == "ruby" && text_editor.document.fileName) {
relPaths.unshift(text_editor.document.fileName);
}
})
validatePaths(relPaths);
}
function validateEntireWorkspace(): void {
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
vscode.window.showErrorMessage('Chef: No workspace folder is open');
return;
}
validatePaths([vscode.workspace.workspaceFolders[0].uri.fsPath])
}
function validatePaths(paths: Array<string>): void {
try {
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
return;
}
if (!vscode.workspace.isTrusted) {
return;
}
const workspaceRoot = vscode.workspace.workspaceFolders[0].uri.fsPath;
const isWindows = process.platform === 'win32';
let spawn = require("child_process").spawnSync;
let rubocop: any;
if (rubocopConfigFile) {
rubocop = spawn(rubocopPath, ["--parallel", "--config", rubocopConfigFile, "-f", "j"].concat(paths), { shell: isWindows, cwd: workspaceRoot });
} else {
rubocop = spawn(rubocopPath, ["--parallel", "-f", "j"].concat(paths), { shell: isWindows, cwd: workspaceRoot });
}
let rubocopOutput = JSON.parse(rubocop.stdout);
if (rubocop.status < 2) {
let arr = [];
for (var r = 0; r < rubocopOutput.files.length; r++) {
var rubocopFile = rubocopOutput.files[r];
let uri: vscode.Uri = vscode.Uri.file((path.join(workspaceRoot, rubocopFile.path)));
var offenses = rubocopFile.offenses;
let diagnostics: vscode.Diagnostic[] = [];
for (var i = 0; i < offenses.length; i++) {
let _line = parseInt(offenses[i].location.line, 10) - 1;
let _start = parseInt(offenses[i].location.column, 10) - 1;
let _end = parseInt(_start + offenses[i].location.length, 10);
let diagRange = new vscode.Range(_line, _start, _line, _end);
let diagMsg = `${offenses[i].message}`;
let diagSeverity = convertSeverity(offenses[i].severity);
let diagnostic = new vscode.Diagnostic(diagRange, diagMsg, diagSeverity);
diagnostics.push(diagnostic);
}
arr.push([uri, diagnostics]);
}
diagnosticCollectionRubocop.clear();
diagnosticCollectionRubocop.set(arr);
} else {
console.log("Rubocop executed but exited with status: " + rubocop.status + rubocop.stdout);
}
} catch (err) {
console.log(err);
}
return;
}
function startLintingOnSaveWatcher():any {
return vscode.workspace.onDidSaveTextDocument(document => {
console.log("onDidSaveTextDocument event received (rubocop).");
if (document.languageId !== "ruby") {
return;
}
validate();
});
}
function startLintingOnConfigurationChangeWatcher():any {
return vscode.workspace.onDidChangeConfiguration(params => {
console.log("Workspace configuration changed, validating workspace.");
validate();
});
}