|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +# |
| 4 | +# {{ ansible_managed }} |
| 5 | +# |
| 6 | + |
| 7 | +# Clean up unused checkouts |
| 8 | +# |
| 9 | +# This script is used to find old checkouts that are no longer in use. Given the |
| 10 | +# size of the build directory, regularly cleaning them up can save significant |
| 11 | +# amounts of disk space. |
| 12 | + |
| 13 | +# Enable strict mode for Bash |
| 14 | +# http://redsymbol.net/articles/unofficial-bash-strict-mode/ |
| 15 | +set -euo pipefail |
| 16 | +IFS=$'\n\t' |
| 17 | + |
| 18 | +# Print directories and their size instead of deleting them |
| 19 | +dry_run=false |
| 20 | + |
| 21 | +# Default to search for checkouts older than 60 days |
| 22 | +time="60" |
| 23 | + |
| 24 | +while [[ $# -gt 0 ]]; do |
| 25 | + case $1 in |
| 26 | + --dry-run) |
| 27 | + dry_run=true |
| 28 | + shift # past argument |
| 29 | + ;; |
| 30 | + -t|--time) |
| 31 | + time="${2}" |
| 32 | + shift # past argument |
| 33 | + shift # past value |
| 34 | + ;; |
| 35 | + -*) |
| 36 | + echo "Unknown option $1" |
| 37 | + exit 1 |
| 38 | + ;; |
| 39 | + esac |
| 40 | +done |
| 41 | + |
| 42 | +# Find all build or target directories created by users |
| 43 | +# |
| 44 | +# This command combines (`-o`) two different conditions to find all build and |
| 45 | +# target directories that users have created. Within each home directory, we |
| 46 | +# recursively look for directories that either have a file named `x.py` and a |
| 47 | +# directory named `build`, or a file named `Cargo.toml` and a directory named |
| 48 | +# `target`. |
| 49 | +all_cache_directories=$(find /home -type d \( -name build -execdir test -f "x.py" \; -o -name target -execdir test -f "Cargo.toml" \; \) -print | sort | uniq) |
| 50 | + |
| 51 | +# For each checkout, we want to determine if the user has been working on it |
| 52 | +# within the `$time` number of days. |
| 53 | +unused_cache_directories=$(for directory in $all_cache_directories; do |
| 54 | + project=$(dirname "${directory}") |
| 55 | +
|
| 56 | + # Find all directories with files that have been modified less than $time days ago |
| 57 | + modified=$(find "${project}" -type f -mtime -"${time}" -printf '%h\n' | xargs -r dirname | sort | uniq) |
| 58 | +
|
| 59 | + # If no files have been modified in the last 90 days, then the project is |
| 60 | + # considered old. |
| 61 | + if [[ -z "${modified}" ]]; then |
| 62 | + echo "${directory}" |
| 63 | + fi |
| 64 | +done) |
| 65 | + |
| 66 | +# Delete the build directories in the unused checkouts |
| 67 | +for directory in $unused_cache_directories; do |
| 68 | + if [[ "${dry_run}" == true ]]; then |
| 69 | + du -sh "${directory}" |
| 70 | + else |
| 71 | + echo "Deleting ${directory}" |
| 72 | + rm -rf "${directory}" |
| 73 | + fi |
| 74 | +done |
0 commit comments