From b8f62075c4d38082a9913d6714cbd77dc955b4fc Mon Sep 17 00:00:00 2001
From: Mathias Chouet <mathias.chouet@irstea.fr>
Date: Fri, 27 Mar 2020 16:58:20 +0100
Subject: [PATCH] Fix #374 - add stale brancehs/tags removal

---
 .gitlab-ci.yml                   | 11 +++++++++
 scripts/release-version.sh       |  2 +-
 scripts/remove-stale-branches.sh | 38 ++++++++++++++++++++++++++++++++
 3 files changed, 50 insertions(+), 1 deletion(-)
 create mode 100755 scripts/remove-stale-branches.sh

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 2ca69ef40..dfb604e3d 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -76,6 +76,17 @@ build:
   script:
     - npm run build -- --base-href=/cassiopee/$CI_COMMIT_REF_NAME/
 
+clean-stale-branches:
+  stage:
+    - deploy
+    - deploy-stable
+  only:
+    - pushes
+    - tags
+    - web
+  script:
+    - nodejs scripts/remove-stale-branches.sh $DEPLOY_HOST_LOGIN $DEPLOY_URL
+
 deploy:
   stage: deploy
   only:
diff --git a/scripts/release-version.sh b/scripts/release-version.sh
index 128616f6f..9952d4134 100755
--- a/scripts/release-version.sh
+++ b/scripts/release-version.sh
@@ -51,7 +51,7 @@ rm "./$TMP_RELEASES_FILE"
 scp "release/Cassiopée Setup $VERSION.exe" "release/fr.irstea.cassiopee_${VERSION}_amd64.deb" "release/cassiopee-$VERSION.apk" "release/Cassiopée-${VERSION}-mac.zip" "$HOST_LOGIN:$RELEASES_DIR/"
 
 # symlink "latest" version for each platform
-ssh $HOST_LOGIN /bin/bash << "EOF"
+ssh $HOST_LOGIN /bin/bash << EOF
     cd "$RELEASES_DIR"
     ln -sf "Cassiopée Setup $VERSION.exe" "windows-latest.exe"
     ln -sf "fr.irstea.cassiopee_${VERSION}_amd64.deb" "linux-latest.deb"
diff --git a/scripts/remove-stale-branches.sh b/scripts/remove-stale-branches.sh
new file mode 100755
index 000000000..12d3562c5
--- /dev/null
+++ b/scripts/remove-stale-branches.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+# Supprime du serveur Web les "builds" de Cassiopée correspondant à des branches ou des
+# tags qui n'existent plus dans le dépôt.
+# Conçu pour être utilisé par Gitlab CI/CD
+
+if [ "$#" -lt 2 ]; then
+    echo "usage: $0 login@server /var/www/deploy_dir"
+    exit 1
+fi
+
+HOST_LOGIN="$1"
+DEPLOY_DIR="$2"
+# DEPLOY_DIR="/tmp/cassiopee" # debug
+
+echo "remove-stale-branches.sh: cleaning directory $DEPLOY_DIR on host $HOST_LOGIN"
+
+nghyd_branches=$(git ls-remote --heads origin|awk '{print $2}'|awk 'BEGIN{FS="/"} {print $3}')
+nghyd_tags=$(git tag)
+TNB="$nghyd_branches $nghyd_tags"
+
+ssh $HOST_LOGIN /bin/bash << EOF
+    cd $DEPLOY_DIR
+    LOCALTNB="$TNB"
+    for d in \$(ls -d *); do
+        found=0
+        for tag_or_branch in \$LOCALTNB; do
+            if [[ \$d == \$tag_or_branch ]]; then
+                found=1
+                break
+            fi
+        done
+        if (( \$found == 0 )); then
+            echo "suppression de branche/tag obsolète \$d"
+            rm -rf \$d
+        fi
+    done
+EOF
-- 
GitLab