View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.coding;
21  
22  import java.io.File;
23  
24  import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
25  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
26  import com.puppycrawl.tools.checkstyle.api.DetailAST;
27  import com.puppycrawl.tools.checkstyle.api.FullIdent;
28  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
29  
30  /**
31   * <p>
32   * Ensures that a class has a package declaration, and (optionally) whether
33   * the package name matches the directory name for the source file.
34   * </p>
35   * <p>
36   * Rationale: Classes that live in the null package cannot be imported.
37   * Many novice developers are not aware of this.
38   * </p>
39   * <p>
40   * Packages provide logical namespace to classes and should be stored in
41   * the form of directory levels to provide physical grouping to your classes.
42   * These directories are added to the classpath so that your classes
43   * are visible to JVM when it runs the code.
44   * </p>
45   * <ul>
46   * <li>
47   * Property {@code matchDirectoryStructure} - Control whether to check for
48   * directory and package name match.
49   * Type is {@code boolean}.
50   * Default value is {@code true}.
51   * </li>
52   * </ul>
53   * <p>
54   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
55   * </p>
56   * <p>
57   * Violation Message Keys:
58   * </p>
59   * <ul>
60   * <li>
61   * {@code mismatch.package.directory}
62   * </li>
63   * <li>
64   * {@code missing.package.declaration}
65   * </li>
66   * </ul>
67   *
68   * @since 3.2
69   */
70  @FileStatefulCheck
71  public final class PackageDeclarationCheck extends AbstractCheck {
72  
73      /**
74       * A key is pointing to the warning message text in "messages.properties"
75       * file.
76       */
77      public static final String MSG_KEY_MISSING = "missing.package.declaration";
78  
79      /**
80       * A key is pointing to the warning message text in "messages.properties"
81       * file.
82       */
83      public static final String MSG_KEY_MISMATCH = "mismatch.package.directory";
84  
85      /** Is package defined. */
86      private boolean defined;
87  
88      /** Control whether to check for directory and package name match. */
89      private boolean matchDirectoryStructure = true;
90  
91      /**
92       * Setter to control whether to check for directory and package name match.
93       *
94       * @param matchDirectoryStructure the new value.
95       * @since 7.6.1
96       */
97      public void setMatchDirectoryStructure(boolean matchDirectoryStructure) {
98          this.matchDirectoryStructure = matchDirectoryStructure;
99      }
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 }