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.File;
23 import java.io.IOException;
24 import java.nio.charset.StandardCharsets;
25 import java.util.List;
26 import java.util.Locale;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30
31 import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
32 import com.puppycrawl.tools.checkstyle.api.DetailAST;
33 import com.puppycrawl.tools.checkstyle.api.FileText;
34 import com.puppycrawl.tools.checkstyle.xpath.XpathQueryGenerator;
35
36
37
38
39
40 public final class SuppressionsStringPrinter {
41
42
43 private static final Pattern VALID_SUPPRESSION_LINE_COLUMN_NUMBER_REGEX =
44 Pattern.compile("^(\\d+):(\\d+)$");
45
46
47 private static final String LINE_SEPARATOR = System.getProperty("line.separator");
48
49
50 private SuppressionsStringPrinter() {
51
52 }
53
54
55
56
57
58
59
60
61
62
63
64
65 public static String printSuppressions(File file, String suppressionLineColumnNumber,
66 int tabWidth) throws IOException, CheckstyleException {
67 final Matcher matcher =
68 VALID_SUPPRESSION_LINE_COLUMN_NUMBER_REGEX.matcher(suppressionLineColumnNumber);
69 if (!matcher.matches()) {
70 final String exceptionMsg = String.format(Locale.ROOT,
71 "%s does not match valid format 'line:column'.",
72 suppressionLineColumnNumber);
73 throw new IllegalStateException(exceptionMsg);
74 }
75
76 final FileText fileText = new FileText(file.getAbsoluteFile(),
77 System.getProperty("file.encoding", StandardCharsets.UTF_8.name()));
78 final DetailAST detailAST =
79 JavaParser.parseFileText(fileText, JavaParser.Options.WITH_COMMENTS);
80 final int lineNumber = Integer.parseInt(matcher.group(1));
81 final int columnNumber = Integer.parseInt(matcher.group(2));
82 return generate(fileText, detailAST, lineNumber, columnNumber, tabWidth);
83 }
84
85
86
87
88
89
90
91
92
93
94
95 private static String generate(FileText fileText, DetailAST detailAST, int lineNumber,
96 int columnNumber, int tabWidth) {
97 final XpathQueryGenerator queryGenerator =
98 new XpathQueryGenerator(detailAST, lineNumber, columnNumber, fileText,
99 tabWidth);
100 final List<String> suppressions = queryGenerator.generate();
101 return suppressions.stream().collect(Collectors.joining(LINE_SEPARATOR,
102 "", LINE_SEPARATOR));
103 }
104 }