forked from soderlind/vscode-phpcbf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhpcbf.js
More file actions
308 lines (272 loc) · 7.37 KB
/
Phpcbf.js
File metadata and controls
308 lines (272 loc) · 7.37 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
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
const path = require('path')
const fs = require('fs')
const os = require('os')
const cp = require('child_process')
const TmpDir = os.tmpdir()
const {
PHPCBF_CONFIG_FILENAMES,
PHPCBF_ERRORS,
PHPCBF_NO_FIXABLE_ERRORS
} = require('./config')
// Errors
const {
ERR_ON_CREATING_TEMP_FILE,
ERR_ON_DELETING_TEMP_FILE,
ERR_PHPCBF_EXIT_CODE_3,
ERR_PHPCBF_EXIT_CODE_16,
ERR_PHPCBF_EXIT_CODE_32,
ERR_PHPCBF_EXIT_CODE_64,
ERR_PHPCBF_EXIT_CODE_UNDEFINED,
ERR_PHPCBF_ENOENT,
ERR_PHPCBF_BIN_ENOENT,
ERR_PHPCBF_INVALID_WORKSPACE
} = PHPCBF_ERRORS
/**
* PHPCBF Class
* */
class PHPCBF {
constructor (options = {}) {
const fakeCallBack = () => true
this.onError = options.onError || fakeCallBack
this.onDebug = options.onDebug || fakeCallBack
this.setOptions(options)
}
/**
* Resolve executable path
*
* @param {string} path
* @returns {string}
* */
resolveExecutablePath (options) {
let path = options.executablePath
if (path === 'phpcbf') {
//TODO !Find a way to resolve global binary
}
if (path.startsWith('{{workspaceFolder}}')) {
path = path.replace(/{{workspaceFolder}}/, options.workspace)
} else if (path.startsWith('./')) {
path = path.replace(/\./, options.workspace)
if (!options.workspace) {
this.onDebug(ERR_PHPCBF_INVALID_WORKSPACE)
path = 'phpcbf'
}
} else if (path.startsWith('~')) {
path = path.replace(/^~\//, os.homedir() + '/')
if (!options.workspace) {
this.onDebug(ERR_PHPCBF_INVALID_WORKSPACE)
path = 'phpcbf'
}
}
if (path !== 'phpcbf') {
try {
fs.statSync(path)
} catch (e) {
this.onError(ERR_PHPCBF_BIN_ENOENT + ': ' + path)
throw new Error(ERR_PHPCBF_BIN_ENOENT)
}
}
return path
}
/**
* Set options to use
*
* @param {object} options
* */
setOptions (options = {}) {
this.enable = options.enable
this.configFilenames = options.config_filenames || PHPCBF_CONFIG_FILENAMES
this.onsave = options.onsave
this.executablePath = this.resolveExecutablePath(options)
this.configSearch = options.configSearch
this.standard = options.standard
this.documentFormattingProvider = options.documentFormattingProvider
this.debug = options.debug
this.workspace = options.workspace
}
/**
* Get options in use
*
* @returns {object} options
* */
getOptions () {
return {
enable: this.enable,
configFilenames: this.configFilenames,
onsave: this.onsave,
executablePath: this.executablePath,
configSearch: this.configSearch,
standard: this.standard,
documentFormattingProvider: this.documentFormattingProvider,
debug: this.debug,
workspace: this.workspace
}
}
/**
* Concatenate arguments to use
* for execute phpcbf binary
*
* @param {string} fileName
* @returns {Array <string>}
* */
concatExecutableArguments (fileName) {
return [
this.debug ? '-l' : '-lq',
fileName,
this.standard ? `--standard=${this.standard}` : ''
]
}
/**
* Set standard
*
* @param {string} documentURI The current file
* */
setStandard (documentURI) {
if (!documentURI || !this.configSearch) {
return
}
// If configSearch attribute is set to true,
// standard used by phpcbf will be replaced by custom config file
// found
const configFile = this.searchConfigFiles(documentURI)
if (configFile) {
this.standard = configFile
}
}
/**
* Search for custom fixers files.
* This method start scanning from the current file folder to root folder
* If an allowed configuration file is found, it return the configuration file
* path
*
* @param {string} documentURI The current file
* @returns {string} the configuration file path
* */
searchConfigFiles (documentURI) {
const folders = documentURI.split(path.sep)
// Remove latest element because
// the file is not a folder
folders.pop()
while (folders.length) {
const currentFolder = folders.join(path.sep)
// Remove latest element
folders.pop()
// if current folder is empty skip it
if (!currentFolder) {
continue
}
let matchs = []
try {
matchs = fs.readdirSync(currentFolder).filter(a => {
return this.configFilenames.indexOf(a) >= 0
})
} catch (e) {
this.onError(`${currentFolder} - ${e.message}`)
continue
}
if (matchs.length > 0) {
return path.join(currentFolder, matchs[0])
}
}
return ''
}
/**
* Create temp file
*
* @param {string} content
* @returns {string} the output file path
* */
createTempFile (content = '') {
const randomHash = Math.random()
.toString(36)
.replace(/[^a-z]+/g, '')
.substr(0, 10)
const fileName = `${TmpDir}/temp-${randomHash}.php`
try {
fs.writeFileSync(fileName, content)
} catch (e) {
throw new Error(ERR_ON_CREATING_TEMP_FILE)
}
return fileName
}
/**
* Execute the fix command
*
* @param {Array <string>} execArguments The argumnets uto use with the command
* @returns {Promise <number>} The output code
* */
executeFormat (execArguments) {
// In debug mode print the command
if (this.debug) {
this.onDebug(`${this.executablePath} ${execArguments}`)
}
// Spawn PHPCBF instance
const exec = cp.spawn(this.executablePath, execArguments)
// Exec process handler
const promise = new Promise((resolve, reject) => {
exec.on('error', err => {
return reject(err.code === 'ENOENT' ? ERR_PHPCBF_ENOENT : err)
})
exec.on('exit', code => {
switch (code) {
// code 0 means no fixes found
// Code 1 and 2 means some fix are applied
case PHPCBF_NO_FIXABLE_ERRORS:
case 1:
case 2:
return resolve(code)
case 3:
return reject(ERR_PHPCBF_EXIT_CODE_3)
case 16:
return reject(ERR_PHPCBF_EXIT_CODE_16)
case 32:
return reject(ERR_PHPCBF_EXIT_CODE_32)
case 64:
return reject(ERR_PHPCBF_EXIT_CODE_64)
default:
return reject(ERR_PHPCBF_EXIT_CODE_UNDEFINED)
}
})
})
if (this.debug) {
exec.stdout.on('data', buffer => {
this.onDebug(`[stdout] ${buffer.toString()}`)
})
exec.stderr.on('data', buffer => {
this.onError(`[stderr] ${buffer.toString()}`)
})
}
return promise
}
/**
* Format the document
*
* @param {string} text
* @returns {Promise <string>}
* */
async format (text) {
// Save content of the document
// into a temp file. Then phpcbf
// will work on this file
const fileName = this.createTempFile(text)
// Get executable arguments
const execArguments = this.concatExecutableArguments(fileName)
let outputText = ''
try {
const code = await this.executeFormat(execArguments)
if (code > PHPCBF_NO_FIXABLE_ERRORS) {
outputText = fs.readFileSync(fileName, 'utf-8')
}
} catch (e) {
throw new Error(e.message)
} finally {
// Remove temp file
fs.unlink(fileName, function (err) {
if (err) {
throw new Error(ERR_ON_DELETING_TEMP_FILE)
}
})
}
return outputText
}
}
module.exports = PHPCBF