-
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 10 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,106 @@ | ||
/* | ||
* 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 java.util.StringJoiner; | ||
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(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 given an absolute 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> findMainClass(Path rootDirectory) throws IOException { | ||
List<String> results = new ArrayList<>(); | ||
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. A more descriptive variable name like |
||
|
||
// Make sure rootDirectory is valid | ||
if (!Files.exists(rootDirectory) || !Files.isDirectory(rootDirectory)) { | ||
return results; | ||
} | ||
|
||
// Get all .class files | ||
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. s/Get/Searches (or Looks at) |
||
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. |
||
// Convert filename (rootDir/path/to/ClassName.class) to class name | ||
// (path.to.ClassName) | ||
Path relativized = rootDirectory.relativize(classFile); | ||
StringJoiner stringJoiner = new StringJoiner("."); | ||
for (Path path : relativized) { | ||
stringJoiner.add(path.toString()); | ||
} | ||
String name = stringJoiner.toString(); | ||
name = name.substring(0, name.length() - ".class".length()); | ||
|
||
Class<?> fileClass = new ClassFileLoader(classFile).findClass(name); | ||
if (fileClass != 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. An early return here would help reduce the tabbing. |
||
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())) { | ||
results.add(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. Hmm, is it possible to not have to do the path-to-class conversion and instead just get the class from the file via reflection? 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. Doesn't look like it, I think I need to pass the full name into the class loader. 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 if you pass in |
||
} | ||
} catch (NoSuchMethodException ignored) { | ||
// main method not found | ||
} | ||
} | ||
}); | ||
|
||
return results; | ||
} | ||
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.findMainClass(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.findMainClass(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.findMainClass(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.findMainClass(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,13 +18,18 @@ | |
|
||
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 java.io.IOException; | ||
import java.nio.file.Path; | ||
import java.nio.file.Paths; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import javax.annotation.Nullable; | ||
import org.gradle.api.GradleException; | ||
import org.gradle.api.Project; | ||
import org.gradle.api.Task; | ||
import org.gradle.api.plugins.JavaPluginConvention; | ||
import org.gradle.api.tasks.SourceSet; | ||
import org.gradle.jvm.tasks.Jar; | ||
|
||
/** Obtains information about a Gradle {@link Project} that uses Jib. */ | ||
|
@@ -46,21 +51,45 @@ 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."); | ||
|
||
final String mainClassSuggestion = "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. Oh by constant, I meant like a |
||
try { | ||
// Adds each file in each classes output directory to the classes files list. | ||
JavaPluginConvention javaPluginConvention = | ||
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 meant here to just directly use the classes files from 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 was either this or 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. Okay, though we do need some way to guarantee that the classes we are searching in are the classes that will be in the container. |
||
project.getConvention().getPlugin(JavaPluginConvention.class); | ||
SourceSet mainSourceSet = javaPluginConvention.getSourceSets().getByName("main"); | ||
Path classesDirs = Paths.get(mainSourceSet.getOutput().getClassesDirs().getAsPath()); | ||
List<String> mainClasses = new ArrayList<>(MainClassFinder.findMainClass(classesDirs)); | ||
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 |
||
|
||
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 |
||
.suggest(mainClassSuggestion)); | ||
} else { | ||
throw new GradleException( | ||
HelpfulSuggestionsProvider.get( | ||
"Multiple valid main classes were found: " + String.join(", ", mainClasses)) | ||
.suggest(mainClassSuggestion)); | ||
} | ||
} catch (IOException ex) { | ||
throw new GradleException( | ||
HelpfulSuggestionsProvider.get("Failed to get main class") | ||
.suggest(mainClassSuggestion), | ||
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 { | ||
|
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.
Since it's returning a list now,
findMainClasses
would be clearer.