Skip to content

Commit b01b6cc

Browse files
authored
Refactors and moves exception building to jib-core. (GoogleContainerTools#239)
1 parent 9a92dfd commit b01b6cc

6 files changed

Lines changed: 165 additions & 89 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
/** Builds messages that provides suggestions on how to fix the error. */
20+
public class HelpfulMessageBuilder {
21+
22+
private final String messageHeader;
23+
24+
/** @param messageHeader the initial message text */
25+
public HelpfulMessageBuilder(String messageHeader) {
26+
this.messageHeader = messageHeader;
27+
}
28+
29+
/** @return the message with a suggestion */
30+
public String withSuggestion(String suggestion) {
31+
return messageHeader + ", perhaps you should " + suggestion;
32+
}
33+
34+
/** @return just the message */
35+
public String withNoHelp() {
36+
return messageHeader;
37+
}
38+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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 org.junit.Assert;
20+
import org.junit.Test;
21+
import org.junit.runner.RunWith;
22+
import org.mockito.Mock;
23+
import org.mockito.junit.MockitoJUnitRunner;
24+
25+
/** Tests for {@link HelpfulMessageBuilder}. */
26+
@RunWith(MockitoJUnitRunner.class)
27+
public class HelpfulMessageBuilderTest {
28+
29+
private static final HelpfulMessageBuilder testHelpfulMessageBuilder =
30+
new HelpfulMessageBuilder("message header");
31+
32+
@Mock private Throwable mockThrowable;
33+
34+
@Test
35+
public void testWithNoHelp() {
36+
String message = testHelpfulMessageBuilder.withNoHelp();
37+
Assert.assertEquals("message header", message);
38+
}
39+
40+
@Test
41+
public void testWithSuggestion() {
42+
String message = testHelpfulMessageBuilder.withSuggestion("do something");
43+
Assert.assertEquals("message header, perhaps you should do something", message);
44+
}
45+
}

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import com.google.cloud.tools.jib.builder.BuildImageSteps;
2222
import com.google.cloud.tools.jib.builder.SourceFilesConfiguration;
2323
import com.google.cloud.tools.jib.cache.Caches;
24+
import com.google.cloud.tools.jib.frontend.HelpfulMessageBuilder;
2425
import com.google.cloud.tools.jib.http.Authorization;
2526
import com.google.cloud.tools.jib.http.Authorizations;
2627
import com.google.cloud.tools.jib.image.ImageReference;
@@ -52,6 +53,9 @@ public class BuildImageTask extends DefaultTask {
5253
/** {@code User-Agent} header suffix to send to the registry. */
5354
private static final String USER_AGENT_SUFFIX = "jib-gradle-plugin";
5455

56+
private static final HelpfulMessageBuilder helpfulMessageBuilder =
57+
new HelpfulMessageBuilder("Build image failed");
58+
5559
/** Converts an {@link ImageConfiguration} to an {@link Authorization}. */
5660
@Nullable
5761
private static Authorization getImageAuthorization(ImageConfiguration imageConfiguration) {
@@ -181,7 +185,7 @@ private void doBuildImage(BuildImageSteps buildImageSteps) {
181185
buildImageSteps.run();
182186

183187
} catch (Throwable ex) {
184-
throw new GradleException("Build image failed", ex);
188+
throw new GradleException(helpfulMessageBuilder.withNoHelp(), ex);
185189
}
186190
// TODO: Catch and handle exceptions.
187191
}

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

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import com.google.cloud.tools.jib.builder.BuildConfiguration;
2020
import com.google.cloud.tools.jib.docker.DockerContextGenerator;
21+
import com.google.cloud.tools.jib.frontend.HelpfulMessageBuilder;
2122
import com.google.common.base.Preconditions;
2223
import com.google.common.io.InsecureRecursiveDeleteException;
2324
import java.io.IOException;
@@ -32,6 +33,9 @@
3233

3334
public class DockerContextTask extends DefaultTask {
3435

36+
private static final HelpfulMessageBuilder helpfulMessageBuilder =
37+
new HelpfulMessageBuilder("Export Docker context failed");
38+
3539
@Nullable private String targetDir;
3640
@Nullable private JibExtension jibExtension;
3741

@@ -94,29 +98,22 @@ public void generateDockerContext() {
9498
getLogger().info("Created Docker context at " + targetDir);
9599

96100
} catch (InsecureRecursiveDeleteException ex) {
97-
throwMojoExecutionExceptionWithHelpMessage(
98-
ex,
99-
"cannot clear directory '"
100-
+ targetDir
101-
+ "' safely - clear it manually before creating the Docker context");
101+
throw new GradleException(
102+
helpfulMessageBuilder.withSuggestion(
103+
"cannot clear directory '"
104+
+ targetDir
105+
+ "' safely - clear it manually before creating the Docker context"),
106+
ex);
102107

103108
} catch (IOException ex) {
104-
throwMojoExecutionExceptionWithHelpMessage(
105-
ex, "check if the command-line option `--jib.dockerDir` is set correctly");
109+
throw new GradleException(
110+
helpfulMessageBuilder.withSuggestion(
111+
"check if the command-line option `--jib.dockerDir` is set correctly"),
112+
ex);
106113
}
107114
}
108115

109116
void setJibExtension(JibExtension jibExtension) {
110117
this.jibExtension = jibExtension;
111118
}
112-
113-
private <T extends Throwable> void throwMojoExecutionExceptionWithHelpMessage(
114-
T ex, String suggestion) {
115-
StringBuilder message = new StringBuilder("Export Docker context failed");
116-
if (suggestion != null) {
117-
message.append(", perhaps you should ");
118-
message.append(suggestion);
119-
}
120-
throw new GradleException(message.toString(), ex);
121-
}
122119
}

‎jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/BuildImageMojo.java‎

Lines changed: 47 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import com.google.cloud.tools.jib.cache.CacheDirectoryNotOwnedException;
2525
import com.google.cloud.tools.jib.cache.CacheMetadataCorruptedException;
2626
import com.google.cloud.tools.jib.cache.Caches;
27+
import com.google.cloud.tools.jib.frontend.HelpfulMessageBuilder;
2728
import com.google.cloud.tools.jib.http.Authorization;
2829
import com.google.cloud.tools.jib.http.Authorizations;
2930
import com.google.cloud.tools.jib.image.ImageReference;
@@ -82,6 +83,9 @@ private Class<? extends BuildableManifestTemplate> getManifestTemplateClass() {
8283
/** {@code User-Agent} header suffix to send to the registry. */
8384
private static final String USER_AGENT_SUFFIX = "jib-maven-plugin";
8485

86+
private static final HelpfulMessageBuilder helpfulMessageBuilder =
87+
new HelpfulMessageBuilder("Build image failed");
88+
8589
@Nullable
8690
@Parameter(defaultValue = "${session}", readonly = true)
8791
private MavenSession session;
@@ -101,9 +105,10 @@ public void execute() throws MojoExecutionException, MojoFailureException {
101105
if (mainClass == null) {
102106
mainClass = projectProperties.getMainClassFromMavenJarPlugin();
103107
if (mainClass == null) {
104-
throwMojoExecutionExceptionWithHelpMessage(
105-
new MojoFailureException("Could not find main class specified in maven-jar-plugin"),
106-
"add a `mainClass` configuration to jib-maven-plugin");
108+
throw new MojoExecutionException(
109+
helpfulMessageBuilder.withSuggestion(
110+
"add a `mainClass` configuration to jib-maven-plugin"),
111+
new MojoFailureException("Could not find main class specified in maven-jar-plugin"));
107112
}
108113
}
109114
Preconditions.checkNotNull(mainClass);
@@ -190,17 +195,19 @@ void buildImage(BuildImageSteps buildImageSteps) throws MojoExecutionException {
190195
buildImageSteps.run();
191196

192197
} catch (CacheMetadataCorruptedException cacheMetadataCorruptedException) {
193-
throwMojoExecutionExceptionWithHelpMessage(
194-
cacheMetadataCorruptedException, "run 'mvn clean' to clear the cache");
198+
throw new MojoExecutionException(
199+
helpfulMessageBuilder.withSuggestion("run 'mvn clean' to clear the cache"),
200+
cacheMetadataCorruptedException);
195201

196202
} catch (ExecutionException executionException) {
197203
BuildConfiguration buildConfiguration = buildImageSteps.getBuildConfiguration();
198204

199205
if (executionException.getCause() instanceof HttpHostConnectException) {
200206
// Failed to connect to registry.
201-
throwMojoExecutionExceptionWithHelpMessage(
202-
executionException.getCause(),
203-
"make sure your Internet is up and that the registry you are pushing to exists");
207+
throw new MojoExecutionException(
208+
helpfulMessageBuilder.withSuggestion(
209+
"make sure your Internet is up and that the registry you are pushing to exists"),
210+
executionException.getCause());
204211

205212
} else if (executionException.getCause() instanceof RegistryUnauthorizedException) {
206213
handleRegistryUnauthorizedException(
@@ -216,26 +223,29 @@ void buildImage(BuildImageSteps buildImageSteps) throws MojoExecutionException {
216223
buildConfiguration);
217224

218225
} else if (executionException.getCause() instanceof UnknownHostException) {
219-
throwMojoExecutionExceptionWithHelpMessage(
220-
executionException.getCause(),
221-
"make sure that the registry you configured exists/is spelled properly");
226+
throw new MojoExecutionException(
227+
helpfulMessageBuilder.withSuggestion(
228+
"make sure that the registry you configured exists/is spelled properly"),
229+
executionException.getCause());
222230

223231
} else {
224-
throwMojoExecutionExceptionWithHelpMessage(executionException.getCause(), null);
232+
throw new MojoExecutionException(
233+
helpfulMessageBuilder.withNoHelp(), executionException.getCause());
225234
}
226235

227236
} catch (InterruptedException | IOException ex) {
228237
getLog().error(ex);
229238
// TODO: Add more suggestions for various build failures.
230-
throwMojoExecutionExceptionWithHelpMessage(ex, null);
239+
throw new MojoExecutionException(helpfulMessageBuilder.withNoHelp(), ex);
231240

232241
} catch (CacheDirectoryNotOwnedException ex) {
233-
throwMojoExecutionExceptionWithHelpMessage(
234-
ex,
235-
"check that '"
236-
+ ex.getCacheDirectory()
237-
+ "' is not used by another application or set the `useOnlyProjectCache` "
238-
+ "configuration");
242+
throw new MojoExecutionException(
243+
helpfulMessageBuilder.withSuggestion(
244+
"check that '"
245+
+ ex.getCacheDirectory()
246+
+ "' is not used by another application or set the `useOnlyProjectCache` "
247+
+ "configuration"),
248+
ex);
239249
}
240250
}
241251

@@ -319,10 +329,11 @@ private void handleRegistryUnauthorizedException(
319329
if (registryUnauthorizedException.getHttpResponseException().getStatusCode()
320330
== HttpStatusCodes.STATUS_CODE_FORBIDDEN) {
321331
// No permissions for registry/repository.
322-
throwMojoExecutionExceptionWithHelpMessage(
323-
registryUnauthorizedException,
324-
"make sure you have permissions for "
325-
+ registryUnauthorizedException.getImageReference());
332+
throw new MojoExecutionException(
333+
helpfulMessageBuilder.withSuggestion(
334+
"make sure you have permissions for "
335+
+ registryUnauthorizedException.getImageReference()),
336+
registryUnauthorizedException);
326337

327338
} else if ((buildConfiguration.getCredentialHelperNames() == null
328339
|| buildConfiguration.getCredentialHelperNames().isEmpty())
@@ -331,35 +342,23 @@ private void handleRegistryUnauthorizedException(
331342
.getKnownRegistryCredentials()
332343
.has(registryUnauthorizedException.getRegistry()))) {
333344
// No credential helpers defined.
334-
throwMojoExecutionExceptionWithHelpMessage(
335-
registryUnauthorizedException,
336-
"set a credential helper name with the configuration 'credHelpers' or "
337-
+ "set credentials for '"
338-
+ registryUnauthorizedException.getRegistry()
339-
+ "' in your Maven settings");
345+
throw new MojoExecutionException(
346+
helpfulMessageBuilder.withSuggestion(
347+
"set a credential helper name with the configuration 'credHelpers' or "
348+
+ "set credentials for '"
349+
+ registryUnauthorizedException.getRegistry()
350+
+ "' in your Maven settings"),
351+
registryUnauthorizedException);
340352

341353
} else {
342354
// Credential helper probably was not configured correctly or did not have the necessary
343355
// credentials.
344-
throwMojoExecutionExceptionWithHelpMessage(
345-
registryUnauthorizedException,
346-
"make sure your credentials for '"
347-
+ registryUnauthorizedException.getRegistry()
348-
+ "' are set up correctly");
349-
}
350-
}
351-
352-
/**
353-
* Wraps an exception in a {@link MojoExecutionException} and provides a suggestion on how to fix
354-
* the error.
355-
*/
356-
private <T extends Throwable> void throwMojoExecutionExceptionWithHelpMessage(
357-
T ex, @Nullable String suggestion) throws MojoExecutionException {
358-
StringBuilder message = new StringBuilder("Build image failed");
359-
if (suggestion != null) {
360-
message.append(", perhaps you should ");
361-
message.append(suggestion);
356+
throw new MojoExecutionException(
357+
helpfulMessageBuilder.withSuggestion(
358+
"make sure your credentials for '"
359+
+ registryUnauthorizedException.getRegistry()
360+
+ "' are set up correctly"),
361+
registryUnauthorizedException);
362362
}
363-
throw new MojoExecutionException(message.toString(), ex);
364363
}
365364
}

0 commit comments

Comments
 (0)