Skip to content

Instantly share code, notes, and snippets.

@pascalpp
Created April 5, 2024 19:23
Show Gist options
  • Save pascalpp/010c6d4d3864f2ee669a1bafbf2f0313 to your computer and use it in GitHub Desktop.
Save pascalpp/010c6d4d3864f2ee669a1bafbf2f0313 to your computer and use it in GitHub Desktop.
delete-squashed-branches
#!/bin/sh
# Cribbed most of this from
# https://stackoverflow.com/questions/43489303/how-can-i-delete-all-git-branches-which-have-been-squash-and-merge-via-github
# Requirements:
# gh (https://cli.github.com/)
# Installation:
# touch ~/bin/delete-squashed-branches (or somewhere in your path)
# edit that file and paste this script into it
# chmod +x ~/bin/delete-squashed-branches
# Usage:
# delete-squashed-branches (will list any local branches that have been merged and can be deleted)
# delete-squashed-branches -D (to actually delete the branches)
# Determine which branch this repo considers the main branch
main=$(gh repo view --json defaultBranchRef --jq .defaultBranchRef.name)
# Switch to that main branch
git checkout -q $main;
# Loop through all branches and list any that have been squashed and merged
# Delete them if the -D flag is passed
git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do
mergeBase=$(git merge-base $main $branch);
revParse=$(git rev-parse "$branch^{tree}");
commitTree=$(git commit-tree $revParse -p $mergeBase -m _);
if [[ $(git cherry $main $commitTree) == "-"* ]]; then
if [[ $1 == '-D' ]]; then
git branch -D $branch;
else
echo "$branch is merged into $main and can be deleted";
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment