001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.header;
021
022import java.io.File;
023import java.util.ArrayList;
024import java.util.Arrays;
025import java.util.List;
026import java.util.regex.Pattern;
027import java.util.regex.PatternSyntaxException;
028
029import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
030
031/**
032 * Checks the header of the source against a header file that contains a
033 * {@link Pattern regular expression}
034 * for each line of the source header. In default configuration,
035 * if header is not specified, the default value of header is set to null
036 * and the check does not rise any violations.
037 *
038 * @author Lars Kühne
039 * @author o_sukhodolsky
040 */
041public class RegexpHeaderCheck extends AbstractHeaderCheck {
042
043    /**
044     * A key is pointing to the warning message text in "messages.properties"
045     * file.
046     */
047    public static final String MSG_HEADER_MISSING = "header.missing";
048
049    /**
050     * A key is pointing to the warning message text in "messages.properties"
051     * file.
052     */
053    public static final String MSG_HEADER_MISMATCH = "header.mismatch";
054
055    /** Empty array to avoid instantiations. */
056    private static final int[] EMPTY_INT_ARRAY = new int[0];
057
058    /** The compiled regular expressions. */
059    private final List<Pattern> headerRegexps = new ArrayList<>();
060
061    /** The header lines to repeat (0 or more) in the check, sorted. */
062    private int[] multiLines = EMPTY_INT_ARRAY;
063
064    /**
065     * Set the lines numbers to repeat in the header check.
066     * @param list comma separated list of line numbers to repeat in header.
067     */
068    public void setMultiLines(int... list) {
069        if (list.length == 0) {
070            multiLines = EMPTY_INT_ARRAY;
071        }
072        else {
073            multiLines = new int[list.length];
074            System.arraycopy(list, 0, multiLines, 0, list.length);
075            Arrays.sort(multiLines);
076        }
077    }
078
079    @Override
080    protected void processFiltered(File file, List<String> lines) {
081        final int headerSize = getHeaderLines().size();
082        final int fileSize = lines.size();
083
084        if (headerSize - multiLines.length > fileSize) {
085            log(1, MSG_HEADER_MISSING);
086        }
087        else {
088            int headerLineNo = 0;
089            int index;
090            for (index = 0; headerLineNo < headerSize && index < fileSize; index++) {
091                final String line = lines.get(index);
092                boolean isMatch = isMatch(line, headerLineNo);
093                while (!isMatch && isMultiLine(headerLineNo)) {
094                    headerLineNo++;
095                    isMatch = headerLineNo == headerSize
096                            || isMatch(line, headerLineNo);
097                }
098                if (!isMatch) {
099                    log(index + 1, MSG_HEADER_MISMATCH, getHeaderLines().get(
100                            headerLineNo));
101                    break;
102                }
103                if (!isMultiLine(headerLineNo)) {
104                    headerLineNo++;
105                }
106            }
107            if (index == fileSize) {
108                // if file finished, but we have at least one non-multi-line
109                // header isn't completed
110                logFirstSinglelineLine(headerLineNo, headerSize);
111            }
112        }
113    }
114
115    /**
116     * Logs warning if any non-multiline lines left in header regexp.
117     * @param startHeaderLine header line number to start from
118     * @param headerSize whole header size
119     */
120    private void logFirstSinglelineLine(int startHeaderLine, int headerSize) {
121        for (int lineNum = startHeaderLine; lineNum < headerSize; lineNum++) {
122            if (!isMultiLine(lineNum)) {
123                log(1, MSG_HEADER_MISSING);
124                break;
125            }
126        }
127    }
128
129    /**
130     * Checks if a code line matches the required header line.
131     * @param line the code line
132     * @param headerLineNo the header line number.
133     * @return true if and only if the line matches the required header line.
134     */
135    private boolean isMatch(String line, int headerLineNo) {
136        return headerRegexps.get(headerLineNo).matcher(line).find();
137    }
138
139    /**
140     * Returns true if line is multiline header lines or false.
141     * @param lineNo a line number
142     * @return if {@code lineNo} is one of the repeat header lines.
143     */
144    private boolean isMultiLine(int lineNo) {
145        return Arrays.binarySearch(multiLines, lineNo + 1) >= 0;
146    }
147
148    @Override
149    protected void postProcessHeaderLines() {
150        final List<String> headerLines = getHeaderLines();
151        headerRegexps.clear();
152        for (String line : headerLines) {
153            try {
154                headerRegexps.add(Pattern.compile(line));
155            }
156            catch (final PatternSyntaxException ex) {
157                throw new IllegalArgumentException("line "
158                        + (headerRegexps.size() + 1)
159                        + " in header specification"
160                        + " is not a regular expression", ex);
161            }
162        }
163    }
164
165    /**
166     * Validates the {@code header} by compiling it with
167     * {@link Pattern#compile(String) } and throws
168     * {@link IllegalArgumentException} if {@code header} isn't a valid pattern.
169     * @param header the header value to validate and set (in that order)
170     */
171    @Override
172    public void setHeader(String header) {
173        if (!CommonUtils.isBlank(header)) {
174            if (!CommonUtils.isPatternValid(header)) {
175                throw new IllegalArgumentException("Unable to parse format: " + header);
176            }
177            super.setHeader(header);
178        }
179    }
180
181}