-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathGitlabOutputFormatter.php
More file actions
249 lines (233 loc) · 9.04 KB
/
GitlabOutputFormatter.php
File metadata and controls
249 lines (233 loc) · 9.04 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
<?php
declare(strict_types=1);
namespace Symplify\EasyCodingStandard\Console\Output;
use SebastianBergmann\Diff\Chunk;
use SebastianBergmann\Diff\Line;
use SebastianBergmann\Diff\Parser as DiffParser;
use Symplify\EasyCodingStandard\Console\ExitCode;
use Symplify\EasyCodingStandard\Console\Style\EasyCodingStandardStyle;
use Symplify\EasyCodingStandard\Contract\Console\Output\OutputFormatterInterface;
use Symplify\EasyCodingStandard\SniffRunner\ValueObject\Error\CodingStandardError;
use Symplify\EasyCodingStandard\ValueObject\Configuration;
use Symplify\EasyCodingStandard\ValueObject\Error\ErrorAndDiffResult;
use Symplify\EasyCodingStandard\ValueObject\Error\FileDiff;
use function array_map as map;
use function array_merge as merge;
/**
* Generates a JSON file containing the Gitlab-supported variant of
* "Code Climate" issues for all unresolved errors.
*
* This is compatible with the specs of:
* - Code Climate: ^0.3.1
* - Gitlab: ^16.11 || ^17
*
* Applied diffs are NOT reported, but unapplied diffs ARE. This allows
* our users to choose between a CI/CD workflow where `--fix` is used to
* automatically commit trivial corrections OR one where any errors, even
* resolvable, cause the pipeline to fail.
*
* Unfortunately, because of the way sniffs apply fixes without provenance data
* and with cascading effects, multiple major refactors would be required in
* order to accurately report exactly which fixes apply to exactly which lines.
*
* Finally, all reported errors will be marked as "minor" severity, since
* DevOps downstream can choose if CI/CD ignores and our Sniffers don't
* currently provide their own levels.
*
* As a warning to future maintainers, I believe Gitlab's documentation may be
* slightly wrong. It's not a subset of the Code Climate format as insinuated,
* since it changes some fields from optional to required.
*
* @see https://docs.gitlab.com/ee/ci/testing/code_quality.html#implement-a-custom-tool
* @see https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#data-types
*
* @phpstan-type GitlabIssue array{
* type: 'issue',
* description: string,
* check_name: string,
* fingerprint: string,
* severity: 'minor',
* categories: array{'Style'},
* remediation_points?: int,
* location: array{
* path: string,
* lines: array{
* begin: int,
* end: int,
* },
* },
* }
*/
final readonly class GitlabOutputFormatter implements OutputFormatterInterface
{
public function __construct(
private EasyCodingStandardStyle $easyCodingStandardStyle,
private ExitCodeResolver $exitCodeResolver,
private DiffParser $diffParser,
) {
}
public static function getName(): string
{
return 'gitlab';
}
public static function hasSupportForProgressBars(): bool
{
return false;
}
/**
* @return ExitCode::*
*/
public function report(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration): int
{
$output = $this->generateReport($errorAndDiffResult, $configuration);
$this->easyCodingStandardStyle->writeln($output);
return $this->exitCodeResolver->resolve($errorAndDiffResult, $configuration);
}
public function generateReport(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration): string
{
$reportedQualityIssues = (! $configuration->isFixer() && $configuration->shouldShowDiffs())
? merge(
$this->generateIssuesForErrors(
$errorAndDiffResult->getErrors(),
$configuration->isReportingWithRealPath()
),
$this->generateIssuesForFixes(
$errorAndDiffResult->getFileDiffs(),
$configuration->isReportingWithRealPath()
),
)
: $this->generateIssuesForErrors(
$errorAndDiffResult->getErrors(),
$configuration->isReportingWithRealPath()
);
return $this->encode($reportedQualityIssues);
}
/**
* @param CodingStandardError[] $errors
* @return GitlabIssue[]
*/
private function generateIssuesForErrors(array $errors, bool $absoluteFilePath = false): array
{
return map(
fn (CodingStandardError $codingStandardError): array => [
'type' => 'issue',
'description' => $codingStandardError->getMessage(),
'check_name' => $codingStandardError->getCheckerClass(),
'fingerprint' => $this->generateFingerprint(
$codingStandardError->getCheckerClass(),
$codingStandardError->getMessage(),
$codingStandardError->getRelativeFilePath(),
),
'severity' => 'minor',
'categories' => ['Style'],
'location' => [
'path' => $absoluteFilePath ? $codingStandardError->getAbsoluteFilePath() ?? '' : $codingStandardError->getRelativeFilePath(),
'lines' => [
'begin' => $codingStandardError->getLine(),
'end' => $codingStandardError->getLine(),
],
],
],
$errors,
);
}
/**
* Reports each chunk of changes as a separate issue.
*
* @param FileDiff[] $diffs
* @return GitlabIssue[]
*/
private function generateIssuesForFixes(array $diffs, bool $absoluteFilePath = false): array
{
return merge(
...map(
fn (FileDiff $fileDiff): array => map(
fn (Chunk $chunk): array => $this->generateIssueForChunk($fileDiff, $chunk, $absoluteFilePath),
$this->diffParser->parse($fileDiff->getDiff())[0]
->chunks(),
),
$diffs,
),
);
}
/**
* @return GitlabIssue
*/
private function generateIssueForChunk(FileDiff $fileDiff, Chunk $chunk, bool $absoluteFilePath): array
{
$checkersAsFqcns = implode(',', $fileDiff->getAppliedCheckers());
$checkersAsClasses = implode(', ', map(
static fn (string $checker): string => preg_replace('/.*\\\/', '', $checker) ?? $checker,
$fileDiff->getAppliedCheckers(),
));
$message = 'Chunk has fixable errors: ' . $checkersAsClasses;
$lineStart = $chunk->start();
$lineEnd = $lineStart + $chunk->startRange() - 1;
return [
'type' => 'issue',
'description' => $message,
'check_name' => $checkersAsFqcns,
'fingerprint' => $this->generateFingerprint(
$checkersAsFqcns,
$message,
$fileDiff->getRelativeFilePath(),
implode(
'\n',
map(static fn (Line $line): string => sprintf(
'%d:%s',
$line->type(),
$line->content()
), $chunk->lines())
),
),
'severity' => 'minor',
'categories' => ['Style'],
'remediation_points' => 50_000,
'location' => [
'path' => $absoluteFilePath ? $fileDiff->getAbsoluteFilePath() ?? '' : $fileDiff->getRelativeFilePath(),
'lines' => [
'begin' => $lineStart,
'end' => $lineEnd,
],
],
];
}
/**
* Generate a fingerprint for a given quality issue. This is used to
* track the presence of an issue between runs, so it should be unique
* and consistent for a given issue.
*
* Subsequently, changing the fingerprint or the data it uses is
* _technically_ a breaking change. Users would see existing issues being
* marked as "new" on the commit proceeding updating ECS.
*
* DO NOT include position information as salting, or every time
* lines are added/removed the lines below it will be reported as
* new errors.
*/
private function generateFingerprint(
string $checker,
string $message,
string $relativeFilePath,
string $salt = '',
): string {
// We implode to add a separator that cannot show up in PHP
// class names or Linux file names and SHOULD never show up in
// messages. This guarantees the same fingerprint won't be generated
// by accident, by the associative property of concatenation. As in:
//
// (ABC + ABC = ABCABC) == (ABCA + BC = ABCABC)
// (ABC + \0 + ABC = ABC\0ABC) != (ABCA + \0 + BC = ABCA\0BC)
return md5(implode("\0", [$checker, $message, $relativeFilePath, $salt]));
}
/**
* @param GitlabIssue[] $lineItems
*/
private function encode(array $lineItems): string
{
return json_encode(
$lineItems,
JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
}
}