-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Infer main class if it isn't configured anywhere #278
Changes from 6 commits
1aa6cdb
8ac2af5
b05a9a9
49b9e89
0389ae2
01a9824
daaf5d2
60f3fc5
eeeed9a
21c1dfa
bca760b
9d1c3f6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
/* | ||
* Copyright 2018 Google LLC. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not | ||
* use this file except in compliance with the License. You may obtain a copy of | ||
* the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
* License for the specific language governing permissions and limitations under | ||
* the License. | ||
*/ | ||
|
||
package com.google.cloud.tools.jib.frontend; | ||
|
||
import java.io.IOException; | ||
import java.lang.reflect.Method; | ||
import java.lang.reflect.Modifier; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.nio.file.Paths; | ||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.Stream; | ||
import javax.annotation.Nullable; | ||
|
||
/** Class used for inferring the main class in an application. */ | ||
public class MainClassFinder { | ||
|
||
/** Helper class for loading a .class file. */ | ||
private static class ClassFileLoader extends ClassLoader { | ||
|
||
private Path classFile; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. final |
||
|
||
private ClassFileLoader(Path classFile) { | ||
this.classFile = classFile; | ||
} | ||
|
||
@Nullable | ||
@Override | ||
public Class findClass(String name) { | ||
try { | ||
byte[] bytes = Files.readAllBytes(classFile); | ||
return defineClass(name, bytes, 0, bytes.length); | ||
} catch (IOException | ClassFormatError ignored) { | ||
// Not a valid class file | ||
return null; | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Searches for a class containing a main method given an absolute root directory. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should prob have a note that this is searching for |
||
* | ||
* @return the name of the class if one is found, null if no class is found. | ||
* @throws IOException if searching/reading files fails. | ||
* @throws MultipleClassesFoundException if more than one valid main class is found. | ||
*/ | ||
@Nullable | ||
public static String findMainClass(String rootDirectory) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should prob pass |
||
throws MultipleClassesFoundException, IOException { | ||
// Make sure rootDirectory is valid | ||
if (!Files.exists(Paths.get(rootDirectory)) || !Files.isDirectory(Paths.get(rootDirectory))) { | ||
return null; | ||
} | ||
|
||
String className = null; | ||
try (Stream<Path> pathStream = Files.walk(Paths.get(rootDirectory))) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this much of an improvement? Looks like implementing a DirectoryWalker would be more complicated. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's mostly as a way to abstract away the strategy for walking into a testable class. The use would like something like:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh I see, the one you implemented. I was thinking you meant something like this https://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/DirectoryWalker.html |
||
// Get all .class files | ||
List<Path> classFiles = | ||
pathStream | ||
.filter(Files::isRegularFile) | ||
.filter(path -> path.toString().endsWith(".class")) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah right that makes sense. Looks like we used |
||
.collect(Collectors.toList()); | ||
|
||
for (Path classFile : classFiles) { | ||
// Convert filename (rootDir/path/to/ClassName.class) to class name (path.to.ClassName) | ||
String name = classFile.toAbsolutePath().toString(); | ||
name = name.substring(rootDirectory.length() + 1); | ||
name = name.replace('/', '.').replace('\\', '.'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
name = name.substring(0, name.length() - ".class".length()); | ||
|
||
Class fileClass = new ClassFileLoader(classFile).findClass(name); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Generics should be used with a template - |
||
if (fileClass == null) { | ||
// Got an invalid class file, keep searching | ||
continue; | ||
} | ||
|
||
try { | ||
// Check if class contains a public static void main(String[] args) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Wrap in |
||
Method main = fileClass.getMethod("main", String[].class); | ||
if (main != null | ||
&& main.getReturnType() == void.class | ||
&& Modifier.isStatic(main.getModifiers()) | ||
&& Modifier.isPublic(main.getModifiers())) { | ||
if (className == null) { | ||
// Main method found; save it and continue searching for duplicates | ||
className = name; | ||
} else { | ||
// Found more than one main method | ||
throw new MultipleClassesFoundException(className, name); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. An alternative could be to change this method to return a list of main classes found so that
|
||
} | ||
} | ||
} catch (NoSuchMethodException ignored) { | ||
// main method not found | ||
} | ||
} | ||
} | ||
|
||
return className; | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should have a private constructor |
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
/* | ||
* Copyright 2018 Google LLC. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not | ||
* use this file except in compliance with the License. You may obtain a copy of | ||
* the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
* License for the specific language governing permissions and limitations under | ||
* the License. | ||
*/ | ||
|
||
package com.google.cloud.tools.jib.frontend; | ||
|
||
public class MultipleClassesFoundException extends Exception { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. short javadoc |
||
MultipleClassesFoundException(String className1, String className2) { | ||
super( | ||
"Multiple classes found while trying to infer main class: " | ||
+ className1 | ||
+ ", " | ||
+ className2); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
/* | ||
* Copyright 2018 Google LLC. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not | ||
* use this file except in compliance with the License. You may obtain a copy of | ||
* the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
* License for the specific language governing permissions and limitations under | ||
* the License. | ||
*/ | ||
|
||
package com.google.cloud.tools.jib.frontend; | ||
|
||
import com.google.common.io.Resources; | ||
import java.io.IOException; | ||
import java.net.URISyntaxException; | ||
import java.nio.file.Path; | ||
import java.nio.file.Paths; | ||
import org.junit.Assert; | ||
import org.junit.Test; | ||
|
||
/** Test for MainClassFinder. */ | ||
public class MainClassFinderTest { | ||
|
||
@Test | ||
public void testFindMainClass_simple() | ||
throws URISyntaxException, MultipleClassesFoundException, IOException { | ||
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/simple").toURI()); | ||
String mainClass = MainClassFinder.findMainClass(rootDirectory.toString()); | ||
Assert.assertEquals("HelloWorld", mainClass); | ||
} | ||
|
||
@Test | ||
public void testFindMainClass_subdirectories() | ||
throws URISyntaxException, MultipleClassesFoundException, IOException { | ||
Path rootDirectory = | ||
Paths.get(Resources.getResource("class-finder-tests/subdirectories").toURI()); | ||
String mainClass = MainClassFinder.findMainClass(rootDirectory.toString()); | ||
Assert.assertEquals("multi.layered.HelloWorld", mainClass); | ||
} | ||
|
||
@Test | ||
public void testFindMainClass_noClass() | ||
throws URISyntaxException, MultipleClassesFoundException, IOException { | ||
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/no-main").toURI()); | ||
String mainClass = MainClassFinder.findMainClass(rootDirectory.toString()); | ||
Assert.assertEquals(null, mainClass); | ||
} | ||
|
||
@Test | ||
public void testFindMainClass_multiple() throws URISyntaxException, IOException { | ||
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/multiple").toURI()); | ||
try { | ||
MainClassFinder.findMainClass(rootDirectory.toString()); | ||
Assert.fail(); | ||
} catch (MultipleClassesFoundException ex) { | ||
Assert.assertTrue( | ||
ex.getMessage().contains("Multiple classes found while trying to infer main class: ")); | ||
Assert.assertTrue(ex.getMessage().contains("multi.layered.HelloMoon")); | ||
Assert.assertTrue(ex.getMessage().contains("HelloWorld")); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Hi there. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,7 +15,6 @@ jib { | |
image = 'gcr.io/jib-integration-testing/emptyimage:gradle' | ||
credHelper = 'gcr' | ||
} | ||
mainClass = 'com.test.Empty' | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 😃 |
||
// Does not have tests use user-level cache for base image layers. | ||
useOnlyProjectCache = true | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,6 +18,8 @@ | |
|
||
import com.google.cloud.tools.jib.builder.BuildConfiguration; | ||
import com.google.cloud.tools.jib.builder.SourceFilesConfiguration; | ||
import com.google.cloud.tools.jib.frontend.MainClassFinder; | ||
import com.google.cloud.tools.jib.frontend.MultipleClassesFoundException; | ||
import java.io.IOException; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
@@ -46,9 +48,31 @@ String getMainClass(@Nullable String mainClass) { | |
if (mainClass == null) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since the logic is getting a bit more complex, it'd be good to add a description to the Javadoc like:
|
||
mainClass = getMainClassFromJarTask(); | ||
if (mainClass == null) { | ||
throw new GradleException( | ||
HelpfulSuggestionsProvider.get("Could not find main class specified in a 'jar' task") | ||
.suggest("add a `mainClass` configuration to jib")); | ||
getLogger() | ||
.info( | ||
"Could not find main class specified in a 'jar' task; attempting to " | ||
+ "infer main class."); | ||
try { | ||
mainClass = | ||
MainClassFinder.findMainClass( | ||
project | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This returns a list of Paths, how would I use it to get the root directory? |
||
.getBuildDir() | ||
.toPath() | ||
.resolve("classes") | ||
.resolve("java") | ||
.resolve("main") | ||
.toAbsolutePath() | ||
.toString()); | ||
} catch (MultipleClassesFoundException | IOException ex) { | ||
throw new GradleException( | ||
HelpfulSuggestionsProvider.get("Failed to get main class: " + ex.getMessage()) | ||
.suggest("add a `mainClass` configuration to jib")); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This suggestion can be a constant together with below. |
||
} | ||
if (mainClass == null) { | ||
throw new GradleException( | ||
HelpfulSuggestionsProvider.get("Could not infer main class") | ||
.suggest("add a `mainClass` configuration to jib")); | ||
} | ||
} | ||
} | ||
if (!BuildConfiguration.isValidJavaClass(mainClass)) { | ||
|
@@ -57,7 +81,7 @@ String getMainClass(@Nullable String mainClass) { | |
return mainClass; | ||
} | ||
|
||
GradleBuildLogger getLogger() { | ||
private GradleBuildLogger getLogger() { | ||
return gradleBuildLogger; | ||
} | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: usually can omit phrases like
Class used for
so it's likeInfers the main...