ImageAwareTrait.groovy
01 /*
02  * SPDX-License-Identifier: Apache-2.0
03  *
04  * Copyright 2019-2022 Andres Almiray.
05  *
06  * Licensed under the Apache License, Version 2.0 (the "License");
07  * you may not use this file except in compliance with the License.
08  * You may obtain a copy of the License at
09  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 package org.kordamp.gradle.plugin.oci.tasks.traits
19 
20 import com.oracle.bmc.core.ComputeClient
21 import com.oracle.bmc.core.model.Image
22 import com.oracle.bmc.core.requests.ListImagesRequest
23 import com.oracle.bmc.core.responses.ListImagesResponse
24 import groovy.transform.CompileStatic
25 import org.gradle.api.provider.Property
26 import org.gradle.api.provider.Provider
27 import org.gradle.api.tasks.Input
28 import org.gradle.api.tasks.Internal
29 import org.gradle.api.tasks.options.Option
30 import org.kordamp.gradle.plugin.oci.tasks.interfaces.ProjectAware
31 import org.kordamp.gradle.property.PathAware
32 import org.kordamp.gradle.property.SimpleStringState
33 import org.kordamp.gradle.property.StringState
34 
35 import static org.kordamp.gradle.util.StringUtils.isBlank
36 
37 /**
38  @author Andres Almiray
39  @since 0.1.0
40  */
41 @CompileStatic
42 trait ImageAwareTrait implements PathAware, ProjectAware {
43     private final StringState state = SimpleStringState.of(project, this, 'oci.image')
44 
45     @Internal
46     Property<String> getImage() {
47         state.property
48     }
49 
50     @Input
51     Provider<String> getResolvedImage() {
52         state.provider
53     }
54 
55     @Option(option = 'image', description = 'The Image of the Instance (REQUIRED).')
56     void setImage(String image) {
57         getImage().set(image)
58     }
59 
60     void validateImage() {
61         if (isBlank(getResolvedImage().orNull)) {
62             throw new IllegalStateException("Missing value for 'image' in $path")
63         }
64     }
65 
66     Image validateImage(ComputeClient client, String compartmentId) {
67         ListImagesResponse response = client.listImages(ListImagesRequest.builder()
68             .compartmentId(compartmentId)
69             .displayName(getResolvedImage().get())
70             .build())
71         Image image = response.items.find Image img -> img.displayName == getResolvedImage().get() }
72         if (!imagethrow new IllegalStateException("Invalid image ${getResolvedImage().get()}")
73         image
74     }
75 }