4
4
5
5
# ## Variables ###
6
6
7
+ [[ -n " ${USE_CACHE} " ]] || USE_CACHE=' true'
7
8
[[ $# == 1 ]] || { echo " Exactly one image to build must be specified!" ; exit 1; }
8
9
[[ -n " ${DOCKERFILE} " ]] || { echo " The DOCKERFILE to build from must be specified!" ; exit 1; }
9
10
[[ -n " ${HASHFILE} " ]] || { echo " The HASHFILE to write the hash to must be specified!" ; exit 1; }
@@ -21,6 +22,28 @@ source "${SCRIPTS_DIR}/lib/debug_functions"
21
22
local_image=" ${REPO} /${1} :${DEV_VERSION} "
22
23
cache_image=" ${REPO} /${1} :${CUTTING_EDGE} "
23
24
25
+ # When using cache pull latest image from the repo, so that its layers may be reused.
26
+ declare -a cache_flags
27
+ if [[ " ${USE_CACHE} " = true ]]; then
28
+ cache_flags+=(--cache-from " ${cache_image} " )
29
+ if [[ -z " $( docker image ls -q " ${cache_image} " ) " ]]; then
30
+ docker pull " ${cache_image} " || :
31
+ fi
32
+ # The shellcheck linting tool recommends piping to a while read loop, but that doesn't work for us
33
+ # because the while loop ends up in a subshell
34
+ # shellcheck disable=SC2013
35
+ for parent in $( awk ' /FROM/ {
36
+ for (i = 2; i <= NF; i++) {
37
+ if ($i == "AS") next;
38
+ if (!($i ~ /^--platform/ || $i ~ /scratch/))
39
+ print gensub("\\${BASE_BRANCH}", ENVIRON["BASE_BRANCH"], "g", $i)
40
+ }
41
+ }' " ${DOCKERFILE} " ) ; do
42
+ cache_flags+=(--cache-from " ${parent} " )
43
+ docker pull " ${parent} " || :
44
+ done
45
+ fi
46
+
24
47
output_flag=--load
25
48
[[ -z " ${OCIFILE} " ]] || output_flag=" --output=type=oci,dest=${OCIFILE} "
26
49
37
60
buildargs_flags=(--build-arg BUILDKIT_INLINE_CACHE=1 --build-arg " BASE_BRANCH=${BASE_BRANCH} " )
38
61
if [[ " ${PLATFORM} " != " ${default_platform} " ]] && docker buildx version > /dev/null 2>&1 ; then
39
62
docker buildx use buildx_builder || docker buildx create --name buildx_builder --use
40
- docker buildx build " ${output_flag} " -t " ${local_image} " -f " ${DOCKERFILE} " --iidfile " ${HASHFILE} " --platform " ${PLATFORM} " " ${buildargs_flags[@]} " .
63
+ docker buildx build " ${output_flag} " -t " ${local_image} " " ${cache_flags[@]} " -f " ${DOCKERFILE} " --iidfile " ${HASHFILE} " --platform " ${PLATFORM} " " ${buildargs_flags[@]} " .
41
64
else
42
65
# Fall back to plain BuildKit
43
66
if [[ " ${PLATFORM} " != " ${default_platform} " ]]; then
44
67
echo " WARNING: buildx isn't available, cross-arch builds won't work as expected"
45
68
fi
46
- DOCKER_BUILDKIT=1 docker build -t " ${local_image} " -f " ${DOCKERFILE} " --iidfile " ${HASHFILE} " " ${buildargs_flags[@]} " .
69
+ DOCKER_BUILDKIT=1 docker build -t " ${local_image} " " ${cache_flags[@]} " -f " ${DOCKERFILE} " --iidfile " ${HASHFILE} " " ${buildargs_flags[@]} " .
47
70
fi
48
71
49
72
# We can only tag the image in non-OCI mode
0 commit comments