1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-13 17:57:37 +01:00
psalm/src/psalm.php

481 lines
13 KiB
PHP
Raw Normal View History

2016-07-26 21:12:44 +02:00
<?php
require_once('command_functions.php');
2016-07-26 21:12:44 +02:00
2017-10-07 20:41:16 +02:00
use Psalm\Checker\ProjectChecker;
use Psalm\Config;
use Psalm\IssueBuffer;
2017-10-07 20:41:16 +02:00
2016-07-26 21:12:44 +02:00
// show all errors
2016-10-30 17:46:18 +01:00
error_reporting(-1);
2016-07-26 21:12:44 +02:00
$valid_short_options = [
'f:',
'm',
'h',
'v',
'c:',
'i',
'r:',
];
$valid_long_options = [
'clear-cache',
2018-10-15 17:29:57 +02:00
'clear-global-cache',
'config:',
'debug',
'debug-by-line',
'diff',
'disable-extension:',
'find-dead-code',
'find-references-to:',
'help',
'init',
'monochrome',
'no-cache',
'output-format:',
'plugin:',
'report:',
'root:',
'show-info:',
'show-snippet:',
'stats',
'threads:',
'use-ini-defaults',
'version',
'diff-methods',
];
$args = array_slice($argv, 1);
array_map(
/**
* @param string $arg
*
* @return void
*/
function ($arg) use ($valid_long_options, $valid_short_options) {
if (substr($arg, 0, 2) === '--' && $arg !== '--') {
$arg_name = preg_replace('/=.*$/', '', substr($arg, 2));
if (!in_array($arg_name, $valid_long_options) && !in_array($arg_name . ':', $valid_long_options)) {
echo 'Unrecognised argument "--' . $arg_name . '"' . PHP_EOL
. 'Type --help to see a list of supported arguments'. PHP_EOL;
exit(1);
}
} elseif (substr($arg, 0, 2) === '-' && $arg !== '-' && $arg !== '--') {
$arg_name = preg_replace('/=.*$/', '', substr($arg, 1));
if (!in_array($arg_name, $valid_short_options) && !in_array($arg_name . ':', $valid_short_options)) {
echo 'Unrecognised argument "-' . $arg_name . '"' . PHP_EOL
. 'Type --help to see a list of supported arguments'. PHP_EOL;
exit(1);
}
}
},
$args
2016-12-08 04:38:57 +01:00
);
// get options from command line
$options = getopt(implode('', $valid_short_options), $valid_long_options);
if (!array_key_exists('use-ini-defaults', $options)) {
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
ini_set('memory_limit', (string) (4 * 1024 * 1024 * 1024));
}
if (array_key_exists('help', $options)) {
2016-11-05 03:55:13 +01:00
$options['h'] = false;
}
if (array_key_exists('version', $options)) {
$options['v'] = false;
}
2017-02-13 05:59:33 +01:00
if (array_key_exists('init', $options)) {
$options['i'] = false;
}
if (array_key_exists('monochrome', $options)) {
2016-11-05 03:55:13 +01:00
$options['m'] = false;
}
if (isset($options['config'])) {
2016-11-05 03:55:13 +01:00
$options['c'] = $options['config'];
}
2017-01-17 01:44:31 +01:00
if (isset($options['c']) && is_array($options['c'])) {
echo 'Too many config files provided' . PHP_EOL;
exit(1);
2017-01-17 01:44:31 +01:00
}
if (array_key_exists('h', $options)) {
echo <<<HELP
Usage:
2016-11-05 03:55:13 +01:00
psalm [options] [file...]
Options:
2017-02-13 05:59:33 +01:00
-h, --help
Display this help message
-v, --version
Display the Psalm version
-i, --init [source_dir=src] [level=3]
2017-02-13 05:59:33 +01:00
Create a psalm config file in the current directory that points to [source_dir]
at the required level, from 1, most strict, to 8, most permissive.
2017-02-13 05:59:33 +01:00
--debug
Debug information
2018-03-26 15:08:55 +02:00
--debug-by-line
Debug information on a line-by-line level
2017-02-13 05:59:33 +01:00
-c, --config=psalm.xml
Path to a psalm.xml configuration file. Run psalm --init to create one.
-m, --monochrome
Enable monochrome output
-r, --root
If running Psalm globally you'll need to specify a project root. Defaults to cwd
2017-02-13 05:59:33 +01:00
--show-info[=BOOLEAN]
Show non-exception parser findings
2018-06-04 16:19:20 +02:00
--show-snippet[=true]
Show code snippets with errors. Options are 'true' or 'false'
2017-02-13 05:59:33 +01:00
--diff
Runs Psalm in diff mode, only checking files that have changed (and their dependents)
--diff-methods
Only checks methods that have changed (and their dependents)
2017-02-13 05:59:33 +01:00
--output-format=console
Changes the output format. Possible values: console, emacs, json, pylint, xml
2017-02-13 05:59:33 +01:00
--find-dead-code
Look for dead code
--find-references-to=[class|method]
Searches the codebase for references to the given fully-qualified class or method,
where method is in the format class::methodName
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
--threads=INT
If greater than one, Psalm will run analysis on multiple threads, speeding things up.
--report=PATH
The path where to output report file. The output format is base on the file extension.
(Currently supported format: ".json", ".xml", ".txt")
2017-10-07 20:41:16 +02:00
--clear-cache
2018-10-15 17:29:57 +02:00
Clears all cache files that Psalm uses for this specific project
--clear-global-cache
Clears all cache files that Psalm uses for all projects
2017-10-07 20:41:16 +02:00
2017-10-14 03:27:20 +02:00
--no-cache
Runs Psalm without using cache
--plugin=PATH
Executes a plugin, an alternative to using the Psalm config
2018-01-31 23:09:09 +01:00
--stats
Shows a breakdown of Psalm's ability to infer types in the codebase
--use-ini-defaults
Use PHP-provided ini defaults for memory and error display
2018-07-17 22:54:34 +02:00
--disable-extension=[extension]
Used to disable certain extensions while Psalm is running.
HELP;
exit;
}
2016-07-26 21:12:44 +02:00
if (getcwd() === false) {
echo 'Cannot get current working directory' . PHP_EOL;
exit(1);
}
if (isset($options['root'])) {
$options['r'] = $options['root'];
}
$current_dir = (string)getcwd() . DIRECTORY_SEPARATOR;
if (isset($options['r']) && is_string($options['r'])) {
$root_path = realpath($options['r']);
if (!$root_path) {
echo 'Could not locate root directory ' . $current_dir . DIRECTORY_SEPARATOR . $options['r'] . PHP_EOL;
exit(1);
}
$current_dir = $root_path . DIRECTORY_SEPARATOR;
}
$vendor_dir = getVendorDir($current_dir);
$first_autoloader = requireAutoloaders($current_dir, isset($options['r']), $vendor_dir);
if (array_key_exists('v', $options)) {
echo 'Psalm ' . PSALM_VERSION . PHP_EOL;
exit;
}
$threads = isset($options['threads']) ? (int)$options['threads'] : 1;
$ini_handler = new \Psalm\Fork\PsalmRestarter('PSALM');
2018-07-17 22:54:34 +02:00
if (isset($options['disable-extension'])) {
if (is_array($options['disable-extension'])) {
/** @psalm-suppress MixedAssignment */
2018-07-17 22:54:34 +02:00
foreach ($options['disable-extension'] as $extension) {
if (is_string($extension)) {
$ini_handler->disableExtension($extension);
}
}
} elseif (is_string($options['disable-extension'])) {
$ini_handler->disableExtension($options['disable-extension']);
}
}
if ($threads > 1) {
$ini_handler->disableExtension('grpc');
}
2017-10-07 20:41:16 +02:00
// If XDebug is enabled, restart without it
$ini_handler->check();
2017-10-07 20:41:16 +02:00
2018-02-18 04:11:42 +01:00
setlocale(LC_CTYPE, 'C');
2017-02-13 05:59:33 +01:00
if (isset($options['i'])) {
if (file_exists($current_dir . 'psalm.xml')) {
2017-02-13 05:59:33 +01:00
die('A config file already exists in the current directory' . PHP_EOL);
}
$args = array_values(array_filter(
$args,
/**
* @param string $arg
*
* @return bool
*/
function ($arg) {
return $arg !== '--ansi'
&& $arg !== '--no-ansi'
&& $arg !== '-i'
&& $arg !== '--init'
&& strpos($arg, '--root=') !== 0
&& strpos($arg, '--r=') !== 0;
}
));
2017-02-13 05:59:33 +01:00
$level = 3;
$source_dir = 'src';
if (count($args)) {
if (count($args) > 2) {
die('Too many arguments provided for psalm --init' . PHP_EOL);
}
if (isset($args[1])) {
if (!preg_match('/^[1-8]$/', $args[1])) {
die('Config strictness must be a number between 1 and 8 inclusive' . PHP_EOL);
2017-02-13 05:59:33 +01:00
}
$level = (int)$args[1];
}
2017-02-13 06:12:56 +01:00
$source_dir = $args[0];
}
if (!is_dir($source_dir)) {
$bad_dir_path = getcwd() . DIRECTORY_SEPARATOR . $source_dir;
if (!isset($args[0])) {
die('Please specify a directory - the default, "src", was not found in this project.' . PHP_EOL);
2017-02-13 05:59:33 +01:00
}
2017-02-13 06:12:56 +01:00
die('The given path "' . $bad_dir_path . '" does not appear to be a directory' . PHP_EOL);
2017-02-13 05:59:33 +01:00
}
2017-05-28 06:07:26 +02:00
$template_file_name = dirname(__DIR__) . '/assets/config_levels/' . $level . '.xml';
2017-02-13 05:59:33 +01:00
if (!file_exists($template_file_name)) {
2017-05-28 06:07:26 +02:00
die('Could not open config template ' . $template_file_name . PHP_EOL);
2017-02-13 05:59:33 +01:00
}
$template = (string)file_get_contents($template_file_name);
$template = str_replace(
'<directory name="src" />',
'<directory name="' . $source_dir . '" />',
$template
);
2017-02-13 05:59:33 +01:00
if (!\Phar::running(false)) {
$template = str_replace(
'vendor/vimeo/psalm/config.xsd',
2018-04-22 00:50:58 +02:00
'file://' . realpath(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config.xsd'),
$template
);
}
if (!file_put_contents($current_dir . 'psalm.xml', $template)) {
2017-02-13 05:59:33 +01:00
die('Could not write to psalm.xml' . PHP_EOL);
}
exit('Config file created successfully. Please re-run psalm.' . PHP_EOL);
}
$output_format = isset($options['output-format']) && is_string($options['output-format'])
? $options['output-format']
: ProjectChecker::TYPE_CONSOLE;
2016-12-08 04:38:57 +01:00
$paths_to_check = getPathsToCheck(isset($options['f']) ? $options['f'] : null);
$plugins = [];
if (isset($options['plugin'])) {
$plugins = $options['plugin'];
if (!is_array($plugins)) {
$plugins = [$plugins];
}
}
$path_to_config = isset($options['c']) && is_string($options['c']) ? realpath($options['c']) : null;
2016-11-05 03:55:13 +01:00
if ($path_to_config === false) {
/** @psalm-suppress InvalidCast */
echo 'Could not resolve path to config ' . (string)$options['c'] . PHP_EOL;
exit(1);
}
$show_info = isset($options['show-info'])
? $options['show-info'] !== 'false' && $options['show-info'] !== '0'
: true;
2016-11-05 03:55:13 +01:00
2016-10-07 06:58:08 +02:00
$is_diff = isset($options['diff']);
2016-07-26 21:12:44 +02:00
$find_dead_code = isset($options['find-dead-code']);
$find_references_to = isset($options['find-references-to']) && is_string($options['find-references-to'])
? $options['find-references-to']
: null;
// initialise custom config, if passed
2018-04-19 23:29:07 +02:00
try {
if ($path_to_config) {
$config = Config::loadFromXMLFile($path_to_config, $current_dir);
} else {
$config = Config::getConfigForPath($current_dir, $current_dir, $output_format);
}
} catch (Psalm\Exception\ConfigException $e) {
echo $e->getMessage();
exit(1);
}
$config->setComposerClassLoader($first_autoloader);
2018-02-08 02:15:56 +01:00
if (isset($options['clear-cache'])) {
$cache_directory = $config->getCacheDirectory();
Config::removeCacheDirectory($cache_directory);
echo 'Cache directory deleted' . PHP_EOL;
exit;
}
2018-10-15 17:29:57 +02:00
if (isset($options['clear-global-cache'])) {
$cache_directory = $config->getGlobalCacheDirectory();
Config::removeCacheDirectory($cache_directory);
echo 'Global cache directory deleted' . PHP_EOL;
exit;
}
$debug = array_key_exists('debug', $options) || array_key_exists('debug-by-line', $options);
if (isset($options['no-cache'])) {
$providers = new Psalm\Provider\Providers(
new Psalm\Provider\FileProvider
);
} else {
$providers = new Psalm\Provider\Providers(
new Psalm\Provider\FileProvider,
new Psalm\Provider\ParserCacheProvider($config),
new Psalm\Provider\FileStorageCacheProvider($config),
new Psalm\Provider\ClassLikeStorageCacheProvider($config),
new Psalm\Provider\FileReferenceCacheProvider($config)
);
}
$project_checker = new ProjectChecker(
$config,
$providers,
!array_key_exists('m', $options),
$show_info,
$output_format,
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$threads,
$debug,
2018-06-04 16:19:20 +02:00
isset($options['report']) && is_string($options['report']) ? $options['report'] : null,
!isset($options['show-snippet']) || $options['show-snippet'] !== "false"
);
2017-01-16 17:05:29 +01:00
$project_checker->diff_methods = isset($options['diff-methods']);
2018-10-10 22:05:06 +02:00
$start_time = microtime(true);
$config->visitComposerAutoloadFiles($project_checker, $debug);
2018-10-10 22:05:06 +02:00
$now_time = microtime(true);
if ($debug) {
echo 'Visiting autoload files took ' . number_format($now_time - $start_time, 3) . 's' . "\n";
}
2018-03-26 15:08:55 +02:00
if (array_key_exists('debug-by-line', $options)) {
$project_checker->debug_lines = true;
}
2018-02-04 00:52:35 +01:00
if ($find_dead_code || $find_references_to !== null) {
$project_checker->getCodebase()->collectReferences();
if ($find_references_to) {
$project_checker->show_issues = false;
}
2018-02-04 00:52:35 +01:00
}
if ($find_dead_code) {
$project_checker->getCodebase()->reportUnusedCode();
}
/** @var string $plugin_path */
foreach ($plugins as $plugin_path) {
Config::getInstance()->addPluginPath($current_dir . DIRECTORY_SEPARATOR . $plugin_path);
}
if ($paths_to_check === null) {
$project_checker->check($current_dir, $is_diff);
} elseif ($paths_to_check) {
$project_checker->checkPaths($paths_to_check);
2016-07-26 21:12:44 +02:00
}
2018-01-22 05:42:57 +01:00
if ($find_references_to) {
$project_checker->findReferencesTo($find_references_to);
} elseif ($find_dead_code && !$paths_to_check && !$is_diff) {
if ($threads > 1) {
if ($output_format === ProjectChecker::TYPE_CONSOLE) {
echo 'Unused classes and methods cannot currently be found in multithreaded mode' . PHP_EOL;
}
} else {
$project_checker->checkClassReferences();
}
2018-01-22 05:42:57 +01:00
}
2018-02-20 05:36:29 +01:00
IssueBuffer::finish($project_checker, !$paths_to_check, $start_time, isset($options['stats']));