001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
055 * </p>
056 * <p>
057 * Violation Message Keys:
058 * </p>
059 * <ul>
060 * <li>
061 * {@code mismatch.package.directory}
062 * </li>
063 * <li>
064 * {@code missing.package.declaration}
065 * </li>
066 * </ul>
067 *
068 * @since 3.2
069 */
070@FileStatefulCheck
071public final class PackageDeclarationCheck extends AbstractCheck {
072
073    /**
074     * A key is pointing to the warning message text in "messages.properties"
075     * file.
076     */
077    public static final String MSG_KEY_MISSING = "missing.package.declaration";
078
079    /**
080     * A key is pointing to the warning message text in "messages.properties"
081     * file.
082     */
083    public static final String MSG_KEY_MISMATCH = "mismatch.package.directory";
084
085    /** Is package defined. */
086    private boolean defined;
087
088    /** Control whether to check for directory and package name match. */
089    private boolean matchDirectoryStructure = true;
090
091    /**
092     * Setter to control whether to check for directory and package name match.
093     *
094     * @param matchDirectoryStructure the new value.
095     * @since 7.6.1
096     */
097    public void setMatchDirectoryStructure(boolean matchDirectoryStructure) {
098        this.matchDirectoryStructure = matchDirectoryStructure;
099    }
100
101    @Override
102    public int[] getDefaultTokens() {
103        return getRequiredTokens();
104    }
105
106    @Override
107    public int[] getRequiredTokens() {
108        return new int[] {TokenTypes.PACKAGE_DEF};
109    }
110
111    @Override
112    public int[] getAcceptableTokens() {
113        return getRequiredTokens();
114    }
115
116    @Override
117    public void beginTree(DetailAST ast) {
118        defined = false;
119    }
120
121    @Override
122    public void finishTree(DetailAST ast) {
123        if (!defined && ast != null) {
124            log(ast, MSG_KEY_MISSING);
125        }
126    }
127
128    @Override
129    public void visitToken(DetailAST ast) {
130        defined = true;
131
132        if (matchDirectoryStructure) {
133            final DetailAST packageNameAst = ast.getLastChild().getPreviousSibling();
134            final FullIdent fullIdent = FullIdent.createFullIdent(packageNameAst);
135            final String packageName = fullIdent.getText().replace('.', File.separatorChar);
136
137            final String directoryName = getDirectoryName();
138
139            if (!directoryName.endsWith(packageName)) {
140                log(ast, MSG_KEY_MISMATCH, packageName);
141            }
142        }
143    }
144
145    /**
146     * Returns the directory name this file is in.
147     *
148     * @return Directory name.
149     */
150    private String getDirectoryName() {
151        final String fileName = getFilePath();
152        final int lastSeparatorPos = fileName.lastIndexOf(File.separatorChar);
153        return fileName.substring(0, lastSeparatorPos);
154    }
155
156}