From c7b6459723d74853553c8f22574abda246dfc81d Mon Sep 17 00:00:00 2001
From: Moul <moul@moul.re>
Date: Thu, 9 Jan 2025 19:18:51 +0100
Subject: [PATCH] containers: improve layers build

Create a cached layer for downloaded dependencies
which does not get invalidated by sources change

Copy pyproject.toml first,
install dependencies as a layer,
which is only invalidated when this file changes

Then copy sources and build layer
If the sources changes, the layer
cache is invalidated and therefore rebuilt
---
 image/pip    | 11 ++++++++---
 image/poetry |  8 +++++++-
 2 files changed, 15 insertions(+), 4 deletions(-)

diff --git a/image/pip b/image/pip
index ff099e56..9ce53568 100644
--- a/image/pip
+++ b/image/pip
@@ -9,10 +9,15 @@ RUN pip install "poetry>=1.8,<2.0"
 
 WORKDIR /silkaj
 
-# Copy source tree
+# Copy pyproject.toml and install dependencies
+# So this dependencies installation layer
+# does not change when the sources changes
+# https://python-poetry.org/docs/faq/#poetry-busts-my-docker-cache-because-it-requires-me-to-copy-my-source-files-in-before-installing-3rd-party-dependencies
+COPY pyproject.toml .
+RUN poetry install --only main --no-root
+
+# Copy source tree, install and build Silkaj
 COPY ./ ./
-
-# Install Silkaj
 RUN poetry install --only main --extras deathreaper
 RUN poetry build
 
diff --git a/image/poetry b/image/poetry
index 759e324d..96eb0d39 100644
--- a/image/poetry
+++ b/image/poetry
@@ -6,6 +6,13 @@ FROM registry.duniter.org/docker/python3/poetry/${PYTHON_VERS}:latest AS build
 
 WORKDIR /silkaj
 
+# Copy pyproject.toml and install dependencies
+# So this dependencies installation layer
+# does not change when the sources changes
+# https://python-poetry.org/docs/faq/#poetry-busts-my-docker-cache-because-it-requires-me-to-copy-my-source-files-in-before-installing-3rd-party-dependencies
+COPY pyproject.toml .
+RUN poetry install --only main --no-root
+
 # Copy source tree
 COPY ./ ./
 
@@ -16,7 +23,6 @@ RUN poetry install --only main --extras deathreaper
 # Final Stage
 # ------------------------------------------------------------------------------
 FROM registry.duniter.org/docker/python3/poetry/${PYTHON_VERS}:latest
-ARG PYTHON_VERS
 
 # Create silkaj group and user
 RUN groupadd -g 1111 silkaj && \
-- 
GitLab