-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathPlugin.php
More file actions
303 lines (240 loc) · 9.9 KB
/
Plugin.php
File metadata and controls
303 lines (240 loc) · 9.9 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
<?php
declare(strict_types=1);
namespace Pest\TypeCoverage;
use Pest\Contracts\Plugins\HandlesOriginalArguments;
use Pest\Plugins\Concerns\HandleArguments;
use Pest\Plugins\Shard;
use Pest\Support\View;
use Pest\TestSuite;
use Pest\TypeCoverage\Contracts\Logger;
use Pest\TypeCoverage\Logging\JsonLogger;
use Pest\TypeCoverage\Logging\NullLogger;
use Pest\TypeCoverage\Support\Cache;
use Pest\TypeCoverage\Support\ConfigurationSourceDetector;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\OutputInterface;
use function Termwind\render;
use function Termwind\renderUsing;
use function Termwind\terminal;
/**
* @internal
*
* @final
*/
class Plugin implements HandlesOriginalArguments
{
use HandleArguments;
/**
* The minimum coverage.
*/
private float $coverageMin = 0.0;
/**
* The logger used to output type coverage to a file.
*/
private Logger $coverageLogger;
/**
* Whether to use compact output.
*/
private bool $compact = false;
/**
* Creates a new Plugin instance.
*/
public function __construct(
private readonly OutputInterface $output,
private readonly Cache $cache,
) {
$this->coverageLogger = new NullLogger;
}
/**
* {@inheritdoc}
*/
public function handleOriginalArguments(array $arguments): void
{
if (! $this->hasArgument('--type-coverage', $arguments)) {
return;
}
if ($this->hasArgument('--no-cache', $arguments)) {
$this->cache->flush();
}
$startTime = microtime(true);
foreach ($arguments as $argument) {
if (str_starts_with($argument, '--min')) {
// grab the value of the --min argument
$this->coverageMin = (float) explode('=', $argument)[1];
}
if (str_starts_with($argument, '--memory-limit')) {
$memoryLimit = explode('=', $argument)[1] ?? '';
if (preg_match('/^-?\d+[kMG]?$/', $memoryLimit) !== 1) {
View::render('components.badge', [
'type' => 'ERROR',
'content' => 'Invalid memory limit: '.$memoryLimit,
]);
$this->exit(1);
}
if (ini_set('memory_limit', $memoryLimit) === false) {
View::render('components.badge', [
'type' => 'ERROR',
'content' => 'Failed to set memory limit: '.$memoryLimit,
]);
$this->exit(1);
}
}
if (str_starts_with($argument, '--type-coverage-json')) {
$outputPath = explode('=', $argument)[1] ?? null;
if ($outputPath === null) {
View::render('components.badge', [
'type' => 'ERROR',
'content' => 'No output path provided for [--type-coverage-json].',
]);
$this->exit(1);
}
$this->coverageLogger = new JsonLogger(explode('=', $argument)[1], $this->coverageMin);
}
if (str_starts_with($argument, '--compact')) {
$this->compact = true;
}
}
// Normalize configuration argument to support: --configuration=, --configuration <file>, -c <file>, -c=<file>
$normalizedConfigArg = null;
foreach ($arguments as $index => $arg) {
if (str_starts_with($arg, '--configuration=')) {
$normalizedConfigArg = $arg;
break;
}
if ($arg === '--configuration') {
$value = $arguments[$index + 1] ?? null;
if ($value !== null) {
$normalizedConfigArg = '--configuration='.$value;
break;
}
}
if ($arg === '-c') {
$value = $arguments[$index + 1] ?? null;
if ($value !== null) {
$normalizedConfigArg = '--configuration='.$value;
break;
}
}
if (str_starts_with($arg, '-c=')) {
$normalizedConfigArg = '--configuration='.substr($arg, 3);
break;
}
}
$files = ConfigurationSourceDetector::detect($normalizedConfigArg ? [$normalizedConfigArg] : []);
if ($files === []) {
View::render('components.badge', [
'type' => 'ERROR',
'content' => 'No source section found. Did you forget to add a `source` section to your `phpunit.xml` file?',
]);
$this->exit(1);
}
// Filter out traits
$files = array_values(array_filter(
$files,
static fn (string $file): bool => is_string($file) && is_file($file) && ! str_contains((string) file_get_contents($file), 'trait '),
));
$totals = [];
$this->output->writeln(['']);
$terminalWidth = terminal()->width();
$input = new ArgvInput($arguments);
$total = 1;
$index = 1;
if ($input->hasParameterOption('--shard')) {
['index' => $index, 'total' => $total] = Shard::getShard($input);
}
if ($total > 1) {
$files = array_values(array_filter($files, static function (string $file) use ($index, $total): bool {
return (crc32((string) realpath($file)) % $total) === ($index - 1);
}));
}
Analyser::analyse(
$files,
function (Result $result) use (&$totals): void {
$path = str_replace(TestSuite::getInstance()->rootPath.DIRECTORY_SEPARATOR, '', $result->file);
$uncoveredLines = [];
$uncoveredLinesIgnored = [];
$errors = $result->errors;
$errorsIgnored = $result->errorsIgnored;
usort($errors, static fn (Error $a, Error $b): int => $a->line <=> $b->line);
usort($errorsIgnored, static fn (Error $a, Error $b): int => $a->line <=> $b->line);
foreach ($errors as $error) {
$uncoveredLines[] = $error->getShortType().$error->line;
}
foreach ($errorsIgnored as $error) {
$uncoveredLinesIgnored[] = $error->getShortType().$error->line;
}
$this->coverageLogger->append($path, $uncoveredLines, $uncoveredLinesIgnored, $result->totalCoverage);
$totals[] = $result->totalCoverage;
},
function (Result $result) use ($terminalWidth): void {
$path = str_replace(TestSuite::getInstance()->rootPath.'/', '', $result->file);
$truncateAt = max(1, $terminalWidth - 12);
$uncoveredLines = [];
$uncoveredLinesIgnored = [];
$errors = $result->errors;
$errorsIgnored = $result->errorsIgnored;
usort($errors, static fn (Error $a, Error $b): int => $a->line <=> $b->line);
usort($errorsIgnored, static fn (Error $a, Error $b): int => $a->line <=> $b->line);
foreach ($errors as $error) {
$uncoveredLines[] = $error->getShortType().$error->line;
}
foreach ($errorsIgnored as $error) {
$uncoveredLinesIgnored[] = $error->getShortType().$error->line;
}
$color = $uncoveredLines === [] ? 'green' : 'yellow';
$uncoveredLines = implode(', ', $uncoveredLines);
$uncoveredLinesIgnored = implode(', ', $uncoveredLinesIgnored);
if ($uncoveredLinesIgnored !== '') {
$uncoveredLinesIgnored = '<span class="text-gray">'.$uncoveredLinesIgnored.'</span>';
if ($uncoveredLines !== '') {
$uncoveredLinesIgnored = ' '.$uncoveredLinesIgnored;
}
}
$percentage = $result->totalCoverage;
if ($this->compact === true && $percentage === 100) {
return;
}
renderUsing($this->output);
render(<<<HTML
<div class="flex mx-2">
<span class="truncate-{$truncateAt}">{$path}</span>
<span class="flex-1 content-repeat-[.] text-gray mx-1"></span>
<span class="text-{$color}">$uncoveredLines{$uncoveredLinesIgnored} {$percentage}%</span>
</div>
HTML);
},
$this->cache,
);
$coverage = array_sum($totals) / count($totals);
$this->coverageLogger->output();
$exitCode = (int) ($coverage < $this->coverageMin);
$duration = number_format(microtime(true) - $startTime, 2, '.', '');
if ($exitCode === 1) {
View::render('components.badge', [
'type' => 'ERROR',
'content' => 'Type coverage below expected: '.number_format($this->coverageMin, 1).'%, currently '.number_format(floor($coverage * 10) / 10, 1).'%',
]);
} else {
$totalCoverageAsString = $coverage === 0
? '0.0'
: number_format((float) $coverage, 1, '.', '');
render(<<<HTML
<div class="mx-2">
<hr class="text-gray" />
<div class="w-full text-right">
<span class="ml-1 font-bold"><span class="text-gray">({$duration}s)</span> Total: {$totalCoverageAsString} %</span>
</div>
</div>
HTML);
$this->output->writeln(['']);
}
$this->exit($exitCode);
}
/**
* Exits the process with the given code.
*/
public function exit(int $code): never
{
exit($code);
}
}