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.checks.header;
21
22 import java.util.Arrays;
23
24 import java.io.File;
25 import java.util.List;
26 import java.util.regex.Pattern;
27 import java.util.regex.PatternSyntaxException;
28
29 import org.apache.commons.beanutils.ConversionException;
30
31 import com.google.common.collect.Lists;
32 import com.puppycrawl.tools.checkstyle.api.Utils;
33
34
35
36
37
38
39
40
41
42 public class RegexpHeaderCheck extends AbstractHeaderCheck
43 {
44
45 private static final int[] EMPTY_INT_ARRAY = new int[0];
46
47
48 private final List<Pattern> headerRegexps = Lists.newArrayList();
49
50
51 private int[] multiLines = EMPTY_INT_ARRAY;
52
53
54
55
56
57 public void setMultiLines(int[] list)
58 {
59 if (list == null || list.length == 0) {
60 multiLines = EMPTY_INT_ARRAY;
61 return;
62 }
63
64 multiLines = new int[list.length];
65 System.arraycopy(list, 0, multiLines, 0, list.length);
66 Arrays.sort(multiLines);
67 }
68
69 @Override
70 protected void processFiltered(File file, List<String> lines)
71 {
72 final int headerSize = getHeaderLines().size();
73 final int fileSize = lines.size();
74
75 if (headerSize - multiLines.length > fileSize) {
76 log(1, "header.missing");
77 }
78 else {
79 int headerLineNo = 0;
80 int i;
81 for (i = 0; headerLineNo < headerSize && i < fileSize; i++) {
82 final String line = lines.get(i);
83 boolean isMatch = isMatch(line, headerLineNo);
84 while (!isMatch && isMultiLine(headerLineNo)) {
85 headerLineNo++;
86 isMatch = headerLineNo == headerSize
87 || isMatch(line, headerLineNo);
88 }
89 if (!isMatch) {
90 log(i + 1, "header.mismatch", getHeaderLines().get(
91 headerLineNo));
92 break;
93 }
94 if (!isMultiLine(headerLineNo)) {
95 headerLineNo++;
96 }
97 }
98 if (i == fileSize) {
99
100
101 for (; headerLineNo < headerSize; headerLineNo++) {
102 if (!isMultiLine(headerLineNo)) {
103 log(1, "header.missing");
104 break;
105 }
106 }
107 }
108 }
109 }
110
111
112
113
114
115
116
117 private boolean isMatch(String line, int headerLineNo)
118 {
119 return headerRegexps.get(headerLineNo).matcher(line).find();
120 }
121
122
123
124
125
126 private boolean isMultiLine(int lineNo)
127 {
128 return Arrays.binarySearch(multiLines, lineNo + 1) >= 0;
129 }
130
131 @Override
132 protected void postprocessHeaderLines()
133 {
134 final List<String> headerLines = getHeaderLines();
135 headerRegexps.clear();
136 for (String line : headerLines) {
137 try {
138
139 headerRegexps.add(Utils.getPattern(line));
140 }
141 catch (final PatternSyntaxException ex) {
142 throw new ConversionException("line "
143 + (headerRegexps.size() + 1)
144 + " in header specification"
145 + " is not a regular expression");
146 }
147 }
148 }
149
150 }