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.api.FileText;
030import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
031
032/**
033 * Checks the header of the source against a header file that contains a
034 * {@link Pattern regular expression}
035 * for each line of the source header. In default configuration,
036 * if header is not specified, the default value of header is set to null
037 * and the check does not rise any violations.
038 *
039 * @author Lars Kühne
040 * @author o_sukhodolsky
041 */
042public class RegexpHeaderCheck extends AbstractHeaderCheck {
043
044    /**
045     * A key is pointing to the warning message text in "messages.properties"
046     * file.
047     */
048    public static final String MSG_HEADER_MISSING = "header.missing";
049
050    /**
051     * A key is pointing to the warning message text in "messages.properties"
052     * file.
053     */
054    public static final String MSG_HEADER_MISMATCH = "header.mismatch";
055
056    /** Empty array to avoid instantiations. */
057    private static final int[] EMPTY_INT_ARRAY = new int[0];
058
059    /** The compiled regular expressions. */
060    private final List<Pattern> headerRegexps = new ArrayList<>();
061
062    /** The header lines to repeat (0 or more) in the check, sorted. */
063    private int[] multiLines = EMPTY_INT_ARRAY;
064
065    /**
066     * Set the lines numbers to repeat in the header check.
067     * @param list comma separated list of line numbers to repeat in header.
068     */
069    public void setMultiLines(int... list) {
070        if (list.length == 0) {
071            multiLines = EMPTY_INT_ARRAY;
072        }
073        else {
074            multiLines = new int[list.length];
075            System.arraycopy(list, 0, multiLines, 0, list.length);
076            Arrays.sort(multiLines);
077        }
078    }
079
080    @Override
081    protected void processFiltered(File file, FileText fileText) {
082        final int headerSize = getHeaderLines().size();
083        final int fileSize = fileText.size();
084
085        if (headerSize - multiLines.length > fileSize) {
086            log(1, MSG_HEADER_MISSING);
087        }
088        else {
089            int headerLineNo = 0;
090            int index;
091            for (index = 0; headerLineNo < headerSize && index < fileSize; index++) {
092                final String line = fileText.get(index);
093                boolean isMatch = isMatch(line, headerLineNo);
094                while (!isMatch && isMultiLine(headerLineNo)) {
095                    headerLineNo++;
096                    isMatch = headerLineNo == headerSize
097                            || isMatch(line, headerLineNo);
098                }
099                if (!isMatch) {
100                    log(index + 1, MSG_HEADER_MISMATCH, getHeaderLines().get(
101                            headerLineNo));
102                    break;
103                }
104                if (!isMultiLine(headerLineNo)) {
105                    headerLineNo++;
106                }
107            }
108            if (index == fileSize) {
109                // if file finished, but we have at least one non-multi-line
110                // header isn't completed
111                logFirstSinglelineLine(headerLineNo, headerSize);
112            }
113        }
114    }
115
116    /**
117     * Logs warning if any non-multiline lines left in header regexp.
118     * @param startHeaderLine header line number to start from
119     * @param headerSize whole header size
120     */
121    private void logFirstSinglelineLine(int startHeaderLine, int headerSize) {
122        for (int lineNum = startHeaderLine; lineNum < headerSize; lineNum++) {
123            if (!isMultiLine(lineNum)) {
124                log(1, MSG_HEADER_MISSING);
125                break;
126            }
127        }
128    }
129
130    /**
131     * Checks if a code line matches the required header line.
132     * @param line the code line
133     * @param headerLineNo the header line number.
134     * @return true if and only if the line matches the required header line.
135     */
136    private boolean isMatch(String line, int headerLineNo) {
137        return headerRegexps.get(headerLineNo).matcher(line).find();
138    }
139
140    /**
141     * Returns true if line is multiline header lines or false.
142     * @param lineNo a line number
143     * @return if {@code lineNo} is one of the repeat header lines.
144     */
145    private boolean isMultiLine(int lineNo) {
146        return Arrays.binarySearch(multiLines, lineNo + 1) >= 0;
147    }
148
149    @Override
150    protected void postProcessHeaderLines() {
151        final List<String> headerLines = getHeaderLines();
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}