001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.BitSet;
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;
032import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
033
034/**
035 * <div>
036 * Checks the header of a source file against a header that contains a
037 * <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html">
038 * pattern</a> for each line of the source header.
039 * </div>
040 *
041 * @since 3.2
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    /** Regex pattern for a blank line. **/
059    private static final String EMPTY_LINE_PATTERN = "^$";
060
061    /** Compiled regex pattern for a blank line. **/
062    private static final Pattern BLANK_LINE = Pattern.compile(EMPTY_LINE_PATTERN);
063
064    /** The compiled regular expressions. */
065    private final List<Pattern> headerRegexps = new ArrayList<>();
066
067    /** Specify the line numbers to repeat (zero or more times). */
068    private BitSet multiLines = new BitSet();
069
070    /**
071     * Creates a new {@code RegexpHeaderCheck} instance.
072     */
073    public RegexpHeaderCheck() {
074        // no code by default
075    }
076
077    /**
078     * Setter to specify the line numbers to repeat (zero or more times).
079     *
080     * @param list line numbers to repeat in header.
081     * @since 3.4
082     */
083    public void setMultiLines(int... list) {
084        multiLines = TokenUtil.asBitSet(list);
085    }
086
087    @Override
088    protected void processFiltered(File file, FileText fileText) {
089        final int headerSize = getHeaderLines().size();
090        final int fileSize = fileText.size();
091
092        if (headerSize - multiLines.cardinality() > fileSize) {
093            log(1, MSG_HEADER_MISSING);
094        }
095        else {
096            int headerLineNo = 0;
097            int index;
098            for (index = 0; headerLineNo < headerSize && index < fileSize; index++) {
099                final String line = fileText.get(index);
100                boolean isMatch = isMatch(line, headerLineNo);
101                while (!isMatch && isMultiLine(headerLineNo)) {
102                    headerLineNo++;
103                    isMatch = headerLineNo == headerSize
104                            || isMatch(line, headerLineNo);
105                }
106                if (!isMatch) {
107                    log(index + 1, MSG_HEADER_MISMATCH, getHeaderLine(headerLineNo));
108                    break;
109                }
110                if (!isMultiLine(headerLineNo)) {
111                    headerLineNo++;
112                }
113            }
114            if (index == fileSize) {
115                // if file finished, but we have at least one non-multi-line
116                // header isn't completed
117                logFirstSinglelineLine(headerLineNo, headerSize);
118            }
119        }
120    }
121
122    /**
123     * Returns the line from the header. Where the line is blank return the regexp pattern
124     * for a blank line.
125     *
126     * @param headerLineNo header line number to return
127     * @return the line from the header
128     */
129    private String getHeaderLine(int headerLineNo) {
130        String line = getHeaderLines().get(headerLineNo);
131        if (line.isEmpty()) {
132            line = EMPTY_LINE_PATTERN;
133        }
134        return line;
135    }
136
137    /**
138     * Logs warning if any non-multiline lines left in header regexp.
139     *
140     * @param startHeaderLine header line number to start from
141     * @param headerSize whole header size
142     */
143    private void logFirstSinglelineLine(int startHeaderLine, int headerSize) {
144        for (int lineNum = startHeaderLine; lineNum < headerSize; lineNum++) {
145            if (!isMultiLine(lineNum)) {
146                log(1, MSG_HEADER_MISSING);
147                break;
148            }
149        }
150    }
151
152    /**
153     * Checks if a code line matches the required header line.
154     *
155     * @param line the code line
156     * @param headerLineNo the header line number.
157     * @return true if and only if the line matches the required header line.
158     */
159    private boolean isMatch(String line, int headerLineNo) {
160        return headerRegexps.get(headerLineNo).matcher(line).find();
161    }
162
163    /**
164     * Returns true if line is multiline header lines or false.
165     *
166     * @param lineNo a line number
167     * @return if {@code lineNo} is one of the repeat header lines.
168     */
169    private boolean isMultiLine(int lineNo) {
170        return multiLines.get(lineNo + 1);
171    }
172
173    @Override
174    protected void postProcessHeaderLines() {
175        final List<String> headerLines = getHeaderLines();
176        for (String line : headerLines) {
177            try {
178                if (line.isEmpty()) {
179                    headerRegexps.add(BLANK_LINE);
180                }
181                else {
182                    headerRegexps.add(Pattern.compile(line));
183                }
184            }
185            catch (final PatternSyntaxException exc) {
186                throw new IllegalArgumentException("line "
187                        + (headerRegexps.size() + 1)
188                        + " in header specification"
189                        + " is not a regular expression", exc);
190            }
191        }
192    }
193
194    /**
195     * Setter to define the required header specified inline.
196     * Individual header lines must be separated by the string {@code "\n"}
197     * (even on platforms with a different line separator).
198     * For header lines containing {@code "\n\n"} checkstyle will forcefully
199     * expect an empty line to exist. See examples below.
200     * Regular expressions must not span multiple lines.
201     *
202     * @param header the header value to validate and set (in that order)
203     * @since 5.0
204     */
205    @Override
206    public void setHeader(String header) {
207        if (!CommonUtil.isBlank(header)) {
208            if (!CommonUtil.isPatternValid(header)) {
209                throw new IllegalArgumentException("Unable to parse format: " + header);
210            }
211            super.setHeader(header);
212        }
213    }
214
215}