Skip to content

Commit 99ad417

Browse files
authored
Reduce duplicate code in maven/gradle ProjectProperties (GoogleContainerTools#310)
* Refactor project properties to reduce duplicate code * Add new tests for ProjectProperty implementations
1 parent e90f567 commit 99ad417

22 files changed

Lines changed: 747 additions & 721 deletions

File tree

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

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,11 @@
1616

1717
package com.google.cloud.tools.jib.frontend;
1818

19+
import com.google.cloud.tools.jib.builder.BuildConfiguration;
20+
import com.google.cloud.tools.jib.builder.BuildLogger;
1921
import com.google.cloud.tools.jib.filesystem.DirectoryWalker;
22+
import com.google.common.annotations.VisibleForTesting;
23+
import com.google.common.base.Preconditions;
2024
import java.io.IOException;
2125
import java.lang.reflect.Method;
2226
import java.lang.reflect.Modifier;
@@ -51,13 +55,82 @@ public Class findClass(@Nullable String name) {
5155
}
5256
}
5357

58+
/**
59+
* If {@code mainClass} is {@code null}, tries to infer main class in this order:
60+
*
61+
* <ul>
62+
* <li>1. Looks in a {@code jar} plugin provided by {@code projectProperties} ({@code
63+
* maven-jar-plugin} for maven or {@code jar} task for gradle).
64+
* <li>2. Searches for a class defined with a main method.
65+
* </ul>
66+
*
67+
* <p>Warns if main class is not valid, or throws an error if no valid main class is not found.
68+
*/
69+
public static String resolveMainClass(
70+
@Nullable String mainClass, ProjectProperties projectProperties)
71+
throws MainClassInferenceException {
72+
BuildLogger logger = projectProperties.getLogger();
73+
if (mainClass == null) {
74+
logger.info(
75+
"Searching for main class... Add a 'mainClass' configuration to '"
76+
+ projectProperties.getPluginName()
77+
+ "' to improve build speed.");
78+
mainClass = projectProperties.getMainClassFromJar();
79+
if (mainClass == null || !BuildConfiguration.isValidJavaClass(mainClass)) {
80+
logger.debug(
81+
"Could not find a valid main class specified in "
82+
+ projectProperties.getJarPluginName()
83+
+ "; attempting to infer main class.");
84+
85+
try {
86+
// Adds each file in each classes output directory to the classes files list.
87+
List<String> mainClasses = new ArrayList<>();
88+
for (Path classPath : projectProperties.getSourceFilesConfiguration().getClassesFiles()) {
89+
mainClasses.addAll(findMainClasses(classPath));
90+
}
91+
92+
if (mainClasses.size() == 1) {
93+
// Valid class found; use inferred main class
94+
mainClass = mainClasses.get(0);
95+
} else if (mainClasses.size() == 0 && mainClass == null) {
96+
// No main class found anywhere
97+
throw new MainClassInferenceException(
98+
projectProperties
99+
.getMainClassHelpfulSuggestions("Main class was not found")
100+
.forMainClassNotFound(projectProperties.getPluginName()));
101+
} else if (mainClasses.size() > 1 && mainClass == null) {
102+
// More than one main class found with no jar plugin to fall back on; error
103+
throw new MainClassInferenceException(
104+
projectProperties
105+
.getMainClassHelpfulSuggestions(
106+
"Multiple valid main classes were found: " + String.join(", ", mainClasses))
107+
.forMainClassNotFound(projectProperties.getPluginName()));
108+
}
109+
} catch (IOException ex) {
110+
throw new MainClassInferenceException(
111+
projectProperties
112+
.getMainClassHelpfulSuggestions("Failed to get main class")
113+
.forMainClassNotFound(projectProperties.getPluginName()),
114+
ex);
115+
}
116+
}
117+
}
118+
Preconditions.checkNotNull(mainClass);
119+
if (!BuildConfiguration.isValidJavaClass(mainClass)) {
120+
logger.warn("'mainClass' is not a valid Java class : " + mainClass);
121+
}
122+
123+
return mainClass;
124+
}
125+
54126
/**
55127
* Searches for a .class file containing a main method in a root directory.
56128
*
57129
* @return the name of the class if one is found, null if no class is found.
58130
* @throws IOException if searching/reading files fails.
59131
*/
60-
public static List<String> findMainClasses(Path rootDirectory) throws IOException {
132+
@VisibleForTesting
133+
static List<String> findMainClasses(Path rootDirectory) throws IOException {
61134
List<String> classNames = new ArrayList<>();
62135

63136
// Make sure rootDirectory is valid
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Copyright 2018 Google LLC. All rights reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
17+
package com.google.cloud.tools.jib.frontend;
18+
19+
/** Thrown when main class inference fails. */
20+
public class MainClassInferenceException extends Exception {
21+
MainClassInferenceException(String message) {
22+
super(message);
23+
}
24+
25+
MainClassInferenceException(String message, Throwable cause) {
26+
super(message, cause);
27+
}
28+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
* Copyright 2018 Google LLC. All rights reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
17+
package com.google.cloud.tools.jib.frontend;
18+
19+
import com.google.cloud.tools.jib.builder.BuildLogger;
20+
import com.google.cloud.tools.jib.builder.SourceFilesConfiguration;
21+
import java.nio.file.Path;
22+
import javax.annotation.Nullable;
23+
24+
/** Project property methods that require maven/gradle-specific implementations. */
25+
public interface ProjectProperties {
26+
27+
/** Directory name for the cache. The directory will be relative to the build output directory. */
28+
String CACHE_DIRECTORY_NAME = "jib-cache";
29+
30+
BuildLogger getLogger();
31+
32+
String getPluginName();
33+
34+
SourceFilesConfiguration getSourceFilesConfiguration();
35+
36+
Path getCacheDirectory();
37+
38+
String getJarPluginName();
39+
40+
/** @return the name of the main class configured in a jar plugin, or null if none is found. */
41+
@Nullable
42+
String getMainClassFromJar();
43+
44+
/** @return a {@link HelpfulSuggestions} instance for main class inference failure. */
45+
HelpfulSuggestions getMainClassHelpfulSuggestions(String prefix);
46+
}

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

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,46 @@
1616

1717
package com.google.cloud.tools.jib.frontend;
1818

19+
import com.google.cloud.tools.jib.builder.BuildLogger;
20+
import com.google.cloud.tools.jib.builder.SourceFilesConfiguration;
1921
import com.google.common.io.Resources;
2022
import java.io.IOException;
2123
import java.net.URISyntaxException;
2224
import java.nio.file.Path;
2325
import java.nio.file.Paths;
26+
import java.util.Collections;
2427
import java.util.List;
2528
import org.junit.Assert;
29+
import org.junit.Before;
2630
import org.junit.Test;
31+
import org.junit.runner.RunWith;
32+
import org.mockito.ArgumentMatchers;
33+
import org.mockito.Mock;
34+
import org.mockito.Mockito;
35+
import org.mockito.junit.MockitoJUnitRunner;
2736

2837
/** Test for MainClassFinder. */
38+
@RunWith(MockitoJUnitRunner.class)
2939
public class MainClassFinderTest {
3040

41+
@Mock private BuildLogger mockBuildLogger;
42+
@Mock private SourceFilesConfiguration mockSourceFilesConfiguration;
43+
@Mock private ProjectProperties mockProjectProperties;
44+
@Mock private HelpfulSuggestions mockHelpfulSuggestions;
45+
46+
private final List<Path> fakeClassesPath = Collections.singletonList(Paths.get("a/b/c"));
47+
48+
@Before
49+
public void setup() {
50+
Mockito.when(mockProjectProperties.getLogger()).thenReturn(mockBuildLogger);
51+
Mockito.when(mockProjectProperties.getPluginName()).thenReturn("plugin");
52+
Mockito.when(mockProjectProperties.getSourceFilesConfiguration())
53+
.thenReturn(mockSourceFilesConfiguration);
54+
Mockito.when(mockProjectProperties.getMainClassHelpfulSuggestions(ArgumentMatchers.any()))
55+
.thenReturn(mockHelpfulSuggestions);
56+
Mockito.when(mockProjectProperties.getJarPluginName()).thenReturn("jar-plugin");
57+
}
58+
3159
@Test
3260
public void testFindMainClass_simple() throws URISyntaxException, IOException {
3361
Path rootDirectory = Paths.get(Resources.getResource("class-finder-tests/simple").toURI());
@@ -60,4 +88,77 @@ public void testFindMainClass_multiple() throws URISyntaxException, IOException
6088
Assert.assertTrue(mainClasses.contains("multi.layered.HelloMoon"));
6189
Assert.assertTrue(mainClasses.contains("HelloWorld"));
6290
}
91+
92+
@Test
93+
public void testResolveMainClass() throws MainClassInferenceException {
94+
Mockito.when(mockProjectProperties.getMainClassFromJar()).thenReturn("some.main.class");
95+
Assert.assertEquals(
96+
"some.main.class", MainClassFinder.resolveMainClass(null, mockProjectProperties));
97+
Assert.assertEquals(
98+
"configured", MainClassFinder.resolveMainClass("configured", mockProjectProperties));
99+
}
100+
101+
@Test
102+
public void testResolveMainClass_notValid() throws MainClassInferenceException {
103+
Mockito.when(mockProjectProperties.getMainClassFromJar()).thenReturn("${start-class}");
104+
Mockito.when(mockSourceFilesConfiguration.getClassesFiles()).thenReturn(fakeClassesPath);
105+
Assert.assertEquals(
106+
"${start-class}", MainClassFinder.resolveMainClass(null, mockProjectProperties));
107+
Mockito.verify(mockBuildLogger).warn("'mainClass' is not a valid Java class : ${start-class}");
108+
}
109+
110+
@Test
111+
public void testResolveMainClass_multipleInferredWithBackup() throws Throwable {
112+
Mockito.when(mockProjectProperties.getMainClassFromJar()).thenReturn("${start-class}");
113+
Mockito.when(mockSourceFilesConfiguration.getClassesFiles())
114+
.thenReturn(
115+
Collections.singletonList(
116+
Paths.get(Resources.getResource("class-finder-tests/multiple").toURI())));
117+
118+
Assert.assertEquals(
119+
"${start-class}", MainClassFinder.resolveMainClass(null, mockProjectProperties));
120+
Mockito.verify(mockBuildLogger).warn("'mainClass' is not a valid Java class : ${start-class}");
121+
}
122+
123+
@Test
124+
public void testResolveMainClass_multipleInferredWithoutBackup() throws URISyntaxException {
125+
Mockito.when(mockProjectProperties.getMainClassFromJar()).thenReturn(null);
126+
Mockito.when(mockSourceFilesConfiguration.getClassesFiles())
127+
.thenReturn(
128+
Collections.singletonList(
129+
Paths.get(Resources.getResource("class-finder-tests/multiple").toURI())));
130+
131+
try {
132+
MainClassFinder.resolveMainClass(null, mockProjectProperties);
133+
Assert.fail();
134+
} catch (MainClassInferenceException ex) {
135+
Mockito.verify(mockProjectProperties)
136+
.getMainClassHelpfulSuggestions(
137+
"Multiple valid main classes were found: HelloWorld, multi.layered.HelloMoon");
138+
}
139+
}
140+
141+
@Test
142+
public void testResolveMainClass_noneInferredWithBackup() throws MainClassInferenceException {
143+
Mockito.when(mockProjectProperties.getMainClassFromJar()).thenReturn("${start-class}");
144+
Mockito.when(mockSourceFilesConfiguration.getClassesFiles()).thenReturn(fakeClassesPath);
145+
146+
Assert.assertEquals(
147+
"${start-class}", MainClassFinder.resolveMainClass(null, mockProjectProperties));
148+
Mockito.verify(mockBuildLogger).warn("'mainClass' is not a valid Java class : ${start-class}");
149+
}
150+
151+
@Test
152+
public void testResolveMainClass_noneInferredWithoutBackup() {
153+
Mockito.when(mockProjectProperties.getMainClassFromJar()).thenReturn(null);
154+
Mockito.when(mockSourceFilesConfiguration.getClassesFiles()).thenReturn(fakeClassesPath);
155+
156+
try {
157+
MainClassFinder.resolveMainClass(null, mockProjectProperties);
158+
Assert.fail();
159+
} catch (MainClassInferenceException ex) {
160+
Mockito.verify(mockProjectProperties)
161+
.getMainClassHelpfulSuggestions("Main class was not found");
162+
}
163+
}
63164
}

‎jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildDockerTask.java‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,32 +58,32 @@ public void buildDocker() throws InvalidImageReferenceException {
5858

5959
// Asserts required @Input parameters are not null.
6060
Preconditions.checkNotNull(jibExtension);
61-
6261
RegistryCredentials knownBaseRegistryCredentials = null;
6362
Authorization fromAuthorization = jibExtension.getFrom().getImageAuthorization();
6463
if (fromAuthorization != null) {
6564
knownBaseRegistryCredentials = new RegistryCredentials("jib.from.auth", fromAuthorization);
6665
}
6766

6867
GradleBuildLogger gradleBuildLogger = new GradleBuildLogger(getLogger());
69-
ProjectProperties projectProperties =
70-
ProjectProperties.getForProject(getProject(), gradleBuildLogger);
68+
GradleProjectProperties gradleProjectProperties =
69+
GradleProjectProperties.getForProject(getProject(), gradleBuildLogger);
70+
String mainClass = gradleProjectProperties.getMainClass(jibExtension);
7171
BuildConfiguration buildConfiguration =
7272
BuildConfiguration.builder(gradleBuildLogger)
7373
.setBaseImage(ImageReference.parse(jibExtension.getBaseImage()))
7474
.setTargetImage(ImageReference.parse(jibExtension.getTargetImage()))
7575
.setBaseImageCredentialHelperName(jibExtension.getFrom().getCredHelper())
7676
.setKnownBaseRegistryCredentials(knownBaseRegistryCredentials)
77-
.setMainClass(projectProperties.getMainClass(jibExtension.getMainClass()))
77+
.setMainClass(mainClass)
7878
.setJvmFlags(jibExtension.getJvmFlags())
7979
.build();
8080

8181
// Uses a directory in the Gradle build cache as the Jib cache.
8282
try {
8383
BuildStepsRunner.forBuildToDockerDaemon(
8484
buildConfiguration,
85-
projectProperties.getSourceFilesConfiguration(),
86-
projectProperties.getCacheDirectory(),
85+
gradleProjectProperties.getSourceFilesConfiguration(),
86+
gradleProjectProperties.getCacheDirectory(),
8787
jibExtension.getUseOnlyProjectCache())
8888
.build(HELPFUL_SUGGESTIONS);
8989

‎jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildImageTask.java‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,10 @@ public void buildImage() throws InvalidImageReferenceException {
7878
}
7979

8080
GradleBuildLogger gradleBuildLogger = new GradleBuildLogger(getLogger());
81-
ProjectProperties projectProperties =
82-
ProjectProperties.getForProject(getProject(), gradleBuildLogger);
81+
GradleProjectProperties gradleProjectProperties =
82+
GradleProjectProperties.getForProject(getProject(), gradleBuildLogger);
83+
String mainClass = gradleProjectProperties.getMainClass(jibExtension);
84+
8385
BuildConfiguration buildConfiguration =
8486
BuildConfiguration.builder(gradleBuildLogger)
8587
.setBaseImage(ImageReference.parse(jibExtension.getBaseImage()))
@@ -88,7 +90,7 @@ public void buildImage() throws InvalidImageReferenceException {
8890
.setKnownBaseRegistryCredentials(knownBaseRegistryCredentials)
8991
.setTargetImageCredentialHelperName(jibExtension.getTo().getCredHelper())
9092
.setKnownTargetRegistryCredentials(knownTargetRegistryCredentials)
91-
.setMainClass(projectProperties.getMainClass(jibExtension.getMainClass()))
93+
.setMainClass(mainClass)
9294
.setJvmFlags(jibExtension.getJvmFlags())
9395
.setTargetFormat(jibExtension.getFormat())
9496
.build();
@@ -115,8 +117,8 @@ public void buildImage() throws InvalidImageReferenceException {
115117
try {
116118
BuildStepsRunner.forBuildImage(
117119
buildConfiguration,
118-
projectProperties.getSourceFilesConfiguration(),
119-
projectProperties.getCacheDirectory(),
120+
gradleProjectProperties.getSourceFilesConfiguration(),
121+
gradleProjectProperties.getCacheDirectory(),
120122
jibExtension.getUseOnlyProjectCache())
121123
.build(HELPFUL_SUGGESTIONS);
122124

‎jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/DockerContextTask.java‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,15 +64,14 @@ public void generateDockerContext() {
6464
Preconditions.checkNotNull(jibExtension);
6565

6666
GradleBuildLogger gradleBuildLogger = new GradleBuildLogger(getLogger());
67-
68-
ProjectProperties projectProperties =
69-
ProjectProperties.getForProject(getProject(), gradleBuildLogger);
70-
String mainClass = projectProperties.getMainClass(jibExtension.getMainClass());
67+
GradleProjectProperties gradleProjectProperties =
68+
GradleProjectProperties.getForProject(getProject(), gradleBuildLogger);
69+
String mainClass = gradleProjectProperties.getMainClass(jibExtension);
7170

7271
String targetDir = getTargetDir();
7372

7473
try {
75-
new DockerContextGenerator(projectProperties.getSourceFilesConfiguration())
74+
new DockerContextGenerator(gradleProjectProperties.getSourceFilesConfiguration())
7675
.setBaseImage(jibExtension.getBaseImage())
7776
.setJvmFlags(jibExtension.getJvmFlags())
7877
.setMainClass(mainClass)

0 commit comments

Comments
 (0)