001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 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.CommonUtil;
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 */
041@StatelessCheck
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    /** Regex pattern for a blank line. **/
060    private static final String EMPTY_LINE_PATTERN = "^$";
061
062    /** Compiled regex pattern for a blank line. **/
063    private static final Pattern BLANK_LINE = Pattern.compile(EMPTY_LINE_PATTERN);
064
065    /** The compiled regular expressions. */
066    private final List<Pattern> headerRegexps = new ArrayList<>();
067
068    /** The header lines to repeat (0 or more) in the check, sorted. */
069    private int[] multiLines = EMPTY_INT_ARRAY;
070
071    /**
072     * Set the lines numbers to repeat in the header check.
073     * @param list comma separated list of line numbers to repeat in header.
074     */
075    public void setMultiLines(int... list) {
076        if (list.length == 0) {
077            multiLines = EMPTY_INT_ARRAY;
078        }
079        else {
080            multiLines = new int[list.length];
081            System.arraycopy(list, 0, multiLines, 0, list.length);
082            Arrays.sort(multiLines);
083        }
084    }
085
086    @Override
087    protected void processFiltered(File file, FileText fileText) {
088        final int headerSize = getHeaderLines().size();
089        final int fileSize = fileText.size();
090
091        if (headerSize - multiLines.length > fileSize) {
092            log(1, MSG_HEADER_MISSING);
093        }
094        else {
095            int headerLineNo = 0;
096            int index;
097            for (index = 0; headerLineNo < headerSize && index < fileSize; index++) {
098                final String line = fileText.get(index);
099                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}