From 29ef7d277eb5cf499d941fec82b0ccc6ce0abe58 Mon Sep 17 00:00:00 2001 From: Mridula <66699525+mpeddada1@users.noreply.github.com> Date: Thu, 7 Jan 2021 21:11:51 -0500 Subject: [PATCH] Add option to specify base image for cli jar command (#2972) * add base image option --- .../cloud/tools/jib/cli/JarCommandTest.java | 16 +++ .../tools/jib/cli/ContainerBuilders.java | 82 +++++++++++++ .../com/google/cloud/tools/jib/cli/Jar.java | 20 +++- .../tools/jib/cli/buildfile/BuildFiles.java | 63 +++------- .../cloud/tools/jib/cli/jar/JarFiles.java | 22 +++- .../api/JibContainerBuilderTestHelper.java | 31 +++++ .../tools/jib/cli/ContainerBuildersTest.java | 111 ++++++++++++++++++ .../google/cloud/tools/jib/cli/JarTest.java | 8 ++ .../cloud/tools/jib/cli/jar/JarFilesTest.java | 27 ++++- 9 files changed, 323 insertions(+), 57 deletions(-) create mode 100644 jib-cli/src/main/java/com/google/cloud/tools/jib/cli/ContainerBuilders.java create mode 100644 jib-cli/src/test/java/com/google/cloud/tools/jib/api/JibContainerBuilderTestHelper.java create mode 100644 jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerBuildersTest.java diff --git a/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/JarCommandTest.java b/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/JarCommandTest.java index 532d7e8ea0..8170809bd0 100644 --- a/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/JarCommandTest.java +++ b/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/JarCommandTest.java @@ -239,6 +239,22 @@ public void testSpringBootJar_packagedMode() throws IOException, InterruptedExce assertThat(getContent(new URL("http://localhost:8080"))).isEqualTo("Hello world"); } + @Test + public void testJar_baseImageSpecified() + throws IOException, URISyntaxException, InterruptedException { + Path jarPath = Paths.get(Resources.getResource("jarTest/standard/noDependencyJar.jar").toURI()); + Integer exitCode = + new CommandLine(new JibCli()) + .execute( + "jar", + "--target=docker://cli-gcr-base", + "--from=gcr.io/google-appengine/openjdk:8", + jarPath.toString()); + assertThat(exitCode).isEqualTo(0); + String output = new Command("docker", "run", "--rm", "cli-gcr-base").run(); + assertThat(output).isEqualTo("Hello World"); + } + @Nullable private static String getContent(URL url) throws InterruptedException { for (int i = 0; i < 40; i++) { diff --git a/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/ContainerBuilders.java b/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/ContainerBuilders.java new file mode 100644 index 0000000000..50d263441f --- /dev/null +++ b/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/ContainerBuilders.java @@ -0,0 +1,82 @@ +/* + * Copyright 2021 Google LLC. + * + * 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.cli; + +import static com.google.cloud.tools.jib.api.Jib.DOCKER_DAEMON_IMAGE_PREFIX; +import static com.google.cloud.tools.jib.api.Jib.REGISTRY_IMAGE_PREFIX; +import static com.google.cloud.tools.jib.api.Jib.TAR_IMAGE_PREFIX; + +import com.google.cloud.tools.jib.api.DockerDaemonImage; +import com.google.cloud.tools.jib.api.ImageReference; +import com.google.cloud.tools.jib.api.InvalidImageReferenceException; +import com.google.cloud.tools.jib.api.Jib; +import com.google.cloud.tools.jib.api.JibContainerBuilder; +import com.google.cloud.tools.jib.api.RegistryImage; +import com.google.cloud.tools.jib.api.TarImage; +import com.google.cloud.tools.jib.api.buildplan.Platform; +import com.google.cloud.tools.jib.frontend.CredentialRetrieverFactory; +import com.google.cloud.tools.jib.plugins.common.DefaultCredentialRetrievers; +import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger; +import java.io.FileNotFoundException; +import java.nio.file.Paths; +import java.util.Set; + +/** Helper class for creating JibContainerBuilders from JibCli specifications. */ +public class ContainerBuilders { + + /** + * Creates a {@link JibContainerBuilder} depending on the base image specified. + * + * @param baseImageReference base image reference + * @param platforms platforms for multi-platform support in build command + * @param commonCliOptions common cli options + * @param logger console logger + * @return a {@link JibContainerBuilder} + * @throws InvalidImageReferenceException if the baseImage reference cannot be parsed + * @throws FileNotFoundException if credential helper file cannot be found + */ + public static JibContainerBuilder create( + String baseImageReference, + Set platforms, + CommonCliOptions commonCliOptions, + ConsoleLogger logger) + throws InvalidImageReferenceException, FileNotFoundException { + if (baseImageReference.startsWith(DOCKER_DAEMON_IMAGE_PREFIX)) { + return Jib.from( + DockerDaemonImage.named(baseImageReference.replaceFirst(DOCKER_DAEMON_IMAGE_PREFIX, ""))); + } + if (baseImageReference.startsWith(TAR_IMAGE_PREFIX)) { + return Jib.from( + TarImage.at(Paths.get(baseImageReference.replaceFirst(TAR_IMAGE_PREFIX, "")))); + } + ImageReference imageReference = + ImageReference.parse(baseImageReference.replaceFirst(REGISTRY_IMAGE_PREFIX, "")); + RegistryImage registryImage = RegistryImage.named(imageReference); + DefaultCredentialRetrievers defaultCredentialRetrievers = + DefaultCredentialRetrievers.init( + CredentialRetrieverFactory.forImage( + imageReference, + logEvent -> logger.log(logEvent.getLevel(), logEvent.getMessage()))); + Credentials.getFromCredentialRetrievers(commonCliOptions, defaultCredentialRetrievers) + .forEach(registryImage::addCredentialRetriever); + JibContainerBuilder containerBuilder = Jib.from(registryImage); + if (!platforms.isEmpty()) { + containerBuilder.setPlatforms(platforms); + } + return containerBuilder; + } +} diff --git a/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/Jar.java b/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/Jar.java index a26df3e887..c396e5ddf6 100644 --- a/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/Jar.java +++ b/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/Jar.java @@ -31,6 +31,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; +import java.util.Optional; import java.util.concurrent.Callable; import picocli.CommandLine; import picocli.CommandLine.Model.CommandSpec; @@ -64,6 +65,13 @@ public class Jar implements Callable { @SuppressWarnings("NullAway.Init") // initialized by picocli private ProcessingMode mode; + @CommandLine.Option( + names = "--from", + paramLabel = "", + description = "The base image to use.") + @SuppressWarnings("NullAway.Init") // initialized by picocli + private String from; + @Override public Integer call() { try { @@ -98,7 +106,8 @@ public Integer call() { } JarProcessor processor = JarProcessors.from(jarFile, tempDirectoryProvider, mode); - JibContainerBuilder containerBuilder = JarFiles.toJibContainerBuilder(processor); + JibContainerBuilder containerBuilder = + JarFiles.toJibContainerBuilder(processor, this, commonCliOptions, logger); CacheDirectories cacheDirectories = CacheDirectories.from(commonCliOptions, jarFile.toAbsolutePath().getParent()); Containerizer containerizer = Containerizers.from(commonCliOptions, logger, cacheDirectories); @@ -114,4 +123,13 @@ public Integer call() { } return 0; } + + /** + * Returns the user specified base image. + * + * @return an optional base image + */ + public Optional getFrom() { + return Optional.ofNullable(from); + } } diff --git a/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/buildfile/BuildFiles.java b/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/buildfile/BuildFiles.java index db31c47156..a8d46c7b89 100644 --- a/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/buildfile/BuildFiles.java +++ b/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/buildfile/BuildFiles.java @@ -16,34 +16,24 @@ package com.google.cloud.tools.jib.cli.buildfile; -import static com.google.cloud.tools.jib.api.Jib.DOCKER_DAEMON_IMAGE_PREFIX; -import static com.google.cloud.tools.jib.api.Jib.REGISTRY_IMAGE_PREFIX; -import static com.google.cloud.tools.jib.api.Jib.TAR_IMAGE_PREFIX; - import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import com.google.cloud.tools.jib.api.DockerDaemonImage; -import com.google.cloud.tools.jib.api.ImageReference; import com.google.cloud.tools.jib.api.InvalidImageReferenceException; import com.google.cloud.tools.jib.api.Jib; import com.google.cloud.tools.jib.api.JibContainerBuilder; -import com.google.cloud.tools.jib.api.RegistryImage; -import com.google.cloud.tools.jib.api.TarImage; import com.google.cloud.tools.jib.api.buildplan.Platform; import com.google.cloud.tools.jib.cli.Build; import com.google.cloud.tools.jib.cli.CommonCliOptions; -import com.google.cloud.tools.jib.cli.Credentials; -import com.google.cloud.tools.jib.frontend.CredentialRetrieverFactory; -import com.google.cloud.tools.jib.plugins.common.DefaultCredentialRetrievers; +import com.google.cloud.tools.jib.cli.ContainerBuilders; import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger; import com.google.common.base.Charsets; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.LinkedHashSet; import java.util.Map; +import java.util.Optional; import java.util.stream.Collectors; import org.apache.commons.text.StringSubstitutor; import org.apache.commons.text.io.StringSubstitutorReader; @@ -87,10 +77,10 @@ public static JibContainerBuilder toJibContainerBuilder( throws InvalidImageReferenceException, IOException { BuildFileSpec buildFile = toBuildFileSpec(buildFilePath, buildCommandOptions.getTemplateParameters()); - + Optional baseImageSpec = buildFile.getFrom(); JibContainerBuilder containerBuilder = - buildFile.getFrom().isPresent() - ? createJibContainerBuilder(buildFile.getFrom().get(), commonCliOptions, logger) + baseImageSpec.isPresent() + ? createJibContainerBuilder(baseImageSpec.get(), commonCliOptions, logger) : Jib.fromScratch(); buildFile.getCreationTime().ifPresent(containerBuilder::setCreationTime); @@ -111,40 +101,15 @@ public static JibContainerBuilder toJibContainerBuilder( return containerBuilder; } - // TODO: add testing, need to do via intergration tests as there's no good way to extract out that - // the base image was populated as the user intended currently. - static JibContainerBuilder createJibContainerBuilder( - BaseImageSpec from, CommonCliOptions commonCliOptions, ConsoleLogger logger) + private static JibContainerBuilder createJibContainerBuilder( + BaseImageSpec baseImageSpec, CommonCliOptions commonCliOptions, ConsoleLogger logger) throws InvalidImageReferenceException, FileNotFoundException { - String baseImageReference = from.getImage(); - if (baseImageReference.startsWith(DOCKER_DAEMON_IMAGE_PREFIX)) { - return Jib.from( - DockerDaemonImage.named(baseImageReference.replaceFirst(DOCKER_DAEMON_IMAGE_PREFIX, ""))); - } - if (baseImageReference.startsWith(TAR_IMAGE_PREFIX)) { - return Jib.from( - TarImage.at(Paths.get(baseImageReference.replaceFirst(TAR_IMAGE_PREFIX, "")))); - } - ImageReference imageReference = - ImageReference.parse(baseImageReference.replaceFirst(REGISTRY_IMAGE_PREFIX, "")); - RegistryImage registryImage = RegistryImage.named(imageReference); - DefaultCredentialRetrievers defaultCredentialRetrievers = - DefaultCredentialRetrievers.init( - CredentialRetrieverFactory.forImage( - imageReference, - logEvent -> logger.log(logEvent.getLevel(), logEvent.getMessage()))); - Credentials.getFromCredentialRetrievers(commonCliOptions, defaultCredentialRetrievers) - .forEach(registryImage::addCredentialRetriever); - JibContainerBuilder containerBuilder = Jib.from(registryImage); - if (!from.getPlatforms().isEmpty()) { - containerBuilder.setPlatforms( - from.getPlatforms() - .stream() - .map( - platformSpec -> - new Platform(platformSpec.getArchitecture(), platformSpec.getOs())) - .collect(Collectors.toCollection(LinkedHashSet::new))); - } - return containerBuilder; + LinkedHashSet platforms = + baseImageSpec + .getPlatforms() + .stream() + .map(platformSpec -> new Platform(platformSpec.getArchitecture(), platformSpec.getOs())) + .collect(Collectors.toCollection(LinkedHashSet::new)); + return ContainerBuilders.create(baseImageSpec.getImage(), platforms, commonCliOptions, logger); } } diff --git a/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/jar/JarFiles.java b/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/jar/JarFiles.java index 93620ad1c7..bfed786ef7 100644 --- a/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/jar/JarFiles.java +++ b/jib-cli/src/main/java/com/google/cloud/tools/jib/cli/jar/JarFiles.java @@ -20,7 +20,12 @@ import com.google.cloud.tools.jib.api.Jib; import com.google.cloud.tools.jib.api.JibContainerBuilder; import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer; +import com.google.cloud.tools.jib.cli.CommonCliOptions; +import com.google.cloud.tools.jib.cli.ContainerBuilders; +import com.google.cloud.tools.jib.cli.Jar; +import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger; import java.io.IOException; +import java.util.Collections; import java.util.List; /** Class to build a container representation from the contents of a jar file. */ @@ -30,16 +35,27 @@ public class JarFiles { * Generates a {@link JibContainerBuilder} from contents of a jar file. * * @param processor jar processor + * @param jarOptions jar cli options + * @param commonCliOptions common cli options + * @param logger console logger * @return JibContainerBuilder * @throws IOException if I/O error occurs when opening the jar file or if temporary directory * provided doesn't exist * @throws InvalidImageReferenceException if the base image reference is invalid */ - public static JibContainerBuilder toJibContainerBuilder(JarProcessor processor) + public static JibContainerBuilder toJibContainerBuilder( + JarProcessor processor, + Jar jarOptions, + CommonCliOptions commonCliOptions, + ConsoleLogger logger) throws IOException, InvalidImageReferenceException { - // Use distroless as the base image. - JibContainerBuilder containerBuilder = Jib.from("gcr.io/distroless/java"); + // Use distroless as the default base image. + JibContainerBuilder containerBuilder = + jarOptions.getFrom().isPresent() + ? ContainerBuilders.create( + jarOptions.getFrom().get(), Collections.emptySet(), commonCliOptions, logger) + : Jib.from("gcr.io/distroless/java"); List layers = processor.createLayers(); List entrypoint = processor.computeEntrypoint(); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/api/JibContainerBuilderTestHelper.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/api/JibContainerBuilderTestHelper.java new file mode 100644 index 0000000000..6534a32a88 --- /dev/null +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/api/JibContainerBuilderTestHelper.java @@ -0,0 +1,31 @@ +/* + * Copyright 2021 Google LLC. + * + * 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.api; + +import com.google.cloud.tools.jib.configuration.BuildContext; + +/** Test helper to expose package-private members of {@link JibContainerBuilder}. */ +public class JibContainerBuilderTestHelper { + + public static BuildContext toBuildContext( + JibContainerBuilder jibContainerBuilder, Containerizer containerizer) + throws CacheDirectoryCreationException { + return jibContainerBuilder.toBuildContext(containerizer); + } + + private JibContainerBuilderTestHelper() {} +} diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerBuildersTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerBuildersTest.java new file mode 100644 index 0000000000..98f9358eea --- /dev/null +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerBuildersTest.java @@ -0,0 +1,111 @@ +/* + * Copyright 2021 Google LLC. + * + * 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.cli; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.tools.jib.api.CacheDirectoryCreationException; +import com.google.cloud.tools.jib.api.Containerizer; +import com.google.cloud.tools.jib.api.InvalidImageReferenceException; +import com.google.cloud.tools.jib.api.JibContainerBuilder; +import com.google.cloud.tools.jib.api.JibContainerBuilderTestHelper; +import com.google.cloud.tools.jib.api.RegistryImage; +import com.google.cloud.tools.jib.api.buildplan.Platform; +import com.google.cloud.tools.jib.configuration.BuildContext; +import com.google.cloud.tools.jib.configuration.ImageConfiguration; +import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger; +import com.google.common.collect.ImmutableSet; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.Optional; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +/** Tests for {@link ContainerBuilders}. */ +@RunWith(MockitoJUnitRunner.class) +public class ContainerBuildersTest { + + @Mock private CommonCliOptions mockCommonCliOptions; + + @Mock private ConsoleLogger mockLogger; + + @Test + public void testCreate_dockerBaseImage() + throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException { + JibContainerBuilder containerBuilder = + ContainerBuilders.create( + "docker://docker-image-ref", Collections.emptySet(), mockCommonCliOptions, mockLogger); + BuildContext buildContext = + JibContainerBuilderTestHelper.toBuildContext( + containerBuilder, Containerizer.to(RegistryImage.named("ignored"))); + ImageConfiguration imageConfiguration = buildContext.getBaseImageConfiguration(); + + assertThat(imageConfiguration.getImage().toString()).isEqualTo("docker-image-ref"); + assertThat(imageConfiguration.getDockerClient().isPresent()).isTrue(); + assertThat(imageConfiguration.getTarPath().isPresent()).isFalse(); + } + + @Test + public void testCreate_registry() + throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException { + JibContainerBuilder containerBuilder = + ContainerBuilders.create( + "registry://registry-image-ref", + Collections.emptySet(), + mockCommonCliOptions, + mockLogger); + BuildContext buildContext = + JibContainerBuilderTestHelper.toBuildContext( + containerBuilder, Containerizer.to(RegistryImage.named("ignored"))); + ImageConfiguration imageConfiguration = buildContext.getBaseImageConfiguration(); + + assertThat(imageConfiguration.getImage().toString()).isEqualTo("registry-image-ref"); + assertThat(imageConfiguration.getDockerClient().isPresent()).isFalse(); + assertThat(imageConfiguration.getTarPath().isPresent()).isFalse(); + } + + @Test + public void testCreate_tarBase() + throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException { + JibContainerBuilder containerBuilder = + ContainerBuilders.create( + "tar:///path/to.tar", Collections.emptySet(), mockCommonCliOptions, mockLogger); + BuildContext buildContext = + JibContainerBuilderTestHelper.toBuildContext( + containerBuilder, Containerizer.to(RegistryImage.named("ignored"))); + ImageConfiguration imageConfiguration = buildContext.getBaseImageConfiguration(); + + assertThat(imageConfiguration.getTarPath()).isEqualTo(Optional.of(Paths.get("/path/to.tar"))); + assertThat(imageConfiguration.getDockerClient().isPresent()).isFalse(); + } + + @Test + public void testCreate_platforms() throws IOException, InvalidImageReferenceException { + JibContainerBuilder containerBuilder = + ContainerBuilders.create( + "registry://registry-image-ref", + ImmutableSet.of(new Platform("arch1", "os1"), new Platform("arch2", "os2")), + mockCommonCliOptions, + mockLogger); + + assertThat(containerBuilder.toContainerBuildPlan().getPlatforms()) + .isEqualTo(ImmutableSet.of(new Platform("arch1", "os1"), new Platform("arch2", "os2"))); + } +} diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JarTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JarTest.java index 1d1a5c043f..c5b14f13d2 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JarTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JarTest.java @@ -403,6 +403,14 @@ public void testParse_incompatibleCredentialOptions(String[] authArgs) { .containsMatch("^Error: (--(from-|to-)?credential-helper|\\[--username)"); } + @Test + public void testParse_from() { + Jar jarCommand = + CommandLine.populateCommand( + new Jar(), "--target", "test-image-ref", "--from", "base-image-ref", "my-app.jar"); + assertThat(jarCommand.getFrom()).hasValue("base-image-ref"); + } + @Test public void testValidate_nameMissingFail() { Jar jarCommand = diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/JarFilesTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/JarFilesTest.java index 299fb11963..127871b3d6 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/JarFilesTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/JarFilesTest.java @@ -25,12 +25,16 @@ import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer; import com.google.cloud.tools.jib.api.buildplan.ImageFormat; import com.google.cloud.tools.jib.api.buildplan.Platform; +import com.google.cloud.tools.jib.cli.CommonCliOptions; +import com.google.cloud.tools.jib.cli.Jar; +import com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.nio.file.Paths; import java.time.Instant; import java.util.Arrays; +import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -49,6 +53,12 @@ public class JarFilesTest { @Mock private SpringBootPackagedProcessor mockSpringBootPackagedProcessor; + @Mock private Jar mockJarCommand; + + @Mock private CommonCliOptions mockCommonCliOptions; + + @Mock private ConsoleLogger mockLogger; + @Test public void testToJibContainerBuilder_explodedStandard_basicInfo() throws IOException, InvalidImageReferenceException { @@ -63,9 +73,11 @@ public void testToJibContainerBuilder_explodedStandard_basicInfo() Mockito.when(mockStandardExplodedProcessor.computeEntrypoint()) .thenReturn( ImmutableList.of("java", "-cp", "/app/explodedJar:/app/dependencies/*", "HelloWorld")); + Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty()); JibContainerBuilder containerBuilder = - JarFiles.toJibContainerBuilder(mockStandardExplodedProcessor); + JarFiles.toJibContainerBuilder( + mockStandardExplodedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger); ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan(); assertThat(buildPlan.getBaseImage()).isEqualTo("gcr.io/distroless/java"); @@ -105,9 +117,11 @@ public void testToJibContainerBuilder_packagedStandard_basicInfo() Mockito.when(mockStandardPackagedProcessor.createLayers()).thenReturn(Arrays.asList(layer)); Mockito.when(mockStandardPackagedProcessor.computeEntrypoint()) .thenReturn(ImmutableList.of("java", "-jar", "/app/standardJar.jar")); + Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty()); JibContainerBuilder containerBuilder = - JarFiles.toJibContainerBuilder(mockStandardPackagedProcessor); + JarFiles.toJibContainerBuilder( + mockStandardPackagedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger); ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan(); assertThat(buildPlan.getBaseImage()).isEqualTo("gcr.io/distroless/java"); @@ -143,13 +157,16 @@ public void testToJibContainerBuilder_explodedLayeredSpringBoot_basicInfo() Paths.get("path/to/tempDirectory/BOOT-INF/classes/class1.class"), AbsoluteUnixPath.get("/app/BOOT-INF/classes/class1.class")) .build(); + Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty()); Mockito.when(mockSpringBootExplodedProcessor.createLayers()).thenReturn(Arrays.asList(layer)); Mockito.when(mockSpringBootExplodedProcessor.computeEntrypoint()) .thenReturn( ImmutableList.of("java", "-cp", "/app", "org.springframework.boot.loader.JarLauncher")); + Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty()); JibContainerBuilder containerBuilder = - JarFiles.toJibContainerBuilder(mockSpringBootExplodedProcessor); + JarFiles.toJibContainerBuilder( + mockSpringBootExplodedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger); ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan(); assertThat(buildPlan.getBaseImage()).isEqualTo("gcr.io/distroless/java"); @@ -189,9 +206,11 @@ public void testToJibContainerBuilder_packagedSpringBoot_basicInfo() Mockito.when(mockSpringBootPackagedProcessor.createLayers()).thenReturn(Arrays.asList(layer)); Mockito.when(mockSpringBootPackagedProcessor.computeEntrypoint()) .thenReturn(ImmutableList.of("java", "-jar", "/app/spring-boot.jar")); + Mockito.when(mockJarCommand.getFrom()).thenReturn(Optional.empty()); JibContainerBuilder containerBuilder = - JarFiles.toJibContainerBuilder(mockSpringBootPackagedProcessor); + JarFiles.toJibContainerBuilder( + mockSpringBootPackagedProcessor, mockJarCommand, mockCommonCliOptions, mockLogger); ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan(); assertThat(buildPlan.getBaseImage()).isEqualTo("gcr.io/distroless/java");