forked from soderlind/vscode-phpcbf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
329 lines (297 loc) · 10.3 KB
/
extension.js
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
"use strict";
const vscode = require("vscode");
const {
commands,
workspace,
window,
languages,
Range,
Position
} = vscode;
const path = require("path");
const fs = require("fs");
const os = require("os");
const cp = require("child_process");
const TmpDir = os.tmpdir();
class PHPCBF {
constructor() {
this.loadSettings();
}
loadSettings() {
let config = workspace.getConfiguration(
"phpcbf",
window.activeTextEditor.document.uri
);
if (!config.get("enable") === true) {
return;
}
this.onsave = config.get("onsave", false);
this.executablePath = config.get(
"executablePath",
process.platform == "win32" ? "php-cbf.bat" : "phpcbf"
);
this.configSearch = config.get("configSearch", false);
/**
* relative paths?
*/
// ${workspaceRoot} is deprecated
if (this.executablePath.startsWith("${workspaceRoot}")) {
this.addRootPath("${workspaceRoot}");
}
if (this.executablePath.startsWith("${workspaceFolder}")) {
this.addRootPath("${workspaceFolder}");
}
if (this.executablePath.startsWith(".")) {
this.addRootPath(".");
}
if (this.executablePath.startsWith("~")) {
this.executablePath = this.executablePath.replace(
/^~\//,
os.homedir() + "/"
);
}
this.standard = config.get("standard", null);
this.documentFormattingProvider = config.get(
"documentFormattingProvider",
true
);
this.debug = config.get("debug", false);
}
getArgs(document, tmpFileName) {
let args = [];
if (this.debug) {
args.push("-l");
} else {
args.push("-lq");
}
args.push(tmpFileName);
this.standard = this.getStandard(document);
if (this.standard) {
args.push("--standard=" + this.standard);
}
if (this.debug) {
console.group("PHPCBF");
console.log(
"PHPCBF args: " + this.executablePath + " " + args.join(" ")
);
}
return args;
}
getStandard(document) {
// Check if a config file exists and handle it
let standard = null;
const folder = workspace.getWorkspaceFolder(document.uri);
const workspaceRoot = folder ? folder.uri.fsPath : null;
const filePath = document.fileName;
if (this.configSearch && workspaceRoot !== null && filePath !== undefined) {
const confFileNames = [
'.phpcs.xml', '.phpcs.xml.dist', 'phpcs.xml', 'phpcs.xml.dist',
'phpcs.ruleset.xml', 'ruleset.xml',
];
const fileDir = path.relative(workspaceRoot, path.dirname(filePath));
const confFile = this.findFiles(workspaceRoot, fileDir, confFileNames);
standard = confFile || this.standard;
} else {
standard = this.standard;
}
return standard;
}
findFiles(parent, directory, name) {
const names = [].concat(name);
const chunks = path.resolve(parent, directory).split(path.sep);
while (chunks.length) {
let currentDir = chunks.join(path.sep);
for (const fileName of names) {
const filePath = path.join(currentDir, fileName);
if (fs.existsSync(filePath)) {
return filePath;
}
}
if (parent === currentDir) {
break;
}
chunks.pop();
}
return null;
}
format(document) {
if (this.debug) {
console.time("phpcbf");
}
let text = document.getText();
let phpcbfError = false;
let fileName =
TmpDir +
"/temp-" +
Math.random()
.toString(36)
.replace(/[^a-z]+/g, "")
.substr(0, 10) +
".php";
fs.writeFileSync(fileName, text);
let exec = cp.spawn(this.executablePath, this.getArgs(document, fileName));
if (!this.debug) {
exec.stdin.end();
}
let promise = new Promise((resolve, reject) => {
exec.on("error", err => {
reject();
console.log(err);
if (err.code == "ENOENT") {
window.showErrorMessage(
"PHPCBF: " + err.message + ". executablePath not found."
);
}
});
exec.on("exit", code => {
/* phpcbf exit codes:
Exit code 0 is used to indicate that no fixable errors were found, so nothing was fixed
Exit code 1 is used to indicate that all fixable errors were fixed correctly
Exit code 2 is used to indicate that PHPCBF failed to fix some of the fixable errors it found
Exit code 3 is used for general script execution errors
*/
switch (code) {
case 0:
reject();
break;
case 1:
case 2:
let fixed = fs.readFileSync(fileName, "utf-8");
if (fixed.length > 0) {
resolve(fixed);
} else {
reject();
}
break;
case 3:
reject();
phpcbfError = true;
break;
default:
let msgs = {
3: "PHPCBF: General script execution errors.",
16: "PHPCBF: Configuration error of the application.",
32: "PHPCBF: Configuration error of a Fixer.",
64: "PHPCBF: Exception raised within the application."
};
window.showErrorMessage(msgs[code]);
reject();
break;
}
fs.unlink(fileName, function (err) {});
});
});
if (phpcbfError) {
exec.stdout.on("data", buffer => {
console.log(buffer.toString());
window.showErrorMessage(buffer.toString());
});
}
if (this.debug) {
exec.stdout.on("data", buffer => {
console.log(buffer.toString());
});
}
exec.stderr.on("data", buffer => {
console.log(buffer.toString());
});
exec.on("close", code => {
// console.log(code);
if (this.debug) {
console.timeEnd("phpcbf");
console.groupEnd();
}
});
return promise;
}
addRootPath(prefix) {
const resources = [];
if (workspace.workspaceFolders) {
for (let wsFolder of workspace.workspaceFolders) {
resources.push(wsFolder.uri);
}
} else {
const editor = window.activeTextEditor;
if (editor) {
resources.push(editor.document.uri);
}
}
for (let resource of resources) {
if (resource.scheme == "file") {
const folder = workspace.getWorkspaceFolder(resource);
if (folder) {
const rootPath = folder.uri.fsPath;
let tmpExecutablePath = this.executablePath.replace(
prefix,
rootPath
);
fs.exists(tmpExecutablePath, exists => {
if (exists) {
this.executablePath = tmpExecutablePath;
}
});
}
}
}
}
}
exports.activate = context => {
let phpcbf = new PHPCBF();
context.subscriptions.push(
workspace.onWillSaveTextDocument(event => {
const editor = window.activeTextEditor;
if (
event.document.languageId == "php" &&
phpcbf.onsave &&
workspace
.getConfiguration("editor", editor.document.uri)
.get("formatOnSave") !== false
) {
event.waitUntil(
commands.executeCommand("editor.action.formatDocument")
);
}
})
);
context.subscriptions.push(
commands.registerTextEditorCommand("phpcbf-simone-baldini", textEditor => {
if (textEditor.document.languageId == "php") {
commands.executeCommand("editor.action.formatDocument");
}
})
);
context.subscriptions.push(
workspace.onDidChangeConfiguration(() => {
phpcbf.loadSettings();
})
);
if (phpcbf.documentFormattingProvider) {
context.subscriptions.push(
languages.registerDocumentFormattingEditProvider("php", {
provideDocumentFormattingEdits: (document, options, token) => {
return new Promise((resolve, reject) => {
const originalText = document.getText();
let lastLine = document.lineAt(document.lineCount - 1);
let range = new Range(
new Position(0, 0),
lastLine.range.end
);
phpcbf
.format(document)
.then(text => {
if (text != originalText) {
resolve([new vscode.TextEdit(range, text)]);
} else {
reject();
}
})
.catch(err => {
console.log(err);
reject();
});
});
}
})
);
}
};