forked from vimeo/psalm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPsalm.php
1530 lines (1278 loc) · 50.9 KB
/
Psalm.php
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Psalm\Internal\Cli;
use Composer\Autoload\ClassLoader;
use Fidry\CpuCoreCounter\CpuCoreCounter;
use Psalm\Config;
use Psalm\Config\Creator;
use Psalm\ErrorBaseline;
use Psalm\Exception\ConfigCreationException;
use Psalm\Exception\ConfigException;
use Psalm\Internal\Analyzer\ProjectAnalyzer;
use Psalm\Internal\CliUtils;
use Psalm\Internal\Codebase\InternalCallMapHandler;
use Psalm\Internal\Codebase\ReferenceMapGenerator;
use Psalm\Internal\Composer;
use Psalm\Internal\ErrorHandler;
use Psalm\Internal\Fork\PsalmRestarter;
use Psalm\Internal\IncludeCollector;
use Psalm\Internal\Preloader;
use Psalm\Internal\Provider\ClassLikeStorageCacheProvider;
use Psalm\Internal\Provider\FileProvider;
use Psalm\Internal\Provider\FileReferenceCacheProvider;
use Psalm\Internal\Provider\FileStorageCacheProvider;
use Psalm\Internal\Provider\ParserCacheProvider;
use Psalm\Internal\Provider\ProjectCacheProvider;
use Psalm\Internal\Provider\Providers;
use Psalm\Internal\Stubs\Generator\StubsGenerator;
use Psalm\IssueBuffer;
use Psalm\Progress\DebugProgress;
use Psalm\Progress\DefaultProgress;
use Psalm\Progress\LongProgress;
use Psalm\Progress\Progress;
use Psalm\Progress\VoidProgress;
use Psalm\Report;
use Psalm\Report\ReportOptions;
use ReflectionClass;
use RuntimeException;
use Symfony\Component\Filesystem\Path;
use Throwable;
use function array_filter;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_shift;
use function array_slice;
use function array_sum;
use function array_values;
use function chdir;
use function count;
use function defined;
use function extension_loaded;
use function file_exists;
use function file_get_contents;
use function file_put_contents;
use function function_exists;
use function fwrite;
use function gc_collect_cycles;
use function gc_disable;
use function getcwd;
use function getenv;
use function getopt;
use function implode;
use function in_array;
use function ini_get;
use function is_array;
use function is_numeric;
use function is_string;
use function json_encode;
use function max;
use function microtime;
use function opcache_get_status;
use function parse_url;
use function preg_match;
use function preg_replace;
use function realpath;
use function setlocale;
use function sort;
use function str_repeat;
use function str_starts_with;
use function strlen;
use function substr;
use function trim;
use function wordwrap;
use const DIRECTORY_SEPARATOR;
use const JSON_THROW_ON_ERROR;
use const LC_CTYPE;
use const PHP_EOL;
use const PHP_URL_SCHEME;
use const PHP_VERSION;
use const STDERR;
// phpcs:disable PSR1.Files.SideEffects
require_once __DIR__ . '/../ErrorHandler.php';
require_once __DIR__ . '/../CliUtils.php';
require_once __DIR__ . '/../Composer.php';
require_once __DIR__ . '/../IncludeCollector.php';
require_once __DIR__ . '/../../IssueBuffer.php';
require_once __DIR__ . '/../../Report.php';
/**
* @internal
*/
final class Psalm
{
private const SHORT_OPTIONS = [
'f:',
'm',
'h',
'v',
'c:',
'i',
'r:',
];
private const LONG_OPTIONS = [
'clear-cache',
'clear-global-cache',
'config:',
'debug',
'debug-by-line',
'debug-performance',
'debug-emitted-issues',
'diff',
'disable-extension:',
'find-dead-code::',
'find-unused-code::',
'find-unused-variables',
'find-references-to:',
'help',
'ignore-baseline',
'init',
'memory-limit:',
'monochrome',
'no-diff',
'force-jit',
'no-cache',
'no-reflection-cache',
'no-file-cache',
'output-format:',
'plugin:',
'report:',
'report-show-info:',
'root:',
'set-baseline::',
'show-info:',
'show-snippet:',
'stats',
'threads:',
'scan-threads:',
'update-baseline',
'use-baseline:',
'use-ini-defaults',
'version',
'php-version:',
'generate-json-map:',
'generate-stubs:',
'alter',
'review',
'language-server',
'refactor',
'shepherd::',
'no-progress',
'long-progress',
'no-suggestions',
'include-php-versions', // used for baseline
'pretty-print', // used for JSON reports
'track-tainted-input',
'taint-analysis',
'security-analysis',
'dump-taint-graph:',
'find-unused-psalm-suppress',
'error-level:',
];
/**
* @param array<int,string> $argv
* @psalm-suppress ComplexMethod Maybe some of the option handling could be moved to its own function...
*/
public static function run(array $argv): void
{
CliUtils::checkRuntimeRequirements();
gc_collect_cycles();
gc_disable();
ErrorHandler::install($argv);
$args = array_slice($argv, 1);
// get options from command line
$options = getopt(implode('', self::SHORT_OPTIONS), self::LONG_OPTIONS);
if (false === $options) {
throw new RuntimeException('Failed to parse CLI options');
}
// debug CI environment
if (!array_key_exists('debug', $options)
&& 'true' === getenv('GITHUB_ACTIONS')
&& '1' === getenv('RUNNER_DEBUG')
) {
$options['debug'] = false;
}
self::forwardCliCall($options, $argv);
self::validateCliArguments($args);
CliUtils::setMemoryLimit($options);
self::syncShortOptions($options);
if (isset($options['c']) && is_array($options['c'])) {
fwrite(STDERR, 'Too many config files provided' . PHP_EOL);
exit(1);
}
if (array_key_exists('h', $options)) {
echo self::getHelpText();
/*
--shepherd[=endpoint]
Send analysis statistics to Shepherd server.
`endpoint` is the URL to the Shepherd server. It defaults to shepherd.dev
*/
exit;
}
$current_dir = self::getCurrentDir($options);
$path_to_config = CliUtils::getPathToConfig($options);
$vendor_dir = CliUtils::getVendorDir($current_dir);
// capture environment before registering autoloader (it may destroy it)
IssueBuffer::captureServer($_SERVER);
$include_collector = new IncludeCollector();
$first_autoloader = $include_collector->runAndCollect(
// we ignore the FQN because of a hack in scoper.inc that needs full path
// phpcs:ignore SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly.ReferenceViaFullyQualifiedName
static fn(): ?\Composer\Autoload\ClassLoader =>
CliUtils::requireAutoloaders($current_dir, isset($options['r']), $vendor_dir),
);
$run_taint_analysis = self::shouldRunTaintAnalysis($options);
if (array_key_exists('v', $options)) {
echo 'Psalm ' . PSALM_VERSION . PHP_EOL;
exit;
}
$output_format = self::initOutputFormat($options);
[$config, $init_source_dir] = self::initConfig(
$current_dir,
$args,
$vendor_dir,
$first_autoloader,
$path_to_config,
$output_format,
$run_taint_analysis,
$options,
);
if (isset($options['no-cache'])) {
$config->cache_directory = null;
}
$config->setIncludeCollector($include_collector);
$in_ci = CliUtils::runningInCI(); // disable progressbar on CI
if ($in_ci) {
$options['long-progress'] = true;
}
$threads = self::getThreads($options, $config, $in_ci, false);
$scanThreads = self::getThreads($options, $config, $in_ci, true);
$progress = self::initProgress($options, $config, $in_ci);
self::restart($options, $threads, $scanThreads, $progress);
if (isset($options['debug-emitted-issues'])) {
$config->debug_emitted_issues = true;
}
setlocale(LC_CTYPE, 'C');
if (isset($options['set-baseline'])) {
if (is_array($options['set-baseline'])) {
fwrite(STDERR, 'Only one baseline file can be created at a time' . PHP_EOL);
exit(1);
}
}
$paths_to_check = CliUtils::getPathsToCheck($options['f'] ?? null);
if ($config->resolve_from_config_file) {
$current_dir = $config->base_dir;
chdir($current_dir);
}
/** @var list<string> $plugins List of paths to plugin files */
$plugins = [];
if (isset($options['plugin'])) {
$plugins_from_options = $options['plugin'];
if (is_array($plugins_from_options)) {
$plugins = $plugins_from_options;
} elseif (is_string($plugins_from_options)) {
$plugins = [$plugins_from_options];
}
}
$show_info = self::initShowInfo($options);
$is_diff = self::initIsDiff($options);
$find_unused_code = self::shouldFindUnusedCode($options, $config);
$find_unused_variables = isset($options['find-unused-variables']);
$find_references_to = isset($options['find-references-to']) && is_string($options['find-references-to'])
? $options['find-references-to']
: null;
self::configureShepherd($config, $options, $plugins);
if (isset($options['clear-cache'])) {
self::clearCache($config);
}
if (isset($options['clear-global-cache'])) {
self::clearGlobalCache($config);
}
$providers = self::initProviders($options, $config, $current_dir);
$stdout_report_options = self::initStdoutReportOptions($options, $show_info, $output_format, $in_ci);
/** @var list<string>|string $report_file_paths type guaranteed by argument to getopt() */
$report_file_paths = $options['report'] ?? [];
if (is_string($report_file_paths)) {
$report_file_paths = [$report_file_paths];
}
$project_analyzer = new ProjectAnalyzer(
$config,
$providers,
$stdout_report_options,
ProjectAnalyzer::getFileReportOptions(
$report_file_paths,
isset($options['report-show-info'])
? $options['report-show-info'] !== 'false' && $options['report-show-info'] !== '0'
: true,
),
$threads,
$scanThreads,
$progress,
);
CliUtils::initPhpVersion($options, $config, $project_analyzer);
$start_time = microtime(true);
self::configureProjectAnalyzer(
$options,
$config,
$project_analyzer,
$find_references_to,
$find_unused_code,
$find_unused_variables,
$run_taint_analysis,
);
if ($config->run_taint_analysis || $run_taint_analysis) {
$is_diff = false;
}
/** @var string $plugin_path */
foreach ($plugins as $plugin_path) {
$config->addPluginPath($plugin_path);
}
// Prime cache
InternalCallMapHandler::getCallMap();
if ($paths_to_check === null) {
$project_analyzer->check($current_dir, $is_diff);
} elseif ($paths_to_check) {
$project_analyzer->checkPaths($paths_to_check);
}
if ($find_references_to) {
$project_analyzer->findReferencesTo($find_references_to);
}
self::storeFlowGraph($options, $project_analyzer);
if (isset($options['generate-json-map']) && is_string($options['generate-json-map'])) {
self::storeTypeMap($providers, $config, $options['generate-json-map']);
}
if (isset($options['generate-stubs'])) {
self::generateStubs($options, $providers, $project_analyzer);
}
if (!isset($options['i'])) {
IssueBuffer::finish(
$project_analyzer,
!$paths_to_check,
$start_time,
isset($options['stats']),
self::initBaseline($options, $config, $current_dir, $path_to_config, $paths_to_check),
);
} else {
self::autoGenerateConfig($project_analyzer, $current_dir, $init_source_dir, $vendor_dir);
}
}
/** @return int<1, max> */
public static function getThreads(array $options, Config $config, bool $in_ci, bool $for_scan): int
{
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
// No support desired for Windows at the moment
return 1;
} elseif (!extension_loaded('pcntl')) {
// Psalm requires pcntl for multi-threads support
return 1;
}
if ($for_scan) {
if (isset($options['scan-threads'])) {
$threads = max(1, (int)$options['scan-threads']);
} elseif (isset($options['debug']) || $in_ci) {
$threads = 1;
} elseif ($config->scan_threads) {
$threads = $config->scan_threads;
} else {
$threads = max(1, (new CpuCoreCounter())->getCount());
}
} else {
if (isset($options['threads'])) {
$threads = max(1, (int)$options['threads']);
} elseif (isset($options['debug']) || $in_ci) {
$threads = 1;
} elseif ($config->threads) {
$threads = $config->threads;
} else {
$threads = max(1, (new CpuCoreCounter())->getCount());
}
}
return $threads;
}
private static function initOutputFormat(array $options): string
{
return isset($options['output-format']) && is_string($options['output-format'])
? $options['output-format']
: self::findDefaultOutputFormat();
}
/**
* @return Report::TYPE_*
*/
private static function findDefaultOutputFormat(): string
{
$emulator = getenv('TERMINAL_EMULATOR');
if (is_string($emulator) && str_starts_with($emulator, 'JetBrains')) {
return Report::TYPE_PHP_STORM;
}
if ('true' === getenv('GITHUB_ACTIONS')) {
return Report::TYPE_GITHUB_ACTIONS;
}
return Report::TYPE_CONSOLE;
}
private static function initShowInfo(array $options): bool
{
return isset($options['show-info'])
? $options['show-info'] === 'true' || $options['show-info'] === '1'
: false;
}
private static function initIsDiff(array $options): bool
{
return !isset($options['no-diff'])
&& !isset($options['set-baseline'])
&& !isset($options['update-baseline']);
}
/**
* @param array<int,string> $args
*/
private static function validateCliArguments(array $args): void
{
array_map(
static function (string $arg): void {
if (str_starts_with($arg, '--') && $arg !== '--') {
$arg_name = (string) preg_replace('/=.*$/', '', substr($arg, 2), 1);
if (!in_array($arg_name, self::LONG_OPTIONS)
&& !in_array($arg_name . ':', self::LONG_OPTIONS)
&& !in_array($arg_name . '::', self::LONG_OPTIONS)
) {
fwrite(
STDERR,
'Unrecognised argument "--' . $arg_name . '"' . PHP_EOL
. 'Type --help to see a list of supported arguments'. PHP_EOL,
);
exit(1);
}
} elseif (str_starts_with($arg, '-') && $arg !== '-' && $arg !== '--') {
$arg_name = (string) preg_replace('/=.*$/', '', substr($arg, 1));
if (!in_array($arg_name, self::SHORT_OPTIONS)
&& !in_array($arg_name . ':', self::SHORT_OPTIONS)
) {
fwrite(
STDERR,
'Unrecognised argument "-' . $arg_name . '"' . PHP_EOL
. 'Type --help to see a list of supported arguments'. PHP_EOL,
);
exit(1);
}
}
},
$args,
);
}
/**
* @param array<int, string> $args
*/
private static function generateConfig(string $current_dir, array &$args): void
{
if (file_exists($current_dir . DIRECTORY_SEPARATOR . 'psalm.xml')) {
fwrite(STDERR, 'A config file already exists in the current directory' . PHP_EOL);
exit(1);
}
$args = array_values(array_filter(
$args,
static fn(string $arg): bool => $arg !== '--ansi'
&& $arg !== '--no-ansi'
&& $arg !== '-i'
&& $arg !== '--init'
&& $arg !== '--debug'
&& $arg !== '--debug-by-line'
&& $arg !== '--debug-emitted-issues'
&& !str_starts_with($arg, '--disable-extension=')
&& !str_starts_with($arg, '--root=')
&& !str_starts_with($arg, '--r='),
));
$init_level = null;
$init_source_dir = null;
if (count($args)) {
if (count($args) > 2) {
fwrite(STDERR, 'Too many arguments provided for psalm --init' . PHP_EOL);
exit(1);
}
if (isset($args[1])) {
if (!preg_match('/^[1-8]$/', $args[1])) {
fwrite(STDERR, 'Config strictness must be a number between 1 and 8 inclusive' . PHP_EOL);
exit(1);
}
$init_level = (int)$args[1];
}
$init_source_dir = $args[0];
}
$vendor_dir = CliUtils::getVendorDir($current_dir);
if (null !== $init_level) {
try {
$template_contents = Creator::getContents(
$current_dir,
$init_source_dir,
$init_level,
$vendor_dir,
);
} catch (ConfigCreationException $e) {
fwrite(STDERR, $e->getMessage() . PHP_EOL);
exit(1);
}
if (file_put_contents($current_dir . DIRECTORY_SEPARATOR . 'psalm.xml', $template_contents) === false) {
fwrite(STDERR, 'Could not write to psalm.xml' . PHP_EOL);
exit(1);
}
exit('Config file created successfully. Please re-run psalm.' . PHP_EOL);
}
}
private static function loadConfig(
?string $path_to_config,
string $current_dir,
string $output_format,
?ClassLoader $first_autoloader,
bool $run_taint_analysis,
array $options,
): Config {
$config = CliUtils::initializeConfig(
$path_to_config,
$current_dir,
$output_format,
$first_autoloader,
$run_taint_analysis,
);
if (isset($options['error-level'])
&& is_numeric($options['error-level'])
) {
$config_level = (int) $options['error-level'];
if (!in_array($config_level, [1, 2, 3, 4, 5, 6, 7, 8], true)) {
throw new ConfigException(
'Invalid error level ' . $config_level,
);
}
$config->level = $config_level;
}
return $config;
}
private static function initProgress(array $options, Config $config, bool $in_ci): Progress
{
$debug = array_key_exists('debug', $options) || array_key_exists('debug-by-line', $options);
$show_info = isset($options['show-info'])
? $options['show-info'] === 'true' || $options['show-info'] === '1'
: false;
if ($debug) {
$progress = new DebugProgress();
} elseif (isset($options['no-progress'])) {
$progress = new VoidProgress();
} else {
$show_errors = !$config->error_baseline || isset($options['ignore-baseline']);
if (isset($options['long-progress'])) {
$progress = new LongProgress($show_errors, $show_info, $in_ci);
} else {
$progress = new DefaultProgress($show_errors, $show_info, $in_ci);
}
}
// output buffered warnings
foreach ($config->config_warnings as $warning) {
$progress->warning($warning);
}
return $progress;
}
private static function initProviders(array $options, Config $config, string $current_dir): Providers
{
if (isset($options['no-cache']) || isset($options['i'])) {
$providers = new Providers(
new FileProvider,
);
} else {
$no_reflection_cache = isset($options['no-reflection-cache']);
$no_file_cache = isset($options['no-file-cache']);
$file_storage_cache_provider = $no_reflection_cache
? null
: new FileStorageCacheProvider($config);
$classlike_storage_cache_provider = $no_reflection_cache
? null
: new ClassLikeStorageCacheProvider($config);
$providers = new Providers(
new FileProvider,
new ParserCacheProvider($config, !$no_file_cache),
$file_storage_cache_provider,
$classlike_storage_cache_provider,
new FileReferenceCacheProvider($config),
new ProjectCacheProvider(Composer::getLockFilePath($current_dir)),
);
}
return $providers;
}
/**
* @param array{"set-baseline": mixed, ...} $options
* @return array<string,array<string,array{o:int, s: list<string>}>>
*/
private static function generateBaseline(
array $options,
Config $config,
string $current_dir,
?string $path_to_config,
): array {
fwrite(STDERR, 'Writing error baseline to file...' . PHP_EOL);
$error_baseline = is_string($options['set-baseline']) ? $options['set-baseline'] :
($config->error_baseline ?? Config::DEFAULT_BASELINE_NAME);
try {
$issue_baseline = ErrorBaseline::read(
new FileProvider,
$error_baseline,
);
} catch (ConfigException) {
$issue_baseline = [];
}
ErrorBaseline::create(
new FileProvider,
$error_baseline,
IssueBuffer::getIssuesData(),
$config->include_php_versions_in_error_baseline || isset($options['include-php-versions']),
);
fwrite(STDERR, "Baseline saved to $error_baseline.");
if ($error_baseline !== $config->error_baseline) {
CliUtils::updateConfigFile(
$config,
$path_to_config ?? $current_dir,
$error_baseline,
);
}
fwrite(STDERR, PHP_EOL);
return $issue_baseline;
}
/**
* @return array<string,array<string,array{o:int, s: list<string>}>>
*/
private static function updateBaseline(array $options, Config $config): array
{
$baselineFile = $config->error_baseline;
if (empty($baselineFile)) {
fwrite(STDERR, 'Cannot update baseline, because no baseline file is configured.' . PHP_EOL);
exit(1);
}
try {
$issue_current_baseline = ErrorBaseline::read(
new FileProvider,
$baselineFile,
);
$total_issues_current_baseline = ErrorBaseline::countTotalIssues($issue_current_baseline);
$issue_baseline = ErrorBaseline::update(
new FileProvider,
$baselineFile,
IssueBuffer::getIssuesData(),
$config->include_php_versions_in_error_baseline || isset($options['include-php-versions']),
);
$total_issues_updated_baseline = ErrorBaseline::countTotalIssues($issue_baseline);
$total_fixed_issues = $total_issues_current_baseline - $total_issues_updated_baseline;
if ($total_fixed_issues > 0) {
echo str_repeat('-', 30) . "\n";
echo $total_fixed_issues . ' errors fixed' . "\n";
}
} catch (ConfigException $exception) {
fwrite(STDERR, 'Could not update baseline file: ' . $exception->getMessage() . PHP_EOL);
exit(1);
}
return $issue_baseline;
}
private static function storeTypeMap(Providers $providers, Config $config, string $type_map_location): void
{
$file_map = $providers->file_reference_provider->getFileMaps();
$name_file_map = [];
$expected_references = [];
foreach ($file_map as $file_path => $map) {
$file_name = $config->shortenFileName($file_path);
foreach ($map[0] as $map_parts) {
$expected_references[$map_parts[1]] = true;
}
$map[2] = [];
$name_file_map[$file_name] = $map;
}
$reference_dictionary = ReferenceMapGenerator::getReferenceMap(
$providers->classlike_storage_provider,
$expected_references,
);
$type_map_string = json_encode(
['files' => $name_file_map, 'references' => $reference_dictionary],
JSON_THROW_ON_ERROR,
);
$providers->file_provider->setContents(
$type_map_location,
$type_map_string,
);
}
private static function autoGenerateConfig(
ProjectAnalyzer $project_analyzer,
string $current_dir,
?string $init_source_dir,
string $vendor_dir,
): void {
$issues_by_file = IssueBuffer::getIssuesData();
if (!$issues_by_file) {
$init_level = 1;
} else {
$codebase = $project_analyzer->getCodebase();
$mixed_counts = $codebase->analyzer->getTotalTypeCoverage($codebase);
$init_level = Creator::getLevel(
array_merge(...array_values($issues_by_file)),
array_sum($mixed_counts),
);
}
echo "\n" . 'Detected level ' . $init_level . ' as a suitable initial default' . "\n";
try {
$template_contents = Creator::getContents(
$current_dir,
$init_source_dir,
$init_level,
$vendor_dir,
);
} catch (ConfigCreationException $e) {
fwrite(STDERR, $e->getMessage() . PHP_EOL);
exit(1);
}
if (file_put_contents($current_dir . DIRECTORY_SEPARATOR . 'psalm.xml', $template_contents) === false) {
fwrite(STDERR, 'Could not write to psalm.xml' . PHP_EOL);
exit(1);
}
exit('Config file created successfully. Please re-run psalm.' . PHP_EOL);
}
private static function initStdoutReportOptions(
array $options,
bool $show_info,
string $output_format,
bool $in_ci,
): ReportOptions {
$stdout_report_options = new ReportOptions();
$stdout_report_options->use_color = !array_key_exists('m', $options);
$stdout_report_options->show_info = $show_info;
$stdout_report_options->show_suggestions = !array_key_exists('no-suggestions', $options);
/**
* @psalm-suppress PropertyTypeCoercion
*/
$stdout_report_options->format = $output_format;
$stdout_report_options->show_snippet = !isset($options['show-snippet']) || $options['show-snippet'] !== "false";
$stdout_report_options->pretty = isset($options['pretty-print']) && $options['pretty-print'] !== "false";
$stdout_report_options->in_ci = $in_ci;
return $stdout_report_options;
}
private static function clearGlobalCache(Config $config): never
{
$cache_directory = $config->getGlobalCacheDirectory();
if ($cache_directory) {
Config::removeCacheDirectory($cache_directory);
echo 'Global cache directory deleted' . PHP_EOL;
}
exit;
}
private static function clearCache(Config $config): never
{
$cache_directory = $config->getCacheDirectory();
if ($cache_directory !== null) {
Config::removeCacheDirectory($cache_directory);
}
echo 'Cache directory deleted' . PHP_EOL;
exit;
}
private static function getCurrentDir(array $options): string
{
$cwd = getcwd();
if (false === $cwd) {
fwrite(STDERR, 'Cannot get current working directory' . PHP_EOL);
exit(1);
}
$current_dir = $cwd;
if (isset($options['r']) && is_string($options['r'])) {
$root_path = realpath($options['r']);
if ($root_path === false) {
fwrite(
STDERR,
'Could not locate root directory ' . $current_dir . DIRECTORY_SEPARATOR . $options['r'] . PHP_EOL,
);
exit(1);
}
$current_dir = $root_path;
}
return $current_dir;
}
private static function restart(array $options, int $threads, int $scanThreads, Progress $progress): void
{
$ini_handler = new PsalmRestarter('PSALM');
if (isset($options['disable-extension'])) {
if (is_array($options['disable-extension'])) {
/** @psalm-suppress MixedAssignment */
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 || $scanThreads > 1)
&& extension_loaded('grpc')
&& (ini_get('grpc.enable_fork_support') === '1' && ini_get('grpc.poll_strategy') === 'epoll1') === false
) {
$ini_handler->disableExtension('grpc');
$progress->warning(PHP_EOL
. 'grpc extension has been disabled. '
. 'Set grpc.enable_fork_support = 1 and grpc.poll_strategy = epoll1 in php.ini to enable it. '
. 'See https://github.com/grpc/grpc/issues/20250#issuecomment-531321945 for more information.'
. PHP_EOL . PHP_EOL);
}
$ini_handler->disableExtensions([
'uopz',
// extensions that are incompatible with JIT (they are also usually make Psalm slow)
'pcov',
'blackfire',
// Issues w/ parallel forking
'uv',
]);
// If Xdebug is enabled, restart without it
$ini_handler->check();
$progress->write(PHP_EOL."Running on PHP ".PHP_VERSION.', Psalm '.PSALM_VERSION.'.'.PHP_EOL);
$hasJit = false;
if (function_exists('opcache_get_status')) {
if (true === (opcache_get_status()['jit']['on'] ?? false)) {
$hasJit = true;
$progress->write(PHP_EOL
. 'JIT acceleration: ON'
. PHP_EOL . PHP_EOL);
} else {
$progress->write(PHP_EOL
. 'JIT acceleration: OFF (an error occurred while enabling JIT)' . PHP_EOL
. 'Please report this to https://github.com/vimeo/psalm with your OS and PHP configuration!'
. PHP_EOL . PHP_EOL);
}
} else {
$progress->write(PHP_EOL
. 'JIT acceleration: OFF (opcache not installed or not enabled)' . PHP_EOL
. 'Install and enable the opcache extension to make use of JIT for a 20%+ performance boost!'
. PHP_EOL . PHP_EOL);
}
if (isset($options['force-jit']) && !$hasJit) {
$progress->write('Exiting because JIT was requested but is not available.' . PHP_EOL . PHP_EOL);
exit(1);
}
$overcommit = null;