Created
November 7, 2023 03:13
-
-
Save redconfetti/1f61c4a2bb1f0b187a4eeb8be0c08a90 to your computer and use it in GitHub Desktop.
Cleanup Builds Directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Cleanup Builds | |
# | |
# Obtains latest Git commit SHAs from branches in remote origin | |
# and assembles an array of build filenames to retain in a build directory (e.g. app-build-$commit_sha.war) | |
# Runs command to remove all found files except those identified in array | |
readonly BUILD_DIR=./builds | |
git fetch origin | |
read -r -d '\n' -a remote_branches < <( git branch -r --format="%(refname:lstrip=3)" ) | |
retain_build_commits=() | |
for branch_name in "${remote_branches[@]}" | |
do | |
# exclude HEAD from branch references | |
if [ $branch_name != 'HEAD' ]; then | |
if [ $branch_name == 'main' ]; then | |
read -r -d '\n' -a branch_commits < <( git log origin/$branch_name -n 5 --format="%h" ) | |
else | |
read -r -d '\n' -a branch_commits < <( git log origin/$branch_name -n 3 --format="%h" ) | |
fi | |
retain_build_commits+=( ${branch_commits[@]} ) | |
fi | |
done | |
keep_files=() | |
for commit_sha in "${retain_build_commits[@]}" | |
do | |
keep_files+=("app-build-$commit_sha.war") | |
done | |
# delete all files in builds directory except those specified to keep | |
find $BUILD_DIR -type f -maxdepth 1 $(printf "! -name %s " ${keep_files[*]}) -exec rm {} \; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment