001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2023 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.coding;
021
022import java.io.File;
023
024import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
025import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
026import com.puppycrawl.tools.checkstyle.api.DetailAST;
027import com.puppycrawl.tools.checkstyle.api.FullIdent;
028import com.puppycrawl.tools.checkstyle.api.TokenTypes;
029
030/**
031 * <p>
032 * Ensures that a class has a package declaration, and (optionally) whether
033 * the package name matches the directory name for the source file.
034 * </p>
035 * <p>
036 * Rationale: Classes that live in the null package cannot be imported.
037 * Many novice developers are not aware of this.
038 * </p>
039 * <p>
040 * Packages provide logical namespace to classes and should be stored in
041 * the form of directory levels to provide physical grouping to your classes.
042 * These directories are added to the classpath so that your classes
043 * are visible to JVM when it runs the code.
044 * </p>
045 * <ul>
046 * <li>
047 * Property {@code matchDirectoryStructure} - Control whether to check for
048 * directory and package name match.
049 * Type is {@code boolean}.
050 * Default value is {@code true}.
051 * </li>
052 * </ul>
053 * <p>
054 * To configure the check:
055 * </p>
056 * <pre>
057 * &lt;module name=&quot;PackageDeclaration&quot;/&gt;
058 * </pre>
059 * <p>
060 * Let us consider the class AnnotationLocationCheck which is in the directory
061 * /com/puppycrawl/tools/checkstyle/checks/annotations/
062 * </p>
063 * <pre>
064 * package com.puppycrawl.tools.checkstyle.checks; //Violation
065 * public class AnnotationLocationCheck extends AbstractCheck {
066 *   //...
067 * }
068 * </pre>
069 * <p>
070 * Example of how the check works when matchDirectoryStructure option is set to false.
071 * Let us again consider the AnnotationLocationCheck class located at directory
072 * /com/puppycrawl/tools/checkstyle/checks/annotations/ along with the following setup,
073 * </p>
074 * <pre>
075 * &lt;module name=&quot;PackageDeclaration&quot;&gt;
076 * &lt;property name=&quot;matchDirectoryStructure&quot; value=&quot;false&quot;/&gt;
077 * &lt;/module&gt;
078 * </pre>
079 * <pre>
080 * package com.puppycrawl.tools.checkstyle.checks;  //No Violation
081 *
082 * public class AnnotationLocationCheck extends AbstractCheck {
083 *   //...
084 * }
085 * </pre>
086 * <p>
087 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
088 * </p>
089 * <p>
090 * Violation Message Keys:
091 * </p>
092 * <ul>
093 * <li>
094 * {@code mismatch.package.directory}
095 * </li>
096 * <li>
097 * {@code missing.package.declaration}
098 * </li>
099 * </ul>
100 *
101 * @since 3.2
102 */
103@FileStatefulCheck
104public final class PackageDeclarationCheck extends AbstractCheck {
105
106    /**
107     * A key is pointing to the warning message text in "messages.properties"
108     * file.
109     */
110    public static final String MSG_KEY_MISSING = "missing.package.declaration";
111
112    /**
113     * A key is pointing to the warning message text in "messages.properties"
114     * file.
115     */
116    public static final String MSG_KEY_MISMATCH = "mismatch.package.directory";
117
118    /** Is package defined. */
119    private boolean defined;
120
121    /** Control whether to check for directory and package name match. */
122    private boolean matchDirectoryStructure = true;
123
124    /**
125     * Setter to control whether to check for directory and package name match.
126     *
127     * @param matchDirectoryStructure the new value.
128     */
129    public void setMatchDirectoryStructure(boolean matchDirectoryStructure) {
130        this.matchDirectoryStructure = matchDirectoryStructure;
131    }
132
133    @Override
134    public int[] getDefaultTokens() {
135        return getRequiredTokens();
136    }
137
138    @Override
139    public int[] getRequiredTokens() {
140        return new int[] {TokenTypes.PACKAGE_DEF};
141    }
142
143    @Override
144    public int[] getAcceptableTokens() {
145        return getRequiredTokens();
146    }
147
148    @Override
149    public void beginTree(DetailAST ast) {
150        defined = false;
151    }
152
153    @Override
154    public void finishTree(DetailAST ast) {
155        if (!defined && ast != null) {
156            log(ast, MSG_KEY_MISSING);
157        }
158    }
159
160    @Override
161    public void visitToken(DetailAST ast) {
162        defined = true;
163
164        if (matchDirectoryStructure) {
165            final DetailAST packageNameAst = ast.getLastChild().getPreviousSibling();
166            final FullIdent fullIdent = FullIdent.createFullIdent(packageNameAst);
167            final String packageName = fullIdent.getText().replace('.', File.separatorChar);
168
169            final String directoryName = getDirectoryName();
170
171            if (!directoryName.endsWith(packageName)) {
172                log(ast, MSG_KEY_MISMATCH, packageName);
173            }
174        }
175    }
176
177    /**
178     * Returns the directory name this file is in.
179     *
180     * @return Directory name.
181     */
182    private String getDirectoryName() {
183        final String fileName = getFilePath();
184        final int lastSeparatorPos = fileName.lastIndexOf(File.separatorChar);
185        return fileName.substring(0, lastSeparatorPos);
186    }
187
188}