1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle;
21
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.io.OutputStreamWriter;
27 import java.io.PrintWriter;
28 import java.io.StringWriter;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.nio.charset.StandardCharsets;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.LinkedHashMap;
35 import java.util.List;
36 import java.util.Locale;
37 import java.util.Map;
38 import java.util.MissingResourceException;
39 import java.util.Objects;
40 import java.util.ResourceBundle;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
43
44 import com.puppycrawl.tools.checkstyle.api.AuditEvent;
45 import com.puppycrawl.tools.checkstyle.api.AuditListener;
46 import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
47 import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
48 import com.puppycrawl.tools.checkstyle.meta.ModuleDetails;
49 import com.puppycrawl.tools.checkstyle.meta.XmlMetaReader;
50 import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
51
52
53
54
55
56
57 public final class SarifLogger extends AbstractAutomaticBean implements AuditListener {
58
59
60 private static final int UNICODE_LENGTH = 4;
61
62
63 private static final int UNICODE_ESCAPE_UPPER_LIMIT = 0x1F;
64
65
66 private static final int BUFFER_SIZE = 1024;
67
68
69 private static final String MESSAGE_PLACEHOLDER = "${message}";
70
71
72 private static final String MESSAGE_TEXT_PLACEHOLDER = "${messageText}";
73
74
75 private static final String MESSAGE_ID_PLACEHOLDER = "${messageId}";
76
77
78 private static final String SEVERITY_LEVEL_PLACEHOLDER = "${severityLevel}";
79
80
81 private static final String URI_PLACEHOLDER = "${uri}";
82
83
84 private static final String LINE_PLACEHOLDER = "${line}";
85
86
87 private static final String COLUMN_PLACEHOLDER = "${column}";
88
89
90 private static final String RULE_ID_PLACEHOLDER = "${ruleId}";
91
92
93 private static final String VERSION_PLACEHOLDER = "${version}";
94
95
96 private static final String RESULTS_PLACEHOLDER = "${results}";
97
98
99 private static final String RULES_PLACEHOLDER = "${rules}";
100
101
102 private static final String TWO_BACKSLASHES = "\\\\";
103
104
105 private static final Pattern TWO_BACKSLASHES_PATTERN = Pattern.compile(TWO_BACKSLASHES);
106
107
108 private static final Pattern WINDOWS_DRIVE_LETTER_PATTERN =
109 Pattern.compile("\\A[A-Z]:", Pattern.CASE_INSENSITIVE);
110
111
112 private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{\\w+}");
113
114
115 private static final String COMMA_LINE_SEPARATOR = ",\n";
116
117
118 private final PrintWriter writer;
119
120
121 private final boolean closeStream;
122
123
124 private final List<String> results = new ArrayList<>();
125
126
127 private final Map<String, ModuleDetails> allModuleMetadata = new HashMap<>();
128
129
130 private final Map<RuleKey, ModuleDetails> ruleMetadata = new LinkedHashMap<>();
131
132
133 private final String report;
134
135
136 private final String resultLineColumn;
137
138
139 private final String resultLineOnly;
140
141
142 private final String resultFileOnly;
143
144
145 private final String resultErrorOnly;
146
147
148 private final String rule;
149
150
151 private final String messageStrings;
152
153
154 private final String messageTextOnly;
155
156
157 private final String messageWithId;
158
159
160
161
162
163
164
165
166
167
168
169
170 public SarifLogger(
171 OutputStream outputStream,
172 AutomaticBean.OutputStreamOptions outputStreamOptions)
173 throws IOException {
174 this(outputStream, OutputStreamOptions.valueOf(outputStreamOptions.name()));
175 }
176
177
178
179
180
181
182
183
184
185 public SarifLogger(
186 OutputStream outputStream,
187 OutputStreamOptions outputStreamOptions)
188 throws IOException {
189 if (outputStreamOptions == null) {
190 throw new IllegalArgumentException("Parameter outputStreamOptions can not be null");
191 }
192 writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
193 closeStream = outputStreamOptions == OutputStreamOptions.CLOSE;
194 loadModuleMetadata();
195 report = readResource("/com/puppycrawl/tools/checkstyle/sarif/SarifReport.template");
196 resultLineColumn =
197 readResource("/com/puppycrawl/tools/checkstyle/sarif/ResultLineColumn.template");
198 resultLineOnly =
199 readResource("/com/puppycrawl/tools/checkstyle/sarif/ResultLineOnly.template");
200 resultFileOnly =
201 readResource("/com/puppycrawl/tools/checkstyle/sarif/ResultFileOnly.template");
202 resultErrorOnly =
203 readResource("/com/puppycrawl/tools/checkstyle/sarif/ResultErrorOnly.template");
204 rule = readResource("/com/puppycrawl/tools/checkstyle/sarif/Rule.template");
205 messageStrings =
206 readResource("/com/puppycrawl/tools/checkstyle/sarif/MessageStrings.template");
207 messageTextOnly =
208 readResource("/com/puppycrawl/tools/checkstyle/sarif/MessageTextOnly.template");
209 messageWithId =
210 readResource("/com/puppycrawl/tools/checkstyle/sarif/MessageWithId.template");
211 }
212
213
214
215
216 private void loadModuleMetadata() {
217 final List<ModuleDetails> allModules =
218 XmlMetaReader.readAllModulesIncludingThirdPartyIfAny();
219 for (ModuleDetails module : allModules) {
220 allModuleMetadata.put(module.getFullQualifiedName(), module);
221 }
222 }
223
224 @Override
225 protected void finishLocalSetup() {
226
227 }
228
229 @Override
230 public void auditStarted(AuditEvent event) {
231
232 }
233
234 @Override
235 public void auditFinished(AuditEvent event) {
236 String rendered = replaceVersionString(report);
237 rendered = rendered
238 .replace(RESULTS_PLACEHOLDER, String.join(COMMA_LINE_SEPARATOR, results))
239 .replace(RULES_PLACEHOLDER, String.join(COMMA_LINE_SEPARATOR, generateRules()));
240 writer.print(rendered);
241 if (closeStream) {
242 writer.close();
243 }
244 else {
245 writer.flush();
246 }
247 }
248
249
250
251
252
253
254 private List<String> generateRules() {
255 final List<String> result = new ArrayList<>();
256 for (Map.Entry<RuleKey, ModuleDetails> entry : ruleMetadata.entrySet()) {
257 final RuleKey ruleKey = entry.getKey();
258 final ModuleDetails module = entry.getValue();
259 final String shortDescription;
260 final String fullDescription;
261 final String messageStringsFragment;
262 if (module == null) {
263 shortDescription = CommonUtil.baseClassName(ruleKey.sourceName());
264 fullDescription = "No description available";
265 messageStringsFragment = "";
266 }
267 else {
268 shortDescription = module.getName();
269 fullDescription = module.getDescription();
270 messageStringsFragment = String.join(COMMA_LINE_SEPARATOR,
271 generateMessageStrings(module));
272 }
273 result.add(rule
274 .replace(RULE_ID_PLACEHOLDER, ruleKey.toRuleId())
275 .replace("${shortDescription}", shortDescription)
276 .replace("${fullDescription}", escape(fullDescription))
277 .replace("${messageStrings}", messageStringsFragment));
278 }
279 return result;
280 }
281
282
283
284
285
286
287
288 private List<String> generateMessageStrings(ModuleDetails module) {
289 final Map<String, String> messages = getMessages(module);
290 return module.getViolationMessageKeys().stream()
291 .filter(messages::containsKey)
292 .map(key -> {
293 final String message = messages.get(key);
294 return messageStrings
295 .replace("${key}", key)
296 .replace("${text}", escape(message));
297 })
298 .toList();
299 }
300
301
302
303
304
305
306
307 private static Map<String, String> getMessages(ModuleDetails moduleDetails) {
308 final String fullQualifiedName = moduleDetails.getFullQualifiedName();
309 final Map<String, String> result = new LinkedHashMap<>();
310 try {
311 final int lastDot = fullQualifiedName.lastIndexOf('.');
312 final String packageName = fullQualifiedName.substring(0, lastDot);
313 final String bundleName = packageName + ".messages";
314 final Class<?> moduleClass = Class.forName(fullQualifiedName);
315 final ResourceBundle bundle = ResourceBundle.getBundle(
316 bundleName,
317 Locale.ROOT,
318 moduleClass.getClassLoader()
319 );
320 for (String key : moduleDetails.getViolationMessageKeys()) {
321 result.put(key, bundle.getString(key));
322 }
323 }
324 catch (ClassNotFoundException | MissingResourceException ignored) {
325
326
327 }
328 return result;
329 }
330
331
332
333
334
335
336
337 private static String replaceVersionString(String report) {
338 final String version = SarifLogger.class.getPackage().getImplementationVersion();
339 return report.replace(VERSION_PLACEHOLDER, Objects.toString(version, "null"));
340 }
341
342 @Override
343 public void addError(AuditEvent event) {
344 final RuleKey ruleKey = cacheRuleMetadata(event);
345 final String message = generateMessage(ruleKey, event);
346 if (event.getColumn() > 0) {
347 results.add(fillTemplate(resultLineColumn, Map.of(
348 SEVERITY_LEVEL_PLACEHOLDER, renderSeverityLevel(event.getSeverityLevel()),
349 URI_PLACEHOLDER, renderFileNameUri(event.getFileName()),
350 COLUMN_PLACEHOLDER, Integer.toString(event.getColumn()),
351 LINE_PLACEHOLDER, Integer.toString(event.getLine()),
352 MESSAGE_PLACEHOLDER, message,
353 RULE_ID_PLACEHOLDER, ruleKey.toRuleId())));
354 }
355 else {
356 results.add(fillTemplate(resultLineOnly, Map.of(
357 SEVERITY_LEVEL_PLACEHOLDER, renderSeverityLevel(event.getSeverityLevel()),
358 URI_PLACEHOLDER, renderFileNameUri(event.getFileName()),
359 LINE_PLACEHOLDER, Integer.toString(event.getLine()),
360 MESSAGE_PLACEHOLDER, message,
361 RULE_ID_PLACEHOLDER, ruleKey.toRuleId())));
362 }
363 }
364
365
366
367
368
369
370
371 private RuleKey cacheRuleMetadata(AuditEvent event) {
372 final String sourceName = event.getSourceName();
373 final RuleKey key = new RuleKey(sourceName, event.getModuleId());
374 final ModuleDetails module = allModuleMetadata.get(sourceName);
375 ruleMetadata.putIfAbsent(key, module);
376 return key;
377 }
378
379
380
381
382
383
384
385
386 private String generateMessage(RuleKey ruleKey, AuditEvent event) {
387 final String violationKey = event.getViolation().getKey();
388 final ModuleDetails module = ruleMetadata.get(ruleKey);
389 final String result;
390 if (module != null && module.getViolationMessageKeys().contains(violationKey)) {
391 result = messageWithId
392 .replace(MESSAGE_ID_PLACEHOLDER, violationKey)
393 .replace(MESSAGE_TEXT_PLACEHOLDER, escape(event.getMessage()));
394 }
395 else {
396 result = messageTextOnly
397 .replace(MESSAGE_TEXT_PLACEHOLDER, escape(event.getMessage()));
398 }
399 return result;
400 }
401
402 @Override
403 public void addException(AuditEvent event, Throwable throwable) {
404 final StringWriter stringWriter = new StringWriter();
405 final PrintWriter printer = new PrintWriter(stringWriter);
406 throwable.printStackTrace(printer);
407 final String message = messageTextOnly
408 .replace(MESSAGE_TEXT_PLACEHOLDER, escape(stringWriter.toString()));
409 if (event.getFileName() == null) {
410 results.add(fillTemplate(resultErrorOnly, Map.of(
411 SEVERITY_LEVEL_PLACEHOLDER, renderSeverityLevel(event.getSeverityLevel()),
412 MESSAGE_PLACEHOLDER, message)));
413 }
414 else {
415 results.add(fillTemplate(resultFileOnly, Map.of(
416 SEVERITY_LEVEL_PLACEHOLDER, renderSeverityLevel(event.getSeverityLevel()),
417 URI_PLACEHOLDER, renderFileNameUri(event.getFileName()),
418 MESSAGE_PLACEHOLDER, message)));
419 }
420 }
421
422 @Override
423 public void fileStarted(AuditEvent event) {
424
425 }
426
427 @Override
428 public void fileFinished(AuditEvent event) {
429
430 }
431
432
433
434
435
436
437
438
439
440
441
442 private static String fillTemplate(String template, Map<String, String> values) {
443 final Matcher matcher = PLACEHOLDER_PATTERN.matcher(template);
444 final StringBuilder result = new StringBuilder(256);
445 while (matcher.find()) {
446 final String placeholder = matcher.group();
447 final String value = values.getOrDefault(placeholder, placeholder);
448 matcher.appendReplacement(result, Matcher.quoteReplacement(value));
449 }
450 matcher.appendTail(result);
451 return result.toString();
452 }
453
454
455
456
457
458
459
460
461 private static String renderFileNameUri(final String fileName) {
462 String normalized = TWO_BACKSLASHES_PATTERN.matcher(fileName).replaceAll("/");
463 if (WINDOWS_DRIVE_LETTER_PATTERN.matcher(normalized).find()) {
464 normalized = '/' + normalized;
465 }
466 try {
467 return "file:" + new URI(null, null, normalized, null).toASCIIString();
468 }
469 catch (URISyntaxException exc) {
470 throw new IllegalArgumentException("Invalid file name: " + fileName, exc);
471 }
472 }
473
474
475
476
477
478
479
480 private static String renderSeverityLevel(SeverityLevel severityLevel) {
481 return switch (severityLevel) {
482 case IGNORE -> "none";
483 case INFO -> "note";
484 case WARNING -> "warning";
485 case ERROR -> "error";
486 };
487 }
488
489
490
491
492
493
494
495
496 public static String escape(String value) {
497 final int length = value.length();
498 final StringBuilder sb = new StringBuilder(length);
499 for (int index = 0; index < length; index++) {
500 final char chr = value.charAt(index);
501 final String replacement = switch (chr) {
502 case '"' -> "\\\"";
503 case '\\' -> TWO_BACKSLASHES;
504 case '\b' -> "\\b";
505 case '\f' -> "\\f";
506 case '\n' -> "\\n";
507 case '\r' -> "\\r";
508 case '\t' -> "\\t";
509 case '/' -> "\\/";
510 default -> {
511 if (chr <= UNICODE_ESCAPE_UPPER_LIMIT) {
512 yield escapeUnicode1F(chr);
513 }
514 yield Character.toString(chr);
515 }
516 };
517 sb.append(replacement);
518 }
519
520 return sb.toString();
521 }
522
523
524
525
526
527
528
529 private static String escapeUnicode1F(char chr) {
530 final String hexString = Integer.toHexString(chr);
531 return "\\u"
532 + "0".repeat(UNICODE_LENGTH - hexString.length())
533 + hexString.toUpperCase(Locale.US);
534 }
535
536
537
538
539
540
541
542
543 public static String readResource(String name) throws IOException {
544 try (InputStream inputStream = SarifLogger.class.getResourceAsStream(name);
545 ByteArrayOutputStream result = new ByteArrayOutputStream()) {
546 if (inputStream == null) {
547 throw new IOException("Cannot find the resource " + name);
548 }
549 final byte[] buffer = new byte[BUFFER_SIZE];
550 int length = 0;
551 while (length != -1) {
552 result.write(buffer, 0, length);
553 length = inputStream.read(buffer);
554 }
555 return result.toString(StandardCharsets.UTF_8);
556 }
557 }
558
559
560
561
562
563
564
565 private record RuleKey(String sourceName, String moduleId) {
566
567
568
569
570
571 private String toRuleId() {
572 final String result;
573 if (moduleId == null) {
574 result = sourceName;
575 }
576 else {
577 result = sourceName + '#' + moduleId;
578 }
579 return result;
580 }
581 }
582
583 }