-
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 11 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,96 @@ | ||
/* | ||
* 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.cloud.tools.jib.filesystem.DirectoryWalker; | ||
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.util.ArrayList; | ||
import java.util.List; | ||
import javax.annotation.Nullable; | ||
|
||
/** Infers the main class in an application. */ | ||
public class MainClassFinder { | ||
|
||
/** Helper for loading a .class file. */ | ||
private static class ClassFileLoader extends ClassLoader { | ||
|
||
private final Path classFile; | ||
|
||
private ClassFileLoader(Path classFile) { | ||
this.classFile = classFile; | ||
} | ||
|
||
@Nullable | ||
@Override | ||
public Class findClass(@Nullable 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 file containing a main method in a root directory. | ||
* | ||
* @return the name of the class if one is found, null if no class is found. | ||
* @throws IOException if searching/reading files fails. | ||
*/ | ||
public static List<String> findMainClasses(Path rootDirectory) throws IOException { | ||
List<String> classNames = new ArrayList<>(); | ||
|
||
// Make sure rootDirectory is valid | ||
if (!Files.exists(rootDirectory) || !Files.isDirectory(rootDirectory)) { | ||
return classNames; | ||
} | ||
|
||
// Get all .class files | ||
new DirectoryWalker(rootDirectory) | ||
.filter(Files::isRegularFile) | ||
.filter(path -> path.toString().endsWith(".class")) | ||
.walk( | ||
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. Might be good to put this in a separate method since it is getting to almost 6 levels of tabbing around line 91. |
||
Class<?> fileClass = new ClassFileLoader(classFile).findClass(null); | ||
if (fileClass == null) { | ||
return; | ||
} | ||
try { | ||
// Check if class contains {@code public static void main(String[] args)} | ||
Method main = fileClass.getMethod("main", String[].class); | ||
if (main != null | ||
&& main.getReturnType() == void.class | ||
&& Modifier.isStatic(main.getModifiers()) | ||
&& Modifier.isPublic(main.getModifiers())) { | ||
classNames.add(fileClass.getCanonicalName()); | ||
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. I believe you would want 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. K, wasn't sure which one we wanted. |
||
} | ||
} catch (NoSuchMethodException ignored) { | ||
// main method not found | ||
} | ||
}); | ||
|
||
return classNames; | ||
} | ||
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 |
||
|
||
private MainClassFinder() {} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
/* | ||
* 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 java.util.List; | ||
import org.junit.Assert; | ||
import org.junit.Test; | ||
|
||
/** Test for MainClassFinder. */ | ||
public class MainClassFinderTest { | ||
|
||
@Test | ||
public void testFindMainClass_simple() throws URISyntaxException, IOException { | ||
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/simple").toURI()); | ||
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory); | ||
Assert.assertEquals(1, mainClasses.size()); | ||
Assert.assertTrue(mainClasses.contains("HelloWorld")); | ||
} | ||
|
||
@Test | ||
public void testFindMainClass_subdirectories() throws URISyntaxException, IOException { | ||
Path rootDirectory = | ||
Paths.get(Resources.getResource("class-finder-tests/subdirectories").toURI()); | ||
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory); | ||
Assert.assertEquals(1, mainClasses.size()); | ||
Assert.assertTrue(mainClasses.contains("multi.layered.HelloWorld")); | ||
} | ||
|
||
@Test | ||
public void testFindMainClass_noClass() throws URISyntaxException, IOException { | ||
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/no-main").toURI()); | ||
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory); | ||
Assert.assertTrue(mainClasses.isEmpty()); | ||
} | ||
|
||
@Test | ||
public void testFindMainClass_multiple() throws URISyntaxException, IOException { | ||
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/multiple").toURI()); | ||
List<String> mainClasses = MainClassFinder.findMainClasses(rootDirectory); | ||
Assert.assertEquals(2, mainClasses.size()); | ||
Assert.assertTrue(mainClasses.contains("multi.layered.HelloMoon")); | ||
Assert.assertTrue(mainClasses.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,7 +18,10 @@ | |
|
||
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.common.annotations.VisibleForTesting; | ||
import java.io.IOException; | ||
import java.nio.file.Path; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import javax.annotation.Nullable; | ||
|
@@ -30,45 +33,87 @@ | |
/** Obtains information about a Gradle {@link Project} that uses Jib. */ | ||
class ProjectProperties { | ||
|
||
private static final String PLUGIN_NAME = "jib"; | ||
|
||
private final Project project; | ||
private final GradleBuildLogger gradleBuildLogger; | ||
private final SourceFilesConfiguration sourceFilesConfiguration; | ||
|
||
ProjectProperties(Project project, GradleBuildLogger gradleBuildLogger) { | ||
this.project = project; | ||
this.gradleBuildLogger = gradleBuildLogger; | ||
try { | ||
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. Looks good! This should prob go in a static method like |
||
sourceFilesConfiguration = GradleSourceFilesConfiguration.getForProject(project); | ||
} catch (IOException ex) { | ||
throw new GradleException("Obtaining project build output files failed", ex); | ||
} | ||
} | ||
|
||
@VisibleForTesting | ||
ProjectProperties( | ||
Project project, | ||
GradleBuildLogger gradleBuildLogger, | ||
SourceFilesConfiguration sourceFilesConfiguration) { | ||
this.project = project; | ||
this.gradleBuildLogger = gradleBuildLogger; | ||
this.sourceFilesConfiguration = sourceFilesConfiguration; | ||
} | ||
|
||
/** | ||
* @param mainClass the configured main class | ||
* @return the main class to use for the container entrypoint. | ||
* If {@code mainClass} is {@code null}, tries to infer main class in this order: | ||
* | ||
* <ul> | ||
* <li>1. Looks in a {@code jar} task. | ||
* <li>2. Searches for a class defined with a main method. | ||
* </ul> | ||
* | ||
* <p>Warns if main class is not valid. | ||
* | ||
* @throws GradleException if no valid main class is not found. | ||
*/ | ||
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")); | ||
gradleBuildLogger.debug( | ||
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. I was talking to @patflynn and Patrick mentioned that it might be better to log something like |
||
"Could not find main class specified in a 'jar' task; attempting to " | ||
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. Let's add a todo to consolidate this code with the Maven one. 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. Already added it to #262, but I can add a TODO in the code as well if you want. 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. Okay that's fine then. |
||
+ "infer main class."); | ||
try { | ||
// Adds each file in each classes output directory to the classes files list. | ||
List<String> mainClasses = new ArrayList<>(); | ||
for (Path classPath : sourceFilesConfiguration.getClassesFiles()) { | ||
mainClasses.addAll(MainClassFinder.findMainClasses(classPath)); | ||
} | ||
|
||
if (mainClasses.size() == 1) { | ||
mainClass = mainClasses.get(0); | ||
} else if (mainClasses.size() == 0) { | ||
throw new GradleException( | ||
HelpfulSuggestionsProvider.get("Main class was not found") | ||
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 these messages are the same as in Maven, they can be added to |
||
.forMainClassNotFound(PLUGIN_NAME)); | ||
} else { | ||
throw new GradleException( | ||
HelpfulSuggestionsProvider.get( | ||
"Multiple valid main classes were found: " + String.join(", ", mainClasses)) | ||
.forMainClassNotFound(PLUGIN_NAME)); | ||
} | ||
} catch (IOException ex) { | ||
throw new GradleException( | ||
HelpfulSuggestionsProvider.get("Failed to get main class") | ||
.forMainClassNotFound(PLUGIN_NAME), | ||
ex); | ||
} | ||
} | ||
} | ||
if (!BuildConfiguration.isValidJavaClass(mainClass)) { | ||
getLogger().warn("'mainClass' is not a valid Java class : " + mainClass); | ||
gradleBuildLogger.warn("'mainClass' is not a valid Java class : " + mainClass); | ||
} | ||
return mainClass; | ||
} | ||
|
||
GradleBuildLogger getLogger() { | ||
return gradleBuildLogger; | ||
} | ||
|
||
/** @return the {@link SourceFilesConfiguration} based on the current project */ | ||
SourceFilesConfiguration getSourceFilesConfiguration() { | ||
try { | ||
return GradleSourceFilesConfiguration.getForProject(project); | ||
|
||
} catch (IOException ex) { | ||
throw new GradleException("Obtaining project build output files failed", ex); | ||
} | ||
return sourceFilesConfiguration; | ||
} | ||
|
||
/** Extracts main class from 'jar' task, if available. */ | ||
|
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.
s/Get/Searches (or Looks at)