|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# Cleanup script that preserves specified artifacts |
| 4 | +# Usage: ./cleanup.sh "artifact1,artifact2,artifact3" |
| 5 | + |
| 6 | +# 'set' should be added to the beginning of each script to ensure that it runs with the correct options. |
| 7 | +# Please do not move it to some common file, like `setup-tests.sh`, because sourcing A script from B script |
| 8 | +# cannot change the options of B script. |
| 9 | +# -e: Exit immediately if any command exits with a non-zero status (i.e., if a command fails). |
| 10 | +# -x: Print each command to the terminal as it is executed, which is useful for debugging. |
| 11 | +set -ex |
| 12 | + |
| 13 | +# Fix mixed logs |
| 14 | +exec 2>&1 |
| 15 | + |
| 16 | +echo "Size before cleanup:" && du -h | tail -n 1 |
| 17 | +echo "Top 5 files:" && du -h | sort -hr | head -n 5 |
| 18 | + |
| 19 | +# Parse artifacts from command line argument |
| 20 | +ARTIFACTS_ARG="${1:-}" |
| 21 | +if [ -z "$ARTIFACTS_ARG" ]; then |
| 22 | + echo "No artifacts specified, cleaning entire workspace" |
| 23 | + ARTIFACTS="" |
| 24 | +else |
| 25 | + # Convert comma-separated string to space-separated |
| 26 | + ARTIFACTS=$(echo "$ARTIFACTS_ARG" | tr ',' ' ') |
| 27 | + echo "Preserving artifacts: $ARTIFACTS" |
| 28 | +fi |
| 29 | + |
| 30 | +TMP="$(mktemp -d)" |
| 31 | +trap 'rm -rf "$TMP"' EXIT |
| 32 | + |
| 33 | +# Stash artifacts to /tmp |
| 34 | +for f in $ARTIFACTS; do |
| 35 | + [ -e "$f" ] || continue |
| 36 | + echo "Stashing artifact: $f" |
| 37 | + mkdir -p "$TMP/$(dirname "$f")" |
| 38 | + mv "$f" "$TMP/$f" |
| 39 | +done |
| 40 | + |
| 41 | +# Clean entire workspace (including dotfiles and .git) |
| 42 | +find . -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + |
| 43 | + |
| 44 | +# Restore artifacts |
| 45 | +for f in $ARTIFACTS; do |
| 46 | + [ -e "$TMP/$f" ] || continue |
| 47 | + echo "Restoring artifact: $f" |
| 48 | + mkdir -p "$(dirname "$f")" |
| 49 | + mv "$TMP/$f" "$f" |
| 50 | +done |
| 51 | + |
| 52 | +echo "Size after cleanup:" && du -h | tail -n 1 |
| 53 | +echo "Top 5 files:" && du -h | sort -hr | head -n 5 |
| 54 | + |
| 55 | +echo "Cleanup completed successfully" |
0 commit comments