88import java .nio .file .InvalidPathException ;
99import java .nio .file .Path ;
1010import javax .annotation .Nullable ;
11+ import org .slf4j .Logger ;
12+ import org .slf4j .LoggerFactory ;
1113
1214public class PackageResolverImpl implements PackageResolver {
1315
16+ private static final Logger log = LoggerFactory .getLogger (PackageResolverImpl .class );
17+
1418 private static final String PACKAGE_KEYWORD = "package" ;
1519 private final FileSystem fileSystem ;
1620
@@ -33,6 +37,7 @@ public PackageResolverImpl(FileSystem fileSystem) {
3337 @ Nullable
3438 @ Override
3539 public Path getPackage (Path sourceFile ) throws IOException {
40+ Language language = Language .getByFileName (sourceFile .getFileName ().toString ());
3641 Path folder = sourceFile .getParent ();
3742 try (BufferedReader br = Files .newBufferedReader (sourceFile )) {
3843 String line ;
@@ -42,6 +47,13 @@ public Path getPackage(Path sourceFile) throws IOException {
4247 continue ;
4348 }
4449
50+ int charAfterPackageKeyword = packageDeclarationStart + PACKAGE_KEYWORD .length ();
51+ if (charAfterPackageKeyword >= line .length ()
52+ || !Character .isWhitespace (line .charAt (charAfterPackageKeyword ))) {
53+ // "package" keyword is not followed by a whitespace
54+ continue ;
55+ }
56+
4557 int lineLength = line .length ();
4658 int packageNameStart = packageDeclarationStart + PACKAGE_KEYWORD .length ();
4759 while (packageNameStart < lineLength
@@ -51,18 +63,21 @@ public Path getPackage(Path sourceFile) throws IOException {
5163
5264 int packageNameEnd = line .indexOf (';' , packageNameStart );
5365 if (packageNameEnd == -1 ) {
54- packageNameEnd = lineLength ; // no ';' is possible if this is a Groovy file
66+ packageNameEnd = lineLength ; // possible if this is a non-Java (e.g. Groovy, Scala) file
5567 }
5668
5769 String packageName = line .substring (packageNameStart , packageNameEnd );
5870 Path packagePath ;
5971 try {
6072 packagePath = fileSystem .getPath (packageName .replace ('.' , File .separatorChar ));
6173 } catch (InvalidPathException e ) {
74+ log .debug ("Invalid package {} found for source file {}" , packageName , sourceFile , e );
6275 continue ;
6376 }
6477
65- if (folder .endsWith (packagePath )) {
78+ // we only do the "sanity check" for Java, as with the other languages
79+ // it is possible to have package that does not correspond to folder
80+ if (language != Language .JAVA || folder .endsWith (packagePath )) {
6681 return packagePath ;
6782 }
6883 }
0 commit comments