Deletes all merged git branches older than the provided date.
| #!/bin/sh | |
| cd ../.. | |
| date=$1 #Format: 2015-01-15 | |
| root_branch=$2 #Format: origin/branchName e.g. origin/release/1_6 | |
| DRY_RUN=$3 | |
| numberDeleted=0 | |
| FilterOut() { | |
| for branchToKeep in "HEAD" "develop" "master"; do | |
| if [ "$1" == "$branchToKeep" ]; then | |
| return 1 | |
| fi | |
| done | |
| return 0 | |
| } | |
| DeleteBranch() { | |
| echo "Deleting branch $1" | |
| if [ "$DRY_RUN" -eq 0 ]; then | |
| git push origin ":$1" | |
| fi | |
| } | |
| DeleteBranchIfMatchingCriteria() { | |
| branch=$1 | |
| # has there been any action on this branch since this date | |
| if [ "$(git log $branch --since $date | wc -l)" -eq 0 ]; then | |
| local_branch_name=$(echo "$branch" | sed 's/^origin\///') | |
| if FilterOut "$local_branch_name" -eq 0; then | |
| DeleteBranch $local_branch_name | |
| numberDeleted=$((numberDeleted + 1)) | |
| fi | |
| fi | |
| } | |
| echo "Deleting git branches older than $date and not merged into $root_branch" | |
| for branch in $(git branch --remote --no-merged $root_branch); do | |
| DeleteBranchIfMatchingCriteria $branch | |
| done | |
| echo "Deleting git branches older than $date and merged into $root_branch" | |
| for branch in $(git branch --remote --merged $root_branch); do | |
| DeleteBranchIfMatchingCriteria $branch | |
| done | |
| echo "Branch deletion complete. Deleted a total of $numberDeleted branches" | |
| cd $OLDPWD |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment