From 8b778f4477aa09a8c45b42974f4146064ded0d9b Mon Sep 17 00:00:00 2001
From: Pierre Smeyers <pierre.smeyers@gmail.com>
Date: Sun, 5 May 2024 17:29:00 +0200
Subject: [PATCH] refactor: add smart OS-agnostic package installation function

The template now supports installing packages on Alpine and Debian-based images.
The function also skips install if packages are already installed.
---
 templates/gitlab-ci-python.yml | 25 +++++++++++++++++++++++--
 1 file changed, 23 insertions(+), 2 deletions(-)

diff --git a/templates/gitlab-ci-python.yml b/templates/gitlab-ci-python.yml
index 0491472..87c9d88 100644
--- a/templates/gitlab-ci-python.yml
+++ b/templates/gitlab-ci-python.yml
@@ -523,6 +523,28 @@ variables:
     done
   }
 
+  function maybe_install_packages() {
+    if command -v apt-get > /dev/null
+    then
+      # Debian
+      if ! dpkg --status "$@" > /dev/null
+      then
+        apt-get update
+        apt-get install --yes --quiet "$@"
+      fi
+    elif command -v apk > /dev/null
+    then
+      # Alpine
+      if ! apk info --installed "$@" > /dev/null
+      then
+        apk add --no-cache "$@"
+      fi
+    else
+      log_error "... didn't find any supported package manager to install $*"
+      exit 1
+    fi
+  }
+
   function guess_build_system() {
     case "${PYTHON_BUILD_SYSTEM:-auto}" in
     auto)
@@ -1114,10 +1136,9 @@ py-trivy:
   # force no dependencies
   dependencies: []
   script:
+    - maybe_install_packages wget apt-transport-https gnupg lsb-release
     - mkdir -p -m 777 reports
     - install_requirements
-    - apt-get update
-    - apt-get install -y wget apt-transport-https gnupg lsb-release
     - wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | apt-key add -
     - echo "deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | tee -a /etc/apt/sources.list.d/trivy.list
     - apt-get update
-- 
GitLab