This repository has been archived by the owner on Sep 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
247 lines (195 loc) · 6.66 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
const vscode = require('vscode');
const path = require('path');
const fs = require('fs');
const tmp = require('tmp');
const cp = require('child_process');
const { config } = require('process');
let logMessages = [];
const output = vscode.window.createOutputChannel('PHP-CS-Fixer-Reloaded');
log('PhpCsFixer extension started');
function log(msg) {
logMessages.push(msg);
}
function dumpLog() {
// output.show();
logMessages.forEach(msg => output.appendLine(msg));
logMessages = [];
}
function formatDocument(document) {
if (document.languageId !== 'php') {
return;
}
const filename = document.fileName;
const opts = { cwd: path.dirname(filename) };
// find a php-cs-fixer binary closest to the processed file
// and falback to the one provided with the extension
// if not found any
const toolPath = getToolPath(opts.cwd);
log('php-cs-fixer: ' + toolPath);
// allow to have multiple config files separated by comma:
// php-cs-fixer.php,php_cs.dist
// which allows to use different file names per project (legacy dependency)
const configFile = getConfigFile(opts.cwd);
log('config: ' + configFile);
// create a temp file
const tmpFile = tmp.fileSync();
const originalText = document.getText(null);
fs.writeFileSync(tmpFile.name, originalText);
const args = makeArgs(toolPath, configFile, tmpFile.name);
return new Promise(function (resolve) {
log('execute: php ' + args.join(' '));
cp.execFile('php', args, opts, function (err, stdout, stderr) {
if (null !== err) {
log("\nPHPCsFixer error");
log(JSON.stringify(err));
log(stdout);
log(stderr);
dumpLog();
tmpFile.removeCallback();
vscode.window.showErrorMessage('There was an error while running php-cs-fixer. Please check the console output for more info');
resolve(originalText);
return;
}
log(stdout);
log("php-cs-fixer done");
dumpLog();
vscode.window.showTextDocument(vscode.window.activeTextEditor.document)
const text = fs.readFileSync(tmpFile.name, 'utf-8');
tmpFile.removeCallback();
resolve(text);
});
});
}
function makeArgs(toolPath, configPath, filePath) {
let args = [];
args.push(toolPath);
args.push('fix');
if (!getConfig('useCache')) {
args.push('--using-cache=no');
}
if (getConfig('allowRisky')) {
args.push('--allow-risky=yes');
}
if (getConfig('intersection')) {
args.push('--path-mode=intersection');
}
if (configPath) {
args.push('--config=' + configPath);
}
if (!configPath) {
// log("config file not found. adding rules")
let rules = getConfig('rules');
if (rules) {
args.push('--rules=' + rules);
}
}
args.push(filePath);
return args;
}
function getConfigFile(basePath) {
let fileNames = getConfig('config').split(',');
let configFile;
try {
configFile = getFilePath(fileNames, basePath);
} catch (e) {
vscode.window.showErrorMessage(e);
}
return configFile;
}
function getToolPath(basePath) {
const defaultPath = vscode.extensions.getExtension('danielzzz.vscode-php-cs-fixer-reloaded').extensionPath + '/php-cs-fixer';
let pathConfig = getConfig('toolPath');
if (!pathConfig) {
return defaultPath;
}
let toolPaths = pathConfig.split(',');
let toolPath = getFilePath(toolPaths, basePath);
if (!toolPath) {
return defaultPath;
}
return toolPath;
}
function absoluteExists(filePath) {
return path.isAbsolute(filePath) && fs.existsSync(filePath);
}
/**
* finds if any of filenames exists in basePath and parent directories
* and returns the path
* @param {array} fileNames
* @param {string} basePath
* @returns string | undefined
*/
function getFilePath(fileNames, basePath) {
if (fileNames.length === 0) {
return undefined;
}
let currentPath;
let currentFile;
let triedPaths;
let foundPath;
for (let i = 0; i < fileNames.length; i++) {
currentFile = fileNames[i];
// log(currentFile);
if (absoluteExists(currentFile)) {
// log('found absolute');
return currentFile;
}
currentPath = basePath;
triedPaths = [currentPath];
while (!fs.existsSync(currentPath + path.sep + currentFile)) {
let lastPath = currentPath;
currentPath = path.resolve(currentPath, '..');
// log(currentPath);
// log(lastPath + ":" + currentPath);
if (lastPath === currentPath) {
// log('not found');
break;
} else {
triedPaths.push(currentPath);
}
}
foundPath = currentPath + path.sep + currentFile;
// log(foundPath);
if (fs.existsSync(foundPath)) {
// log('really found ' + foundPath);
return foundPath;
}
};
return undefined;
}
function registerDocumentProvider(document, options) {
return new Promise(function (resolve, reject) {
formatDocument(document).then(function (text) {
const range = new vscode.Range(new vscode.Position(0, 0), document.lineAt(document.lineCount - 1).range.end);
resolve([new vscode.TextEdit(range, text)]);
}).catch(function (err) {
reject();
});
});
}
function getConfig(key) {
try {
return vscode.workspace.getConfiguration('vscode-php-cs-fixer-reloaded').get(key);
} catch (e) {
return undefined;
}
}
function activate(context) {
context.subscriptions.push(vscode.commands.registerTextEditorCommand('vscode-php-cs-fixer-reloaded.fix', function (textEditor) {
vscode.commands.executeCommand('editor.action.formatDocument');
}));
context.subscriptions.push(vscode.workspace.onWillSaveTextDocument(function (event) {
if (event.document.languageId === 'php' && getConfig('fixOnSave') && vscode.workspace.getConfiguration('editor', null).get('formatOnSave') == false) {
event.waitUntil(vscode.commands.executeCommand('editor.action.formatDocument'));
}
}));
context.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider('php', {
provideDocumentFormattingEdits: function (document, options) {
return registerDocumentProvider(document, options);
}
}));
}
exports.activate = activate;
function deactivate() {
}
exports.deactivate = deactivate;