Skip to content

Instantly share code, notes, and snippets.

@wilensky
Last active November 9, 2023 15:04
Show Gist options
  • Save wilensky/98475be39f3a6a3c54e2611931746283 to your computer and use it in GitHub Desktop.
Save wilensky/98475be39f3a6a3c54e2611931746283 to your computer and use it in GitHub Desktop.
Script recreates an existing Git tag by removing it and creating on the same commit. Useful for checking idempotent triggers or dropping large amount of tags.
#!/usr/bin/env bash
# tag.sh -t my-awesome-tag@1.2.3 -dcyv
#
# -d Deletes tags
# -c Creates tag on the same commit
# -y Non-interactive mode (always YES)
# -v Slightly increased verbosity
TAG=''
OPT_DEL=0
OPT_CREATE=0
YES_MAN=0
VERBOSE=0
while getopts ":dcyvt:" OPTION; do
case "$OPTION" in
t) # tag name
TAG=$OPTARG
;;
d) # drop tag
OPT_DEL=1
;;
c) # create same tag
OPT_CREATE=1
;;
y) # all yes
YES_MAN=1
;;
v) # verbose
VERBOSE=1
;;
\?) # Invalid option
echo "Error: Invalid option -$OPTARG"
exit;;
:)
echo "Missing option argument for -$OPTARG" >&2
exit 1;;
*)
echo "Unimplemented option: -$option" >&2
exit 1;;
esac
done
if [ -z "${TAG}" ]; then
echo "Empty tag! Aborting ...";
exit 1
fi
COMMIT=$(git rev-list -n 1 "${TAG}")
if [ $? != 0 ] || [ -z "$COMMIT" ]; then
echo ' Tag not found!'
exit 2;
fi
echo "Tag: ${TAG} (${COMMIT})"
function confirm {
while true; do
read -p "$* [y/n]: " yn
case $yn in
[Yy]*) return 0 ;;
[Nn]*) return 1 ;;
esac
done
}
if [[ $YES_MAN == 0 ]]; then
confirm "Continue?"
if [[ $? == 1 ]]; then
echo "Aborted ..."
fi
fi
if [[ $OPT_DEL == 1 ]]; then
[[ $VERBOSE == 1 ]] && echo "- Removing remote tag"
git push origin :$TAG
if [[ $? != 0 ]]; then
echo " ! Failed to remove remote tag ..."
exit 120
fi
[[ $VERBOSE == 1 ]] && echo "- Removing local tag"
git tag -d $TAG
if [[ $? != 0 ]]; then
echo " ! Failed to remove local tag ..."
exit 121
fi
fi
if [[ $OPT_CREATE == 1 ]]; then
[[ $VERBOSE == 1 ]] && echo "+ Re-creating tag"
git tag ${TAG} ${COMMIT}
if [[ $? != 0 ]]; then
echo " ! Failed to re-create tag ..."
exit 122
fi
[[ $VERBOSE == 1 ]] && echo "+ Pushing tag"
git push origin $TAG
if [[ $? != 0 ]]; then
echo " ! Failed to push tag ..."
exit 123
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment