Skip to content

Commit

Permalink
Add default target image name parameter for build to Docker daemon (#375
Browse files Browse the repository at this point in the history
)
  • Loading branch information
TadCordle authored Jun 6, 2018
1 parent d45c9da commit 5d7588c
Show file tree
Hide file tree
Showing 20 changed files with 267 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ public class JibPluginIntegrationTest {

@ClassRule public static final TestProject simpleTestProject = new TestProject("simple");

@ClassRule
public static final TestProject defaultTargetTestProject = new TestProject("default-target");

private static String buildAndRun(TestProject testProject, String imageReference)
throws IOException, InterruptedException {
BuildResult buildResult = testProject.build("clean", JibPlugin.BUILD_IMAGE_TASK_NAME);
Expand Down Expand Up @@ -98,6 +101,22 @@ public void testBuild_simple() throws IOException, InterruptedException {
buildAndRun(simpleTestProject, "gcr.io/jib-integration-testing/simpleimage:gradle"));
}

@Test
public void testBuild_defaultTarget() {
// Test error when 'to' is missing
try {
defaultTargetTestProject.build("clean", JibPlugin.BUILD_IMAGE_TASK_NAME, "-x=classes");
Assert.fail();
} catch (UnexpectedBuildFailure ex) {
Assert.assertThat(
ex.getMessage(),
CoreMatchers.containsString(
"Missing target image parameter. Add a 'jib.to.image' configuration parameter to "
+ "your build.gradle or set the parameter via commandline (e.g. 'gradle jib "
+ "--image <your image name>')."));
}
}

@Test
public void testDockerDaemon_empty() throws IOException, InterruptedException {
Assert.assertEquals(
Expand All @@ -114,6 +133,14 @@ public void testDockerDaemon_simple() throws IOException, InterruptedException {
simpleTestProject, "gcr.io/jib-integration-testing/simpleimage:gradle"));
}

@Test
public void testDockerDaemon_defaultTarget() throws IOException, InterruptedException {
Assert.assertEquals(
"Hello, world. An argument.\n",
buildToDockerDaemonAndRun(
defaultTargetTestProject, "default-target-name:default-target-version"));
}

@Test
public void testDockerContext() throws IOException, InterruptedException {
BuildResult buildResult =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
plugins {
id 'java'
id 'com.google.cloud.tools.jib'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
mavenCentral()
}

dependencies {
compile files('libs/dependency-1.0.0.jar')
}

jib {
args = ['An argument.']

// Does not have tests use user-level cache for base image layers.
useOnlyProjectCache = true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
version = default-target-version
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'default-target-name'
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* 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.test;

import dependency.Greeting;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/** Example class that uses a dependency and a resource file. */
public class HelloWorld {

public static void main(String[] args) throws IOException, URISyntaxException {
// 'Greeting' comes from the dependency artfiact.
String greeting = Greeting.getGreeting();

// Gets the contents of the resource file 'world'.
ClassLoader classLoader = HelloWorld.class.getClassLoader();
Path worldFile = Paths.get(classLoader.getResource("world").toURI());
String world = new String(Files.readAllBytes(worldFile), StandardCharsets.UTF_8);

System.out.println(greeting + ", " + world + ". " + (args.length > 0 ? args[0] : ""));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
world
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.google.cloud.tools.jib.registry.RegistryClient;
import com.google.cloud.tools.jib.registry.credentials.RegistryCredentials;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import javax.annotation.Nullable;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
Expand Down Expand Up @@ -56,7 +57,7 @@ public JibExtension getJib() {
return jibExtension;
}

/** The target image can be overriden with the {@code --image} command line option. */
/** The target image can be overridden with the {@code --image} command line option. */
@Option(option = "image", description = "The image reference for the target image")
public void setTargetImage(String targetImage) {
Preconditions.checkNotNull(jibExtension).getTo().setImage(targetImage);
Expand All @@ -80,10 +81,17 @@ public void buildDocker() throws InvalidImageReferenceException {
GradleProjectProperties gradleProjectProperties =
GradleProjectProperties.getForProject(getProject(), gradleBuildLogger);
String mainClass = gradleProjectProperties.getMainClass(jibExtension);

// TODO: Validate that project name and version are valid repository/tag
ImageReference targetImage =
Strings.isNullOrEmpty(jibExtension.getTargetImage())
? ImageReference.of(null, getProject().getName(), getProject().getVersion().toString())
: ImageReference.parse(jibExtension.getTargetImage());

BuildConfiguration buildConfiguration =
BuildConfiguration.builder(gradleBuildLogger)
.setBaseImage(ImageReference.parse(jibExtension.getBaseImage()))
.setTargetImage(ImageReference.parse(jibExtension.getTargetImage()))
.setTargetImage(targetImage)
.setBaseImageCredentialHelperName(jibExtension.getFrom().getCredHelper())
.setKnownBaseRegistryCredentials(knownBaseRegistryCredentials)
.setMainClass(mainClass)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import com.google.cloud.tools.jib.registry.RegistryClient;
import com.google.cloud.tools.jib.registry.credentials.RegistryCredentials;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import javax.annotation.Nullable;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
Expand Down Expand Up @@ -55,7 +56,7 @@ public JibExtension getJib() {
return jibExtension;
}

/** The target image can be overriden with the {@code --image} command line option. */
/** The target image can be overridden with the {@code --image} command line option. */
@Option(option = "image", description = "The image reference for the target image")
public void setTargetImage(String targetImage) {
Preconditions.checkNotNull(jibExtension).getTo().setImage(targetImage);
Expand All @@ -66,6 +67,13 @@ public void buildImage() throws InvalidImageReferenceException {
// Asserts required @Input parameters are not null.
Preconditions.checkNotNull(jibExtension);

if (Strings.isNullOrEmpty(jibExtension.getTargetImage())) {
throw new GradleException(
"Missing target image parameter. Add a 'jib.to.image' configuration parameter to your "
+ "build.gradle or set the parameter via commandline (e.g. 'gradle jib --image "
+ "<your image name>').");
}

RegistryCredentials knownBaseRegistryCredentials = null;
RegistryCredentials knownTargetRegistryCredentials = null;
Authorization fromAuthorization = jibExtension.getFrom().getImageAuthorization();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public ImageConfiguration(ObjectFactory objectFactory) {

@Input
@Nullable
@Optional
public String getImage() {
return image;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,9 @@ String getBaseImage() {
}

@Internal
@Nullable
String getTargetImage() {
return Preconditions.checkNotNull(to.getImage());
return to.getImage();
}

@Nested
Expand All @@ -155,6 +156,8 @@ ImageConfiguration getFrom() {
return from;
}

@Nested
@Optional
ImageConfiguration getTo() {
return to;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import com.google.cloud.tools.jib.registry.credentials.RegistryCredentials;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
Expand Down Expand Up @@ -54,7 +55,12 @@ public void execute() throws MojoExecutionException {

// Parses 'from' and 'to' into image reference.
ImageReference baseImage = parseBaseImageReference(getBaseImage());
ImageReference targetImage = parseTargetImageReference(getTargetImage());

// TODO: Validate that project name and version are valid repository/tag
ImageReference targetImage =
Strings.isNullOrEmpty(getTargetImage())
? ImageReference.of(null, getProject().getName(), getProject().getVersion())
: parseTargetImageReference(getTargetImage());

// Checks Maven settings for registry credentials.
MavenSettingsServerCredentials mavenSettingsServerCredentials =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import com.google.cloud.tools.jib.registry.credentials.RegistryCredentials;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.util.Arrays;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
Expand Down Expand Up @@ -80,8 +81,17 @@ public void execute() throws MojoExecutionException, MojoFailureException {
+ "'.");
}

// Parses 'from' and 'to' into image reference.
// Parses 'from' into image reference.
ImageReference baseImage = parseBaseImageReference(getBaseImage());

// Parses 'to' into image reference.
if (Strings.isNullOrEmpty(getTargetImage())) {
// TODO: Consolidate with gradle message
throw new MojoFailureException(
"Missing target image parameter. Add a <to><image> configuration parameter to your "
+ "pom.xml or set the parameter via commandline (e.g. 'mvn compile jib:build "
+ "-Dimage=<your image name>').");
}
ImageReference targetImage = parseTargetImageReference(getTargetImage());

// Checks Maven settings for registry credentials.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ public static class FromConfiguration {
/** Configuration for {@code to} parameter, where image is required. */
public static class ToConfiguration {

@Nullable
@Parameter(required = true)
private String image;
@Nullable @Parameter private String image;

@Nullable @Parameter private String credHelper;

Expand Down Expand Up @@ -85,11 +83,10 @@ static ImageReference parseTargetImageReference(String to) {
@Parameter(defaultValue = "${session}", readonly = true)
MavenSession session;

@Nullable @Parameter private FromConfiguration from = new FromConfiguration();
@Parameter private FromConfiguration from = new FromConfiguration();

@Nullable
@Parameter(property = "image", required = true)
private ToConfiguration to;
@Parameter(property = "image")
private ToConfiguration to = new ToConfiguration();

@Parameter private List<String> jvmFlags = Collections.emptyList();

Expand Down Expand Up @@ -119,8 +116,9 @@ String getBaseImageCredentialHelperName() {
return Preconditions.checkNotNull(from).credHelper;
}

@Nullable
String getTargetImage() {
return Preconditions.checkNotNull(Preconditions.checkNotNull(to).image);
return to.image;
}

@Nullable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ public class BuildDockerMojoIntegrationTest {
@ClassRule
public static final TestProject emptyTestProject = new TestProject(testPlugin, "empty");

@ClassRule
public static final TestProject defaultTargetTestProject =
new TestProject(testPlugin, "default-target");

/**
* Builds and runs jib:buildDocker on a project at {@code projectRoot} pushing to {@code
* imageReference}.
Expand Down Expand Up @@ -69,4 +73,14 @@ public void testExecute_empty() throws InterruptedException, IOException, Verifi
buildToDockerDaemonAndRun(
emptyTestProject.getProjectRoot(), "gcr.io/jib-integration-testing/emptyimage:maven"));
}

@Test
public void testExecute_defaultTarget()
throws VerificationException, IOException, InterruptedException {
Assert.assertEquals(
"Hello, world. An argument.\n",
buildToDockerDaemonAndRun(
defaultTargetTestProject.getProjectRoot(),
"default-target-name:default-target-version"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ public class BuildImageMojoIntegrationTest {
@ClassRule
public static final TestProject emptyTestProject = new TestProject(testPlugin, "empty");

@ClassRule
public static final TestProject defaultTargetTestProject =
new TestProject(testPlugin, "default-target");

/**
* Builds and runs jib:build on a project at {@code projectRoot} pushing to {@code
* imageReference}.
Expand Down Expand Up @@ -102,4 +106,22 @@ public void testExecute_empty() throws InterruptedException, IOException, Verifi
buildAndRun(
emptyTestProject.getProjectRoot(), "gcr.io/jib-integration-testing/emptyimage:maven"));
}

@Test
public void testExecute_defaultTarget() {
// Test error when 'to' is missing
try {
Verifier verifier = new Verifier(defaultTargetTestProject.getProjectRoot().toString());
verifier.setAutoclean(false);
verifier.executeGoals(Arrays.asList("clean", "jib:" + BuildImageMojo.GOAL_NAME));
Assert.fail();
} catch (VerificationException ex) {
Assert.assertThat(
ex.getMessage(),
CoreMatchers.containsString(
"Missing target image parameter. Add a <to><image> configuration parameter to your "
+ "pom.xml or set the parameter via commandline (e.g. 'mvn compile jib:build "
+ "-Dimage=<your image name>')."));
}
}
}
Binary file not shown.
Loading

0 comments on commit 5d7588c

Please sign in to comment.