Skip to content

Commit d45c9da

Browse files
authored
Fixes main class finding with external dependencies. (GoogleContainerTools#355)
1 parent 03d4265 commit d45c9da

9 files changed

Lines changed: 78 additions & 127 deletions

File tree

‎jib-core/build.gradle‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ dependencies {
3838
compile 'com.google.guava:guava:23.5-jre'
3939
compile 'com.fasterxml.jackson.core:jackson-databind:2.9.2'
4040
compile 'org.slf4j:slf4j-api:1.7.25'
41+
compile 'org.javassist:javassist:3.22.0-GA'
4142

4243
testCompile 'junit:junit:4.12'
4344
testCompile 'org.mockito:mockito-core:2.12.0'

‎jib-core/src/main/java/com/google/cloud/tools/jib/frontend/MainClassFinder.java‎

Lines changed: 51 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -21,87 +21,25 @@
2121
import com.google.cloud.tools.jib.filesystem.DirectoryWalker;
2222
import com.google.common.annotations.VisibleForTesting;
2323
import com.google.common.base.Preconditions;
24-
import com.google.common.base.Splitter;
2524
import java.io.IOException;
26-
import java.lang.reflect.Method;
25+
import java.io.InputStream;
2726
import java.lang.reflect.Modifier;
2827
import java.nio.file.Files;
2928
import java.nio.file.Path;
30-
import java.util.ArrayDeque;
3129
import java.util.ArrayList;
32-
import java.util.Deque;
33-
import java.util.HashMap;
30+
import java.util.Collections;
3431
import java.util.HashSet;
3532
import java.util.List;
36-
import java.util.Map;
3733
import java.util.Set;
34+
import javassist.ClassPool;
35+
import javassist.CtClass;
36+
import javassist.CtMethod;
37+
import javassist.NotFoundException;
3838
import javax.annotation.Nullable;
3939

4040
/** Infers the main class in an application. */
4141
public class MainClassFinder {
4242

43-
/** Helper for loading a .class file. */
44-
@VisibleForTesting
45-
static class ClassFileLoader extends ClassLoader {
46-
47-
private final Map<Path, Class<?>> definedClasses = new HashMap<>();
48-
private final Path rootDirectory;
49-
50-
@VisibleForTesting
51-
ClassFileLoader(Path rootDirectory) {
52-
this.rootDirectory = rootDirectory;
53-
}
54-
55-
@Nullable
56-
@Override
57-
public Class<?> findClass(String name) {
58-
return findClass(name, getPathFromClassName(name));
59-
}
60-
61-
/**
62-
* @param name the name of the class. This should be {@code null} when we call it manually with
63-
* a file, and not {@code null} when it is called internally.
64-
* @param file the .class file defining the class.
65-
* @return the {@link Class} defined by the file, or {@code null} if the class could not be
66-
* defined.
67-
*/
68-
@Nullable
69-
private Class<?> findClass(@Nullable String name, Path file) {
70-
if (definedClasses.containsKey(file)) {
71-
return definedClasses.get(file);
72-
}
73-
74-
if (!Files.exists(file)) {
75-
// TODO: Log search class failure?
76-
return null;
77-
}
78-
79-
try {
80-
byte[] bytes = Files.readAllBytes(file);
81-
Class<?> definedClass = defineClass(name, bytes, 0, bytes.length);
82-
definedClasses.put(file, definedClass);
83-
return definedClass;
84-
} catch (IOException | ClassFormatError | SecurityException | NoClassDefFoundError ignored) {
85-
// Not a valid class file
86-
// TODO: Log search class failure when NoClassDefFoundError/SecurityException is caught?
87-
return null;
88-
}
89-
}
90-
91-
/** Converts a class name (pack.ClassName) to a Path (rootDirectory/pack/ClassName.class). */
92-
@VisibleForTesting
93-
Path getPathFromClassName(String className) {
94-
Path path = rootDirectory;
95-
Deque<String> folders = new ArrayDeque<>(Splitter.on('.').splitToList(className));
96-
String fileName = folders.removeLast() + ".class";
97-
for (String folder : folders) {
98-
path = path.resolve(folder);
99-
}
100-
path = path.resolve(fileName);
101-
return path;
102-
}
103-
}
104-
10543
/**
10644
* If {@code mainClass} is {@code null}, tries to infer main class in this order:
10745
*
@@ -139,7 +77,7 @@ public static String resolveMainClass(
13977
continue;
14078
}
14179
visitedRoots.add(root);
142-
mainClasses.addAll(findMainClasses(root));
80+
mainClasses.addAll(findMainClasses(root, logger));
14381
}
14482

14583
if (mainClasses.size() == 1) {
@@ -177,47 +115,58 @@ public static String resolveMainClass(
177115
}
178116

179117
/**
180-
* Searches for a .class file containing a main method in a root directory.
118+
* Finds the classes with {@code public static void main(String[] args)} in {@code rootDirectory}.
181119
*
182-
* @return the name of the class if one is found, null if no class is found.
183-
* @throws IOException if searching/reading files fails.
120+
* @param rootDirectory directory containing the {@code .class} files
184121
*/
185122
@VisibleForTesting
186-
static List<String> findMainClasses(Path rootDirectory) throws IOException {
187-
List<String> classNames = new ArrayList<>();
188-
189-
// Make sure rootDirectory is valid
123+
static List<String> findMainClasses(Path rootDirectory, BuildLogger buildLogger)
124+
throws IOException {
125+
// Makes sure rootDirectory is valid.
190126
if (!Files.exists(rootDirectory) || !Files.isDirectory(rootDirectory)) {
191-
return classNames;
127+
return Collections.emptyList();
192128
}
193129

194-
// Get all .class files
195-
ClassFileLoader classFileLoader = new ClassFileLoader(rootDirectory);
196-
new DirectoryWalker(rootDirectory)
197-
.filter(Files::isRegularFile)
198-
.filter(path -> path.toString().endsWith(".class"))
199-
.walk(
200-
classFile -> {
201-
Class<?> fileClass = classFileLoader.findClass(null, classFile);
202-
if (fileClass == null) {
203-
return;
204-
}
205-
try {
206-
// Check if class contains {@code public static void main(String[] args)}
207-
Method main = fileClass.getMethod("main", String[].class);
208-
if (main != null
209-
&& main.getReturnType() == void.class
210-
&& Modifier.isStatic(main.getModifiers())
211-
&& Modifier.isPublic(main.getModifiers())) {
212-
classNames.add(fileClass.getName());
130+
List<String> classNames = new ArrayList<>();
131+
132+
ClassPool classPool = new ClassPool();
133+
classPool.appendSystemPath();
134+
135+
try {
136+
CtClass[] mainMethodParams = new CtClass[] {classPool.get("java.lang.String[]")};
137+
138+
new DirectoryWalker(rootDirectory)
139+
.filter(Files::isRegularFile)
140+
.filter(path -> path.toString().endsWith(".class"))
141+
.walk(
142+
classFile -> {
143+
try (InputStream classFileInputStream = Files.newInputStream(classFile)) {
144+
CtClass fileClass = classPool.makeClass(classFileInputStream);
145+
146+
// Check if class contains 'public static void main(String[] args)'.
147+
CtMethod mainMethod = fileClass.getDeclaredMethod("main", mainMethodParams);
148+
149+
if (CtClass.voidType.equals(mainMethod.getReturnType())
150+
&& Modifier.isStatic(mainMethod.getModifiers())
151+
&& Modifier.isPublic(mainMethod.getModifiers())) {
152+
classNames.add(fileClass.getName());
153+
}
154+
155+
} catch (NotFoundException ex) {
156+
// Ignores main method not found.
157+
158+
} catch (IOException ex) {
159+
// Could not read class file.
160+
buildLogger.warn("Could not read class file: " + classFile);
213161
}
214-
} catch (NoSuchMethodException | NoClassDefFoundError ignored) {
215-
// main method not found
216-
// TODO: Log search class failure when NoClassDefFoundError is caught?
217-
}
218-
});
162+
});
163+
164+
return classNames;
219165

220-
return classNames;
166+
} catch (NotFoundException ex) {
167+
// Thrown if 'java.lang.String' is not found in classPool.
168+
throw new RuntimeException(ex);
169+
}
221170
}
222171

223172
private MainClassFinder() {}

‎jib-core/src/test/java/com/google/cloud/tools/jib/frontend/MainClassFinderTest.java‎

Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public void setup() {
5959
@Test
6060
public void testFindMainClass_simple() throws URISyntaxException, IOException {
6161
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/simple").toURI());
62-
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory);
62+
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory, mockBuildLogger);
6363
Assert.assertEquals(1, mainClasses.size());
6464
Assert.assertTrue(mainClasses.contains("HelloWorld"));
6565
}
@@ -68,22 +68,22 @@ public void testFindMainClass_simple() throws URISyntaxException, IOException {
6868
public void testFindMainClass_subdirectories() throws URISyntaxException, IOException {
6969
Path rootDirectory =
7070
Paths.get(Resources.getResource("class-finder-tests/subdirectories").toURI());
71-
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory);
71+
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory, mockBuildLogger);
7272
Assert.assertEquals(1, mainClasses.size());
7373
Assert.assertTrue(mainClasses.contains("multi.layered.HelloWorld"));
7474
}
7575

7676
@Test
7777
public void testFindMainClass_noClass() throws URISyntaxException, IOException {
7878
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/no-main").toURI());
79-
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory);
79+
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory, mockBuildLogger);
8080
Assert.assertTrue(mainClasses.isEmpty());
8181
}
8282

8383
@Test
8484
public void testFindMainClass_multiple() throws URISyntaxException, IOException {
8585
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/multiple").toURI());
86-
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory);
86+
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory, mockBuildLogger);
8787
Assert.assertEquals(2, mainClasses.size());
8888
Assert.assertTrue(mainClasses.contains("multi.layered.HelloMoon"));
8989
Assert.assertTrue(mainClasses.contains("HelloWorld"));
@@ -92,16 +92,25 @@ public void testFindMainClass_multiple() throws URISyntaxException, IOException
9292
@Test
9393
public void testFindMainClass_extension() throws URISyntaxException, IOException {
9494
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/extension").toURI());
95-
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory);
95+
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory, mockBuildLogger);
9696
Assert.assertEquals(1, mainClasses.size());
9797
Assert.assertTrue(mainClasses.contains("main.MainClass"));
9898
}
9999

100100
@Test
101-
public void testFindMainClass_externalmethod() throws URISyntaxException, IOException {
101+
public void testFindMainClass_importedMethods() throws URISyntaxException, IOException {
102102
Path rootDirectory =
103-
Paths.get(Resources.getResource("class-finder-tests/externalmethod").toURI());
104-
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory);
103+
Paths.get(Resources.getResource("class-finder-tests/imported-methods").toURI());
104+
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory, mockBuildLogger);
105+
Assert.assertEquals(1, mainClasses.size());
106+
Assert.assertTrue(mainClasses.contains("main.MainClass"));
107+
}
108+
109+
@Test
110+
public void testFindMainClass_externalClasses() throws URISyntaxException, IOException {
111+
Path rootDirectory =
112+
Paths.get(Resources.getResource("class-finder-tests/external-classes").toURI());
113+
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory, mockBuildLogger);
105114
Assert.assertEquals(1, mainClasses.size());
106115
Assert.assertTrue(mainClasses.contains("main.MainClass"));
107116
}
@@ -110,7 +119,7 @@ public void testFindMainClass_externalmethod() throws URISyntaxException, IOExce
110119
public void testFindMainClass_innerClasses() throws URISyntaxException, IOException {
111120
Path rootDirectory =
112121
Paths.get(Resources.getResource("class-finder-tests/inner-classes").toURI());
113-
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory);
122+
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory, mockBuildLogger);
114123
Assert.assertEquals(1, mainClasses.size());
115124
Assert.assertTrue(mainClasses.contains("HelloWorld$InnerClass"));
116125
}
@@ -191,20 +200,4 @@ public void testResolveMainClass_noneInferredWithoutBackup() {
191200
.getMainClassHelpfulSuggestions("Main class was not found");
192201
}
193202
}
194-
195-
@Test
196-
public void testGetPathFromClassName() {
197-
Path root = Paths.get("test").resolve("root");
198-
MainClassFinder.ClassFileLoader classFileLoader = new MainClassFinder.ClassFileLoader(root);
199-
Assert.assertEquals(
200-
root.resolve("test").resolve("ClassName.class"),
201-
classFileLoader.getPathFromClassName("test.ClassName"));
202-
}
203-
204-
@Test
205-
public void testGetPathFromClassName_emptyClassName() {
206-
MainClassFinder.ClassFileLoader classFileLoader =
207-
new MainClassFinder.ClassFileLoader(Paths.get(""));
208-
Assert.assertEquals(Paths.get(".class"), classFileLoader.getPathFromClassName(""));
209-
}
210203
}

jib-core/src/test/resources/class-finder-tests/externalmethod/main/MainClass.class renamed to jib-core/src/test/resources/class-finder-tests/external-classes/main/MainClass.class

File renamed without changes.
Binary file not shown.

jib-core/src/test/resources/class-finder-tests/externalmethod/pack/Apple.class renamed to jib-core/src/test/resources/class-finder-tests/imported-methods/pack/Apple.class

File renamed without changes.

jib-core/src/test/resources/class-finder-tests/externalmethod/pack/Orange.class renamed to jib-core/src/test/resources/class-finder-tests/imported-methods/pack/Orange.class

File renamed without changes.

‎jib-gradle-plugin/build.gradle‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ dependencies {
6161
compile 'com.google.guava:guava:23.5-jre'
6262
compile 'com.fasterxml.jackson.core:jackson-databind:2.9.2'
6363
compile 'org.slf4j:slf4j-api:1.7.25'
64+
compile 'org.javassist:javassist:3.22.0-GA'
65+
6466
testCompile 'junit:junit:4.12'
6567
testCompile 'org.mockito:mockito-core:2.12.0'
6668

‎jib-maven-plugin/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,12 @@
7777
<version>1.7.25</version>
7878
<scope>compile</scope>
7979
</dependency>
80+
<dependency>
81+
<groupId>org.javassist</groupId>
82+
<artifactId>javassist</artifactId>
83+
<version>3.22.0-GA</version>
84+
<scope>compile</scope>
85+
</dependency>
8086
<!-- End dependencies from jib-core -->
8187

8288
<dependency>

0 commit comments

Comments
 (0)