Skip to content

Instantly share code, notes, and snippets.

@tolu
Created October 17, 2024 19:12
Show Gist options
  • Save tolu/964abb61f16b4773df698f20b9f0345e to your computer and use it in GitHub Desktop.
Save tolu/964abb61f16b4773df698f20b9f0345e to your computer and use it in GitHub Desktop.
Remove git branches older than x
#!/bin/bash
# Function to get the cutoff date
get_cutoff_date() {
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS
date -v-12m +%s
else
# Linux and others
date -d "12 months ago" +%s
fi
}
# Function to convert epoch to relative time
epoch_to_relative() {
local epoch=$1
local now=$(date +%s)
local diff=$((now - epoch))
local days=$((diff / 86400))
local hours=$(( (diff % 86400) / 3600 ))
local minutes=$(( (diff % 3600) / 60 ))
local seconds=$((diff % 60))
if [[ $days -gt 0 ]]; then
echo "$days days ago"
elif [[ $hours -gt 0 ]]; then
echo "$hours hours ago"
elif [[ $minutes -gt 0 ]]; then
echo "$minutes minutes ago"
else
echo "$seconds seconds ago"
fi
}
# Set the cutoff date to 6 months ago
cutoff=$(get_cutoff_date)
# Function to delete branches
delete_branches() {
local branch_type=$1
local branches=$2
for branch in $branches; do
# Skip the current branch and main/master branches
if [[ "$branch" == "$(git rev-parse --abbrev-ref HEAD)" ]] || [[ "$branch" == "main" ]] || [[ "$branch" == "master" ]]; then
continue
fi
# Get the timestamp of the latest commit
if [[ $branch_type == "local" ]]; then
timestamp=$(git log -1 --format=%at "$branch")
else
timestamp=$(git log -1 --format=%at "origin/$branch")
fi
if [[ $timestamp -lt $cutoff ]]; then
relative_time=$(epoch_to_relative $timestamp)
echo "Branch ($branch_type) $branch - last updated $relative_time"
if [[ $branch_type == "local" ]]; then
git branch -d "$branch"
echo "Deleted local branch: $branch"
else
git push origin --delete "$branch"
echo "Deleted remote branch: $branch"
fi
fi
done
}
# Update the local list of remote branches
git fetch --all --prune
# Get all local branches
local_branches=$(git branch --sort=-committerdate --format="%(refname:short)")
# Get all remote branches
remote_branches=$(git branch -r --sort=-committerdate | grep -v '\->' | sed 's/origin\///')
# Delete old local branches
delete_branches "local" "$local_branches"
# Delete old remote branches
delete_branches "remote" "$remote_branches"
echo "Branch cleanup completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment