forked from phan/phan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphan_client
executable file
·418 lines (385 loc) · 17.1 KB
/
phan_client
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#!/usr/bin/env php
<?php
/**
* Usage: phan_client -l path/to/file.php
* Compatible with php 5.6, 7.0 and php 7.1.
* (The server itself requires a newer php version)
*
* See plugins/vim/snippet.vim for an example of a use of this program.
*
* Analyzes a single php file.
* - If it is syntactically valid, scans it with phan, and emits lines beginning with "phan error:"
* - If it is invalid, emits the output of the PHP syntax checker
*
* This is meant to be a self-contained script with no file dependencies.
*
* Not tested on windows, probably won't work, but should be easy to add.
* Enhanced substitute for php -l, when phan daemon is running in the background for that folder.
*
* Note: if the daemon is run inside of Docker, one would probably need to change the URL in src/Phan/Daemon/Request.php from 127.0.0.1 to 0.0.0.0,
* and docker run -p 127.0.0.1:4846:4846 path/to/phan --daemonize-tcp-port 4846 --quick (second port is the docker one)
*
* See one of the many dockerized phan instructions, such as https://github.com/cloudflare/docker-phan
* e.g. https://github.com/cloudflare/docker-phan/blob/master/builder/scripts/mkimage-phan.bash
* mentions how it installed php-ast, similar steps could be used for other modules.
* (Install phpVERSION-dev/pecl to install extensions from source/pecl (phpize, configure, make install/pecl install))
*
* TODO: tutorial or repo.
*/
class PhanPHPLinter {
// Wait at most 3 seconds to lint a file.
const TIMEOUT_MS = 3000;
/** @var bool - Whether or not this is verbose */
public static $verbose = false;
/**
* @param string $msg
* @return void
*/
private static function debugError($msg) {
error_log($msg);
}
/**
* @param string $msg
* @return void
*/
private static function debugInfo($msg) {
if (self::$verbose) {
self::debugError($msg);
}
}
public static function run() {
error_reporting(E_ALL);
// TODO: check for .phan/lock to see if daemon is running?
$opts = new PhanPHPLinterOpts(); // parse options, exit on failure.
self::$verbose = $opts->verbose;
$failure_code = 0;
$temporary_file_mapping_contents = [];
foreach ($opts->file_list as $path) {
if (isset($opts->temporary_file_map[$path])) {
$temporary_path = $opts->temporary_file_map[$path];
$temporary_contents = file_get_contents($temporary_path);
if ($temporary_contents === false) {
self::debugError(sprintf("Could not open temporary input file: %s", $temporary_path));
$failure_code = 1;
continue;
}
system("php -l --no-php-ini " . escapeshellarg($temporary_path), $exit_code);
if ($exit_code === 0) {
$temporary_file_mapping_contents[$path] = $temporary_contents;
}
} else {
// TODO: use popen instead
// TODO: add option to capture output, suppress "No syntax error"?
// --no-php-ini is a faster way to parse since php doesn't need to load multiple extensions. Assumes none of the extensions change the way php is parsed.
system("php -l --no-php-ini " . escapeshellarg($path), $exit_code);
}
if ($exit_code !== 0) {
// The file is syntactically invalid. Or php somehow isn't able to be invoked from this script.
$failure_code = $exit_code;
}
}
// Exit if any of the requested files are syntactically invalid.
if ($failure_code !== 0) {
self::debugError("Files were syntactically invalid\n");
exit($failure_code);
}
// TODO: Check that everything in $this->file_list is in the same path.
// $path = reset($opts->file_list);
$real = realpath($path);
if (!$real) {
self::debugError("Could not resolve $path\n");
}
$dirname = dirname($real);
$old_dirname = null;
unset($real);
// TODO: In another PR, have an alternative way to run the daemon/server on Windows (Serialize and unserialize global state?
// The server side is unsupported on Windows, due to the `pcntl` extension not being supported.
$found_phan_config = false;
while ($dirname !== $old_dirname) {
if (file_exists($dirname . '/.phan/config.php')) {
$found_phan_config = true;
break;
}
$old_dirname = $dirname;
$dirname = dirname($dirname);
}
if (!$found_phan_config) {
self::debugInfo("Not in a Phan project, nothing to do.");
exit(0);
}
$file_mapping = [];
$real_files = [];
foreach ($opts->file_list as $path) {
$real = realpath($path);
if (!$real) {
self::debugInfo("could not find real path to '$path'");
continue;
}
// Convert this to a relative path
if (strncmp($dirname . '/', $real, strlen($dirname . '/')) === 0) {
$real = substr($real, strlen($dirname . '/'));
if (isset($opts->temporary_file_map[$path])) {
// If we are analyzing a temporary file, but it's within a project, then output the path to a temporary file for consistency.
// (Tools which pass something a temporary path expect a temporary path in the output.)
$file_mapping[$real] = $opts->temporary_file_map[$path];
} else {
$file_mapping[$real] = $path;
}
$real_files[] = $real;
} else {
self::debugInfo("Not in a Phan project, nothing to do.");
}
}
if (count($file_mapping) == 0) {
self::debugInfo("Not in a real project");
}
// The file is syntactically valid. Run phan.
// TODO: Make TCP port configurable
// TODO: check if the folder is within a folder with subdirectory .phan/config.php
// TODO: Check if there is a lock before attempting to connect?
$client = @stream_socket_client($opts->url, $errno, $errstr, 20.0);
if (!is_resource($client)) {
// TODO: This should attempt to start up the phan daemon for the given folder?
self::debugError("Phan daemon not running on port 4846");
exit(0);
}
$request = [
'method' => 'analyze_files',
'files' => $real_files,
'format' => 'json',
];
if (count($temporary_file_mapping_contents) > 0) {
$request['temporary_file_mapping_contents'] = $temporary_file_mapping_contents;
}
// This used to use the 'phplike' format, but it doesn't work well with filtering files.
fwrite($client, json_encode($request));
stream_set_timeout($client, (int)floor(self::TIMEOUT_MS / 1000), 1000 * (self::TIMEOUT_MS % 1000));
stream_socket_shutdown($client, STREAM_SHUT_WR);
$response_lines = [];
while (!feof($client)) {
$response_lines[] = fgets($client);
}
stream_socket_shutdown($client, STREAM_SHUT_RD);
fclose($client);
$client = null;
$response_bytes = implode('', $response_lines);
// This uses the 'phplike' format imitating php's error format. "%s in %s on line %d"
$response = json_decode($response_bytes, true);
$status = isset($response['status']) ? $response['status'] : null;
if ($status === 'ok') {
self::dumpJSONIssues($response, $file_mapping);
} else {
self::debugError(sprintf("Invalid response from phan for url %s, files %s: %s\n", $opts->url, json_encode($file_mapping), $response_bytes));
}
}
/**
* @param array[] $response
* @param string[] $file_mapping
* @return void
*/
private static function dumpJSONIssues(array $response, array $file_mapping) {
$did_debug = false;
// if ($response['issue_count'] > 0)
$issues = $response['issues'];
if (!is_array($issues)) {
if (is_string($issues)) {
self::debugError(sprintf("Invalid issues response from phan: %s\n", $issues));
} else {
self::debugError(sprintf("Invalid type for issues response from phan: %s\n", gettype($issues)));
}
return;
}
foreach ($issues as $issue) {
if ($issue['type'] !== 'issue') {
continue;
}
$pathInProject = $issue['location']['path']; // relative path
if (!isset($file_mapping[$pathInProject])) {
if (!$did_debug) {
self::debugInfo(sprintf("Unexpected path for issue (expected %s): %s\n", json_encode($file_mapping), json_encode($issue)));
}
$did_debug = true;
continue;
}
$line = $issue['location']['lines']['begin'];
$description = $issue['description'];
$parts = explode(' ', $description, 3);
if (count($parts) === 3 && $parts[1] === $issue['check_name']) {
$description = implode(': ', $parts);
}
printf("Phan error: %s in %s on line %d\n", $description, $file_mapping[$pathInProject], $line);
}
}
}
class PhanPHPLinterOpts {
/** @var string tcp:// or unix:// socket URL of the daemon. */
public $url;
/** @var string[] - file list */
public $file_list = [];
/** @var string[]|null - optional, maps original files to temporary file path to use as a substitute. */
public $temporary_file_map = null;
/** @var bool - unused. */
public $verbose = false;
/**
* @param string $msg - optional message
* @param int $exit_code - process exit code.
* @return void - exits with $exit_code
*/
public function usage($msg = '', $exit_code = 0) {
global $argv;
if (!empty($msg)) {
echo "$msg\n";
}
// TODO: Add an option to autostart the daemon if user also has global configuration to allow it for a given project folder. ($HOME/.phanconfig)
// TODO: Allow changing (adding/removing) issue suppression types for the analysis phase (would not affect the parse phase)
echo <<<EOB
Usage: {$argv[0]} [options] -l file.php [ -l file2.php]
--daemonize-socket </path/to/file.sock>
Unix socket which a Phan daemon is listening for requests on.
--daemonize-tcp-port <1024-65535>
TCP port which a Phan daemon is listening for JSON requests on, in daemon mode. (E.g. 4846)
-l, --syntax-check <file.php>
Syntax check, and if the Phan daemon is running, analyze the following file (absolute path or relative to current working ditectory)
This will only analyze the file if a full phan check (with .phan/config.php) would analyze the file.
-t, --temporary-file-map '{"file.php":"/path/to/tmp/file_copy.php"}'
A json mapping from original path to absolute temporary path (E.g. of a file that is still being edited)
-f, --flycheck-file '/path/to/tmp/file_copy.php'
A simpler way to specify a file mapping when checking a single files.
Pass this after the only occurence of --syntax-check.
-v, --verbose
Whether to emit debugging output of this client.
-h,--help
This help information
EOB;
exit($exit_code);
}
public function __construct() {
global $argv;
// Parse command line args
$optind = 0;
$shortopts = "s:p:l:t:f:v";
$longopts = [
'daemonize-socket:',
'daemonize-tcp-port:',
'syntax-check:',
'temporary-file-map:',
'flycheck-file:',
'verbose',
];
if (PHP_VERSION_ID >= 70100) {
// optind support is only in php 7.1+.
$opts = getopt($shortopts, $longopts, $optind);
} else {
$opts = getopt($shortopts, $longopts);
}
if (PHP_VERSION_ID >= 70100 && $optind < count($argv)) {
$this->usage(sprintf("Unexpected parameter %s", json_encode($argv[$optind])));
}
// Check for this first, since the option parser may also emit debug output in the future.
if (in_array('-v', $argv) || in_array('--verbose', $argv)) {
PhanPHPLinter::$verbose = true;
$this->verbose = true;
}
$url = null;
foreach ((is_array($opts) ? $opts : []) as $key => $value) {
switch($key) {
case 's':
case 'daemonize-socket':
$this->checkCanConnectToDaemon('unix');
if ($this->url !== null) {
$this->usage('Can specify --daemonize-socket or --daemonize-tcp-port only once', 1);
}
// Check if the socket is valid after parsing the file list.
$socket_dirname = realpath(dirname($value));
if (!file_exists($socket_dirname) || !is_dir($socket_dirname)) {
// The client doesn't require that the file exists if the daemon isn't running, but we do require that the folder exists.
$msg = sprintf('Configured to connect to unix socket server at socket %s, but folder %s does not exist', json_encode($value), json_encode($socket_dirname));
$this->usage($msg, 1);
} else {
$this->url = sprintf('unix://%s/%s', $socket_dirname, basename($value));
}
break;
case 'f':
case 'flycheck-file':
// Add alias, for use in flycheck
if (is_array($this->temporary_file_map)) {
$this->usage('--flycheck-file should be specified only once.', 1);
}
if (!is_array($this->file_list) || count($this->file_list) !== 1) {
$this->usage('--flycheck-file should be specified after the first occurrence of -l.', 1);
}
$this->temporary_file_map = [
$this->file_list[0] => $value,
];
break;
case 't':
case 'temporary-file-map':
if (is_array($this->temporary_file_map)) {
$this->usage('--temporary-file-map should be specified only once.', 1);
}
$mapping = json_decode($value, true);
if (!is_array($mapping)) {
$this->usage('--temporary-file-map should be a JSON encoded map from source file to temporary file to analyze instead', 1);
}
$this->temporary_file_map = $mapping;
break;
case 'p':
case 'daemonize-tcp-port':
$this->checkCanConnectToDaemon('tcp');
$port = filter_var($value, FILTER_VALIDATE_INT);
if ($port >= 1024 && $port <= 65535) {
$this->url = sprintf('tcp://127.0.0.1:%d', $port);
} else {
$this->usage("daemonize-tcp-port must be between 1024 and 65535, got '$value'", 1);
}
break;
case 'l':
case 'syntax-check':
$path = $value;
if (!file_exists($path)) {
$this->usage(sprintf("Error: asked to analyze file %s which does not exist", json_encode($path)), 1);
exit(1);
}
$this->file_list[] = $path;
break;
case 'h':
case 'help':
$this->usage();
break;
case 'v':
case 'verbose':
break; // already parsed.
default:
$this->usage("Unknown option '-$key'", 1);
break;
}
}
if (count($this->file_list) === 0) {
$this->usage("This requires at least one file to analyze (with -l path/to/file", 1);
}
if (is_array($this->temporary_file_map)) {
foreach ($this->temporary_file_map as $original_path => $temporary_path) {
if (!in_array($original_path, $this->file_list)) {
$this->usage("Need to specify -l '$original_path' if a mapping is included", 1);
}
}
}
if ($this->url === null) {
$this->url = 'tcp://127.0.0.1:4846';
}
}
/**
* prints error message if php doesn't support connecting to a daemon with a given protocol.
* @return void
*/
private function checkCanConnectToDaemon($protocol) {
$opt = $protocol === 'unix' ? '--daemonize-socket' : '--daemonize-tcp-port';
if (!in_array($protocol, stream_get_transports())) {
$this->usage("The $protocol:///path/to/file schema is not supported on this system, cannot connect to a daemon with $opt", 1);
}
if ($this->url !== null) {
$this->usage('Can specify --daemonize-socket or --daemonize-tcp-port only once', 1);
}
}
}
PhanPHPLinter::run();