1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2019 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.header;
21  
22  import java.io.File;
23  import java.util.ArrayList;
24  import java.util.Arrays;
25  import java.util.List;
26  import java.util.regex.Pattern;
27  import java.util.regex.PatternSyntaxException;
28  
29  import com.puppycrawl.tools.checkstyle.StatelessCheck;
30  import com.puppycrawl.tools.checkstyle.api.FileText;
31  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
32  
33  /**
34   * Checks the header of the source against a header file that contains a
35   * {@link Pattern regular expression}
36   * for each line of the source header. In default configuration,
37   * if header is not specified, the default value of header is set to null
38   * and the check does not rise any violations.
39   *
40   */
41  @StatelessCheck
42  public class RegexpHeaderCheck extends AbstractHeaderCheck {
43  
44      /**
45       * A key is pointing to the warning message text in "messages.properties"
46       * file.
47       */
48      public static final String MSG_HEADER_MISSING = "header.missing";
49  
50      /**
51       * A key is pointing to the warning message text in "messages.properties"
52       * file.
53       */
54      public static final String MSG_HEADER_MISMATCH = "header.mismatch";
55  
56      /** Empty array to avoid instantiations. */
57      private static final int[] EMPTY_INT_ARRAY = new int[0];
58  
59      /** Regex pattern for a blank line. **/
60      private static final String EMPTY_LINE_PATTERN = "^$";
61  
62      /** Compiled regex pattern for a blank line. **/
63      private static final Pattern BLANK_LINE = Pattern.compile(EMPTY_LINE_PATTERN);
64  
65      /** The compiled regular expressions. */
66      private final List<Pattern> headerRegexps = new ArrayList<>();
67  
68      /** The header lines to repeat (0 or more) in the check, sorted. */
69      private int[] multiLines = EMPTY_INT_ARRAY;
70  
71      /**
72       * Set the lines numbers to repeat in the header check.
73       * @param list comma separated list of line numbers to repeat in header.
74       */
75      public void setMultiLines(int... list) {
76          if (list.length == 0) {
77              multiLines = EMPTY_INT_ARRAY;
78          }
79          else {
80              multiLines = new int[list.length];
81              System.arraycopy(list, 0, multiLines, 0, list.length);
82              Arrays.sort(multiLines);
83          }
84      }
85  
86      @Override
87      protected void processFiltered(File file, FileText fileText) {
88          final int headerSize = getHeaderLines().size();
89          final int fileSize = fileText.size();
90  
91          if (headerSize - multiLines.length > fileSize) {
92              log(1, MSG_HEADER_MISSING);
93          }
94          else {
95              int headerLineNo = 0;
96              int index;
97              for (index = 0; headerLineNo < headerSize && index < fileSize; index++) {
98                  final String line = fileText.get(index);
99                  boolean isMatch = isMatch(line, headerLineNo);
100                 while (!isMatch && isMultiLine(headerLineNo)) {
101                     headerLineNo++;
102                     isMatch = headerLineNo == headerSize
103                             || isMatch(line, headerLineNo);
104                 }
105                 if (!isMatch) {
106                     log(index + 1, MSG_HEADER_MISMATCH, getHeaderLine(headerLineNo));
107                     break;
108                 }
109                 if (!isMultiLine(headerLineNo)) {
110                     headerLineNo++;
111                 }
112             }
113             if (index == fileSize) {
114                 // if file finished, but we have at least one non-multi-line
115                 // header isn't completed
116                 logFirstSinglelineLine(headerLineNo, headerSize);
117             }
118         }
119     }
120 
121     /**
122      * Returns the line from the header. Where the line is blank return the regexp pattern
123      * for a blank line.
124      * @param headerLineNo header line number to return
125      * @return the line from the header
126      */
127     private String getHeaderLine(int headerLineNo) {
128         String line = getHeaderLines().get(headerLineNo);
129         if (line.isEmpty()) {
130             line = EMPTY_LINE_PATTERN;
131         }
132         return line;
133     }
134 
135     /**
136      * Logs warning if any non-multiline lines left in header regexp.
137      * @param startHeaderLine header line number to start from
138      * @param headerSize whole header size
139      */
140     private void logFirstSinglelineLine(int startHeaderLine, int headerSize) {
141         for (int lineNum = startHeaderLine; lineNum < headerSize; lineNum++) {
142             if (!isMultiLine(lineNum)) {
143                 log(1, MSG_HEADER_MISSING);
144                 break;
145             }
146         }
147     }
148 
149     /**
150      * Checks if a code line matches the required header line.
151      * @param line the code line
152      * @param headerLineNo the header line number.
153      * @return true if and only if the line matches the required header line.
154      */
155     private boolean isMatch(String line, int headerLineNo) {
156         return headerRegexps.get(headerLineNo).matcher(line).find();
157     }
158 
159     /**
160      * Returns true if line is multiline header lines or false.
161      * @param lineNo a line number
162      * @return if {@code lineNo} is one of the repeat header lines.
163      */
164     private boolean isMultiLine(int lineNo) {
165         return Arrays.binarySearch(multiLines, lineNo + 1) >= 0;
166     }
167 
168     @Override
169     protected void postProcessHeaderLines() {
170         final List<String> headerLines = getHeaderLines();
171         for (String line : headerLines) {
172             try {
173                 if (line.isEmpty()) {
174                     headerRegexps.add(BLANK_LINE);
175                 }
176                 else {
177                     headerRegexps.add(Pattern.compile(line));
178                 }
179             }
180             catch (final PatternSyntaxException ex) {
181                 throw new IllegalArgumentException("line "
182                         + (headerRegexps.size() + 1)
183                         + " in header specification"
184                         + " is not a regular expression", ex);
185             }
186         }
187     }
188 
189     /**
190      * Validates the {@code header} by compiling it with
191      * {@link Pattern#compile(String) } and throws
192      * {@link IllegalArgumentException} if {@code header} isn't a valid pattern.
193      * @param header the header value to validate and set (in that order)
194      */
195     @Override
196     public void setHeader(String header) {
197         if (!CommonUtil.isBlank(header)) {
198             if (!CommonUtil.isPatternValid(header)) {
199                 throw new IllegalArgumentException("Unable to parse format: " + header);
200             }
201             super.setHeader(header);
202         }
203     }
204 
205 }