001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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.Arrays;
024
025import com.puppycrawl.tools.checkstyle.StatelessCheck;
026import com.puppycrawl.tools.checkstyle.api.FileText;
027
028/**
029 * <p>
030 * Checks that a source file begins with a specified header.
031 * Property {@code headerFile} specifies a file that contains the required header.
032 * Alternatively, the header specification can be set directly in the
033 * {@code header} property without the need for an external file.
034 * </p>
035 * <p>
036 * Property {@code ignoreLines} specifies the line numbers to ignore when matching
037 * lines in a header file. This property is very useful for supporting headers
038 * that contain copyright dates. For example, consider the following header:
039 * </p>
040 * <pre>
041 * line 1: ////////////////////////////////////////////////////////////////////
042 * line 2: // checkstyle:
043 * line 3: // Checks Java source code for adherence to a set of rules.
044 * line 4: // Copyright (C) 2002  Oliver Burn
045 * line 5: ////////////////////////////////////////////////////////////////////
046 * </pre>
047 * <p>
048 * Since the year information will change over time, you can tell Checkstyle
049 * to ignore line 4 by setting property {@code ignoreLines} to {@code 4}.
050 * </p>
051 * <p>
052 * In default configuration, if header is not specified, the default value
053 * of header is set to {@code null} and the check does not rise any violations.
054 * </p>
055 * <ul>
056 * <li>
057 * Property {@code headerFile} - Specify the name of the file containing the required header.
058 * Default value is {@code null}.
059 * </li>
060 * <li>
061 * Property {@code charset} - Specify the character encoding to use when reading the headerFile.
062 * Default value is the charset property of the parent
063 * <a href="https://checkstyle.org/config.html#Checker">Checker</a> module.
064 * </li>
065 * <li>
066 * Property {@code header} - Specify the required header specified inline.
067 * Individual header lines must be separated by the string {@code "\n"}
068 * (even on platforms with a different line separator), see examples below.
069 * Default value is {@code null}.
070 * </li>
071 * <li>
072 * Property {@code ignoreLines} - Specify the line numbers to ignore.
073 * Default value is {@code {}}.
074 * </li>
075 * <li>
076 * Property {@code fileExtensions} - Specify the file type extension of files to process.
077 * Default value is {@code all files}.
078 * </li>
079 * </ul>
080 * <p>
081 * In default configuration the check does not rise any violations.
082 * Default values of properties are used.
083 * </p>
084 * <pre>
085 * &lt;module name="Header"/&gt;
086 * </pre>
087 * <p>
088 * To configure the check to use header file {@code "config/java.header"}
089 * and ignore lines {@code 2}, {@code 3}, and {@code 4} and only process Java files:
090 * </p>
091 * <pre>
092 * &lt;module name="Header"&gt;
093 *   &lt;property name="headerFile" value="config/java.header"/&gt;
094 *   &lt;property name="ignoreLines" value="2, 3, 4"/&gt;
095 *   &lt;property name="fileExtensions" value="java"/&gt;
096 * &lt;/module&gt;
097 * </pre>
098 * <p>
099 * To configure the check to verify that each file starts with the header
100 * </p>
101 * <pre>
102 * // Copyright (C) 2004 MyCompany
103 * // All rights reserved
104 * </pre>
105 * <p>
106 * without the need for an external header file:
107 * </p>
108 * <pre>
109 * &lt;module name="Header"&gt;
110 *   &lt;property name="header"
111 *     value="// Copyright (C) 2004 MyCompany\n// All rights reserved"/&gt;
112 * &lt;/module&gt;
113 * </pre>
114 *
115 * @since 6.9
116 */
117@StatelessCheck
118public class HeaderCheck extends AbstractHeaderCheck {
119
120    /**
121     * A key is pointing to the warning message text in "messages.properties"
122     * file.
123     */
124    public static final String MSG_MISSING = "header.missing";
125
126    /**
127     * A key is pointing to the warning message text in "messages.properties"
128     * file.
129     */
130    public static final String MSG_MISMATCH = "header.mismatch";
131
132    /** Empty array to avoid instantiations. */
133    private static final int[] EMPTY_INT_ARRAY = new int[0];
134
135    /** Specify the line numbers to ignore. */
136    private int[] ignoreLines = EMPTY_INT_ARRAY;
137
138    /**
139     * Returns true if lineNo is header lines or false.
140     * @param lineNo a line number
141     * @return if {@code lineNo} is one of the ignored header lines.
142     */
143    private boolean isIgnoreLine(int lineNo) {
144        return Arrays.binarySearch(ignoreLines, lineNo) >= 0;
145    }
146
147    /**
148     * Checks if a code line matches the required header line.
149     * @param lineNumber the line number to check against the header
150     * @param line the line contents
151     * @return true if and only if the line matches the required header line
152     */
153    private boolean isMatch(int lineNumber, String line) {
154        // skip lines we are meant to ignore
155        return isIgnoreLine(lineNumber + 1)
156            || getHeaderLines().get(lineNumber).equals(line);
157    }
158
159    /**
160     * Setter to specify the line numbers to ignore.
161     *
162     * @param list comma separated list of line numbers to ignore in header.
163     */
164    public void setIgnoreLines(int... list) {
165        if (list.length == 0) {
166            ignoreLines = EMPTY_INT_ARRAY;
167        }
168        else {
169            ignoreLines = new int[list.length];
170            System.arraycopy(list, 0, ignoreLines, 0, list.length);
171            Arrays.sort(ignoreLines);
172        }
173    }
174
175    @Override
176    protected void processFiltered(File file, FileText fileText) {
177        if (getHeaderLines().size() > fileText.size()) {
178            log(1, MSG_MISSING);
179        }
180        else {
181            for (int i = 0; i < getHeaderLines().size(); i++) {
182                if (!isMatch(i, fileText.get(i))) {
183                    log(i + 1, MSG_MISMATCH, getHeaderLines().get(i));
184                    break;
185                }
186            }
187        }
188    }
189
190    @Override
191    protected void postProcessHeaderLines() {
192        // no code
193    }
194
195}