forked from checkstyle/checkstyle
/
InlineConfigParser.java
342 lines (310 loc) · 15.2 KB
/
InlineConfigParser.java
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2021 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.bdd;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
public final class InlineConfigParser {
/** A pattern matching the symbol: "\" or "/". */
private static final Pattern SLASH_PATTERN = Pattern.compile("[\\\\/]");
/** A pattern to find the string: "// violation". */
private static final Pattern VIOLATION_PATTERN = Pattern
.compile(".*//\\s*violation(?:\\W+'(.*)')?$");
/** A pattern to find the string: "// violation above". */
private static final Pattern VIOLATION_ABOVE_PATTERN = Pattern
.compile(".*//\\s*violation above(?:\\W+'(.*)')?$");
/** A pattern to find the string: "// violation below". */
private static final Pattern VIOLATION_BELOW_PATTERN = Pattern
.compile(".*//\\s*violation below(?:\\W+'(.*)')?$");
/** A pattern to find the string: "// X violations". */
private static final Pattern MULTIPLE_VIOLATIONS_PATTERN = Pattern
.compile(".*//\\s*(\\d+) violations$");
/** A pattern to find the string: "// X violations above". */
private static final Pattern MULTIPLE_VIOLATIONS_ABOVE_PATTERN = Pattern
.compile(".*//\\s*(\\d+) violations above$");
/** A pattern to find the string: "// X violations below". */
private static final Pattern MULTIPLE_VIOLATIONS_BELOW_PATTERN = Pattern
.compile(".*//\\s*(\\d+) violations below$");
/** A pattern to find the string: "// filtered violation". */
private static final Pattern FILTERED_VIOLATION_PATTERN = Pattern
.compile(".*//\\s*filtered violation(?:\\W+'(.*)')?$");
/** A pattern to find the string: "// filtered violation above". */
private static final Pattern FILTERED_VIOLATION_ABOVE_PATTERN = Pattern
.compile(".*//\\s*filtered violation above(?:\\W+'(.*)')?$");
/** A pattern to find the string: "// filtered violation below". */
private static final Pattern FILTERED_VIOLATION_BELOW_PATTERN = Pattern
.compile(".*//\\s*filtered violation below(?:\\W+'(.*)')?$");
/** The String "(null)". */
private static final String NULL_STRING = "(null)";
/** Stop instances being created. **/
private InlineConfigParser() {
}
public static ModuleInputConfiguration parse(String inputFilePath) throws Exception {
return parse(inputFilePath, false);
}
/**
* Parses the input file provided.
*
* @param inputFilePath the input file path.
* @param setFilteredViolations flag to set filtered violations.
* @throws Exception if unable to read file or file not formatted properly.
*/
private static ModuleInputConfiguration parse(String inputFilePath,
boolean setFilteredViolations) throws Exception {
final Path filePath = Paths.get(inputFilePath);
final List<String> lines = readFile(filePath);
final ModuleInputConfiguration.Builder inputConfigBuilder =
new ModuleInputConfiguration.Builder();
setModuleName(inputConfigBuilder, inputFilePath, lines);
setProperties(inputConfigBuilder, inputFilePath, lines, 2);
setViolations(inputConfigBuilder, lines, setFilteredViolations);
return inputConfigBuilder.build();
}
public static ModuleInputConfiguration parseWithFilteredViolations(String inputFilePath)
throws Exception {
return parse(inputFilePath, true);
}
/**
* Parses the filter input file provided.
*
* @param inputFilePath the input file path.
* @throws Exception if unable to read file or file not formatted properly.
*/
public static ModuleInputConfiguration parseFilter(String inputFilePath)
throws Exception {
final Path filePath = Paths.get(inputFilePath);
final List<String> lines = readFile(filePath);
final ModuleInputConfiguration.Builder inputConfigBuilder =
new ModuleInputConfiguration.Builder();
final int lineNo = getFilterConfigLineNo(lines);
setFilterName(inputConfigBuilder, inputFilePath, lines, lineNo);
setProperties(inputConfigBuilder, inputFilePath, lines, lineNo + 1);
setViolations(inputConfigBuilder, lines, false);
return inputConfigBuilder.build();
}
private static String getFullyQualifiedClassName(String filePath, String moduleName) {
String fullyQualifiedClassName;
if (moduleName.startsWith("com.")) {
fullyQualifiedClassName = moduleName;
}
else {
final String path = SLASH_PATTERN.matcher(filePath).replaceAll("\\.");
final int beginIndex = path.indexOf("com.puppycrawl");
final int endIndex = path.lastIndexOf(moduleName.toLowerCase(Locale.ROOT));
fullyQualifiedClassName = path.substring(beginIndex, endIndex) + moduleName;
}
if (!fullyQualifiedClassName.endsWith("Filter")) {
fullyQualifiedClassName += "Check";
}
return fullyQualifiedClassName;
}
private static String getFilePath(String fileName, String inputFilePath) {
final int lastSlashIndex = Math.max(inputFilePath.lastIndexOf('\\'),
inputFilePath.lastIndexOf('/'));
final String root = inputFilePath.substring(0, lastSlashIndex + 1);
return root + fileName;
}
private static String getResourcePath(String fileName, String inputFilePath) {
final String filePath = getUriPath(fileName, inputFilePath);
final int lastSlashIndex = filePath.lastIndexOf('/');
final String root = filePath.substring(filePath.indexOf("puppycrawl") - 5,
lastSlashIndex + 1);
return root + fileName;
}
private static String getUriPath(String fileName, String inputFilePath) {
return new File(getFilePath(fileName, inputFilePath)).toURI().toString();
}
private static String getResolvedPath(String fileValue, String inputFilePath) {
final String resolvedFilePath;
if (fileValue.startsWith("(resource)")) {
resolvedFilePath =
getResourcePath(fileValue.substring(fileValue.indexOf(')') + 1),
inputFilePath);
}
else if (fileValue.startsWith("(uri)")) {
resolvedFilePath =
getUriPath(fileValue.substring(fileValue.indexOf(')') + 1), inputFilePath);
}
else {
resolvedFilePath = getFilePath(fileValue, inputFilePath);
}
return resolvedFilePath;
}
private static List<String> readFile(Path filePath) throws CheckstyleException {
try {
return Files.readAllLines(filePath);
}
catch (IOException ex) {
throw new CheckstyleException("Failed to read " + filePath, ex);
}
}
private static void setModuleName(ModuleInputConfiguration.Builder inputConfigBuilder,
String filePath, List<String> lines)
throws CheckstyleException {
if (lines.size() < 2) {
throw new CheckstyleException("Config not specified in " + filePath);
}
final String moduleName = lines.get(1);
final String fullyQualifiedClassName = getFullyQualifiedClassName(filePath, moduleName);
inputConfigBuilder.setModuleName(fullyQualifiedClassName);
}
private static int getFilterConfigLineNo(List<String> lines) {
int lineNo = 1;
while (!lines.get(lineNo - 1).isEmpty() || lines.get(lineNo).isEmpty()) {
lineNo++;
}
return lineNo;
}
private static void setFilterName(ModuleInputConfiguration.Builder inputConfigBuilder,
String filePath, List<String> lines, int lineNo)
throws CheckstyleException {
final String filterName = lines.get(lineNo);
if (!filterName.endsWith("Filter")) {
throw new CheckstyleException("Filter not specified in " + filePath);
}
final String fullyQualifiedClassName = getFullyQualifiedClassName(filePath, filterName);
inputConfigBuilder.setModuleName(fullyQualifiedClassName);
}
private static void setProperties(ModuleInputConfiguration.Builder inputConfigBuilder,
String inputFilePath,
List<String> lines,
int beginLineNo)
throws Exception {
final StringBuilder stringBuilder = new StringBuilder(128);
int lineNo = beginLineNo;
for (String line = lines.get(lineNo); !line.isEmpty() && !"*/".equals(line);
++lineNo, line = lines.get(lineNo)) {
stringBuilder.append(line).append('\n');
}
final Properties properties = new Properties();
try (Reader reader = new StringReader(stringBuilder.toString())) {
properties.load(reader);
}
for (final Map.Entry<Object, Object> entry : properties.entrySet()) {
final String key = entry.getKey().toString();
final String value = entry.getValue().toString();
if (key.startsWith("message.")) {
inputConfigBuilder.addModuleMessage(key.substring(8), value);
}
else if (value.startsWith("(file)")) {
final String fileName = value.substring(value.indexOf(')') + 1);
final String filePath = getResolvedPath(fileName, inputFilePath);
inputConfigBuilder.addNonDefaultProperty(key, filePath);
}
else if (value.startsWith("(default)")) {
final String defaultValue = value.substring(value.indexOf(')') + 1);
if (NULL_STRING.equals(defaultValue)) {
inputConfigBuilder.addDefaultProperty(key, null);
}
else {
inputConfigBuilder.addDefaultProperty(key, defaultValue);
}
}
else {
if (NULL_STRING.equals(value)) {
inputConfigBuilder.addNonDefaultProperty(key, null);
}
else {
inputConfigBuilder.addNonDefaultProperty(key, value);
}
}
}
}
private static void setViolations(ModuleInputConfiguration.Builder inputConfigBuilder,
List<String> lines, boolean useFilteredViolations) {
for (int lineNo = 0; lineNo < lines.size(); lineNo++) {
final Matcher violationMatcher =
VIOLATION_PATTERN.matcher(lines.get(lineNo));
final Matcher violationAboveMatcher =
VIOLATION_ABOVE_PATTERN.matcher(lines.get(lineNo));
final Matcher violationBelowMatcher =
VIOLATION_BELOW_PATTERN.matcher(lines.get(lineNo));
final Matcher multipleViolationsMatcher =
MULTIPLE_VIOLATIONS_PATTERN.matcher(lines.get(lineNo));
final Matcher multipleViolationsAboveMatcher =
MULTIPLE_VIOLATIONS_ABOVE_PATTERN.matcher(lines.get(lineNo));
final Matcher multipleViolationsBelowMatcher =
MULTIPLE_VIOLATIONS_BELOW_PATTERN.matcher(lines.get(lineNo));
if (violationMatcher.matches()) {
inputConfigBuilder.addViolation(lineNo + 1, violationMatcher.group(1));
}
else if (violationAboveMatcher.matches()) {
inputConfigBuilder.addViolation(lineNo, violationAboveMatcher.group(1));
}
else if (violationBelowMatcher.matches()) {
inputConfigBuilder.addViolation(lineNo + 2, violationBelowMatcher.group(1));
}
else if (multipleViolationsMatcher.matches()) {
Collections
.nCopies(Integer.parseInt(multipleViolationsMatcher.group(1)), lineNo + 1)
.forEach(actualLineNumber -> {
inputConfigBuilder.addViolation(actualLineNumber, null);
});
}
else if (multipleViolationsAboveMatcher.matches()) {
Collections
.nCopies(Integer.parseInt(multipleViolationsAboveMatcher.group(1)), lineNo)
.forEach(actualLineNumber -> {
inputConfigBuilder.addViolation(actualLineNumber, null);
});
}
else if (multipleViolationsBelowMatcher.matches()) {
Collections
.nCopies(Integer.parseInt(multipleViolationsBelowMatcher.group(1)),
lineNo + 2)
.forEach(actualLineNumber -> {
inputConfigBuilder.addViolation(actualLineNumber, null);
});
}
else if (useFilteredViolations) {
setFilteredViolation(inputConfigBuilder, lineNo + 1, lines.get(lineNo));
}
}
}
private static void setFilteredViolation(ModuleInputConfiguration.Builder inputConfigBuilder,
int lineNo, String line) {
final Matcher violationMatcher =
FILTERED_VIOLATION_PATTERN.matcher(line);
final Matcher violationAboveMatcher =
FILTERED_VIOLATION_ABOVE_PATTERN.matcher(line);
final Matcher violationBelowMatcher =
FILTERED_VIOLATION_BELOW_PATTERN.matcher(line);
if (violationMatcher.matches()) {
inputConfigBuilder.addViolation(lineNo, violationMatcher.group(1));
}
else if (violationAboveMatcher.matches()) {
inputConfigBuilder.addViolation(lineNo - 1, violationAboveMatcher.group(1));
}
else if (violationBelowMatcher.matches()) {
inputConfigBuilder.addViolation(lineNo + 1, violationBelowMatcher.group(1));
}
}
}