Skip to content

Instantly share code, notes, and snippets.

@regisb
Last active April 14, 2023 14:47
Show Gist options
  • Save regisb/4049622ec4b48cbd48c89ec708dc5252 to your computer and use it in GitHub Desktop.
Save regisb/4049622ec4b48cbd48c89ec708dc5252 to your computer and use it in GitHub Desktop.
# Usage
#
# tutor plugins install https://gist.githubusercontent.com/regisb/4049622ec4b48cbd48c89ec708dc5252/raw/docker-registry-cache.py
# tutor plugins enable docker-registry-cache
#
# Cache will automatically be pulled from registry when you run:
#
# tutor images build openedx
#
# You can also push after building:
#
# tutor images build --docker-arg=push-cache openedx
from __future__ import annotations
from tutor import hooks
@hooks.Filters.DOCKER_BUILD_COMMAND.add()
def _cache_from(command: list[str]) -> list[str]:
if command[0] not in ("build", "buildx"):
return command
# Use buildkit
if command[0] != "buildx":
command.insert(0, "buildx")
# Find the image tag
tag_arg = "-t" if "-t" in command else "--tag"
try:
tag_arg_index = command.index(tag_arg)
except ValueError:
# it's weird but we didn't find the tag
return command
# Add the --cache-from args
tag = command[tag_arg_index + 1]
# Use the image tag to determine the cache image tag
command.insert(tag_arg_index, f"--cache-from=type=registry,ref={tag}-cache")
# Do we also want to push the cache to the registry?
if "push-cache" in command:
command[
command.index("push-cache")
] = f"--cache-to=type=registry,mode=max,ref={tag}-cache"
# Add image to docker
command.insert(tag_arg_index, "--load")
return command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment