-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender-phpdecide-annotations.php
More file actions
220 lines (181 loc) · 5.36 KB
/
Copy pathrender-phpdecide-annotations.php
File metadata and controls
220 lines (181 loc) · 5.36 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
#!/usr/bin/env php
<?php
declare(strict_types=1);
if ($argc < 2 || $argc > 3) {
fwrite(STDERR, "Usage: php render-phpdecide-annotations.php <enforce-json-path> [output-commands-path]\n");
exit(1);
}
$inputPath = $argv[1];
$outputPath = $argv[2] ?? null;
if (!is_file($inputPath)) {
fwrite(STDERR, sprintf("Input JSON file not found: %s\n", $inputPath));
exit(1);
}
$json = file_get_contents($inputPath);
if ($json === false) {
fwrite(STDERR, sprintf("Unable to read input JSON file: %s\n", $inputPath));
exit(1);
}
$json = normalizeInputEncoding($json);
try {
/** @var mixed $payload */
$payload = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
fwrite(STDERR, sprintf("Invalid JSON input: %s\n", $exception->getMessage()));
exit(1);
}
if (!is_array($payload)) {
fwrite(STDERR, "JSON input must decode to an object.\n");
exit(1);
}
$commands = renderAnnotationCommands($payload);
if ($outputPath !== null) {
$bytes = file_put_contents($outputPath, $commands);
if ($bytes === false) {
fwrite(STDERR, sprintf("Unable to write output commands file: %s\n", $outputPath));
exit(1);
}
exit(0);
}
fwrite(STDOUT, $commands);
exit(0);
/**
* @param array<string, mixed> $payload
*/
function renderAnnotationCommands(array $payload): string
{
$commands = [];
$error = $payload['error'] ?? null;
if (is_string($error) && $error !== '') {
$commands[] = githubCommand('error', [], 'PHPDecide enforcement failed: ' . $error);
return implode("\n", $commands) . "\n";
}
foreach (decisionEntries($payload) as $entry) {
$decisionId = stringOrDefault($entry, 'decision_id', 'unknown');
$decisionTitle = stringOrDefault($entry, 'decision_title', 'Unknown decision');
foreach (findingEntries($entry, 'violations') as $finding) {
$commands[] = githubCommand(
'error',
findingProperties($finding, sprintf('[%s] %s', $decisionId, $decisionTitle)),
renderFindingMessage($finding)
);
}
}
foreach (findingEntries($payload, 'unmapped_findings') as $finding) {
$commands[] = githubCommand(
'warning',
findingProperties($finding, 'Unmapped finding'),
renderFindingMessage($finding)
);
}
if ($commands === []) {
$commands[] = githubCommand('notice', [], 'PHPDecide enforcement found no decision-linked violations.');
}
return implode("\n", $commands) . "\n";
}
function normalizeInputEncoding(string $contents): string
{
$encoding = mb_detect_encoding(
$contents,
['UTF-8', 'UTF-16LE', 'UTF-16BE', 'UTF-32LE', 'UTF-32BE'],
true
);
if ($encoding === false) {
return removeUtf8Bom($contents);
}
$normalized = $encoding === 'UTF-8'
? $contents
: mb_convert_encoding($contents, 'UTF-8', $encoding);
return removeUtf8Bom($normalized);
}
function removeUtf8Bom(string $contents): string
{
$bom = "\xEF\xBB\xBF";
if (str_starts_with($contents, $bom)) {
return substr($contents, 3);
}
return $contents;
}
/**
* @return list<array<string, mixed>>
*/
function decisionEntries(array $payload): array
{
return findingEntries($payload, 'violations_by_decision');
}
/**
* @return list<array<string, mixed>>
*/
function findingEntries(array $payload, string $field): array
{
$value = $payload[$field] ?? [];
if (!is_array($value)) {
return [];
}
return array_values(array_filter($value, 'is_array'));
}
/**
* @param array<string, mixed> $finding
* @return array<string, string>
*/
function findingProperties(array $finding, string $title): array
{
$properties = [
'title' => $title,
'file' => stringOrDefault($finding, 'path', 'unknown-path'),
];
if (isset($finding['line']) && is_int($finding['line'])) {
$properties['line'] = (string) $finding['line'];
}
return $properties;
}
/**
* @param array<string, mixed> $finding
*/
function renderFindingMessage(array $finding): string
{
return sprintf(
'[%s via %s] %s',
stringOrDefault($finding, 'rule_id', 'unknown-rule'),
stringOrDefault($finding, 'tool', 'unknown-tool'),
stringOrDefault($finding, 'message', 'No message provided.')
);
}
/**
* @param array<string, string> $properties
*/
function githubCommand(string $level, array $properties, string $message): string
{
$prefix = '::' . $level;
if ($properties === []) {
return $prefix . '::' . escapeCommandData($message);
}
$pairs = [];
foreach ($properties as $key => $value) {
$pairs[] = $key . '=' . escapeCommandProperty($value);
}
return sprintf('%s %s::%s', $prefix, implode(',', $pairs), escapeCommandData($message));
}
function escapeCommandData(string $value): string
{
return str_replace(
['%', "\r", "\n"],
['%25', '%0D', '%0A'],
$value
);
}
function escapeCommandProperty(string $value): string
{
return str_replace(
['%', "\r", "\n", ':', ','],
['%25', '%0D', '%0A', '%3A', '%2C'],
$value
);
}
/**
* @param array<string, mixed> $data
*/
function stringOrDefault(array $data, string $field, string $default): string
{
return isset($data[$field]) && is_string($data[$field]) ? $data[$field] : $default;
}