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