Skip to content

Instantly share code, notes, and snippets.

@redconfetti
Created November 7, 2023 03:13
Show Gist options
  • Select an option

  • Save redconfetti/1f61c4a2bb1f0b187a4eeb8be0c08a90 to your computer and use it in GitHub Desktop.

Select an option

Save redconfetti/1f61c4a2bb1f0b187a4eeb8be0c08a90 to your computer and use it in GitHub Desktop.

Revisions

  1. redconfetti created this gist Nov 7, 2023.
    36 changes: 36 additions & 0 deletions cleanup.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    #!/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 {} \;