Skip to content

Instantly share code, notes, and snippets.

@karlvr
Last active October 29, 2021 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlvr/224d3198fc1ee3abc6fb202b201e2bcc to your computer and use it in GitHub Desktop.
Save karlvr/224d3198fc1ee3abc6fb202b201e2bcc to your computer and use it in GitHub Desktop.
Delete tags from a git repository that reference commits that aren't part of the named branch.
#!/bin/bash -eu
#
# Delete tags from a git repository that reference commits that aren't part of the named branch
#
# This is useful if you've split a branch out of a repository and want to remove all of the commits
# that referenced activity in other branches.
usage() {
echo "usage: $0 [-d] [-p <remote>] <branch>" >&1
echo " -d dry run" >&1
echo " -p push tag deletes to the remote" >&1
}
dryrun=0
push=
while getopts ":dp:" opt; do
case $opt in
d)
dryrun=1
;;
p)
push="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
shift $((OPTIND-1))
branch="${1:-}"
if [ -z "$branch" ]; then
usage
exit 1
fi
tags=$(git tag --list)
for tag in $tags ; do
tagref=$(git rev-list -n 1 "$tag")
if [ -z "$tagref" ]; then
echo "Failed to find ref for tag: $tag" >&1
exit 1
fi
set +e
git rev-list "$branch" | grep -q "$tagref"
if [ $? == 1 ]; then
if [ $dryrun == 1 ]; then
echo "Would delete $tag"
else
git tag --delete "$tag"
if [ -n $push ]; then
git push $push :refs/tags/"$tag"
fi
fi
fi
set -e
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment