Created
September 4, 2014 16:34
-
-
Save wesleybliss/e42d47d166f37f4a468c to your computer and use it in GitHub Desktop.
Rename GIT branches based on a pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
echo | |
show_usage() { | |
cat << EOF | |
Rename a set of branches, effectively DELETING old | |
branches and creating new ones based on the old ones. | |
USAGE | |
$(basename "$0") <remote> <query> | |
remote A GIT remote (usually origin) | |
find A search query to grep for a set of branches | |
replace Text to replace the find query with | |
EXAMPLE | |
$(basename "$0") origin "1.2.2" "1.2.4" | |
EOF | |
} | |
if [[ -z "$1" ]] || [[ -z "$2" ]] || [[ -z "$3" ]]; then | |
show_usage | |
exit 1 | |
fi | |
# Get a list of branches - local only, for now | |
oldbranches=$(git branch -l | grep "$2") | |
newbranches=() | |
echo "Here are the branches and what they will be renamed to." | |
echo | |
for branch in $oldbranches; do | |
echo "$branch" | |
newbranches+=(${branch/"$2"/"$3"}) | |
echo ${newbranches[${#newbranches[@]} - 1]} | |
echo | |
done | |
# Confirm rename | |
read -r -p "Are you sure you want to rename these local branches? [y/N] " response | |
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then | |
echo "OK" | |
echo "" | |
else | |
echo "Cancelled" | |
exit 2 | |
fi | |
# Move (rename) branches | |
i=0 | |
for oldbranch in $oldbranches; do | |
git branch -m $oldbranch ${newbranches[$i]} | |
i=$[i + 1] | |
done | |
# Confirm remote delete | |
read -r -p "Would you like to delete old branches from all remotes? [y/N] " response | |
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then | |
echo "OK" | |
echo "" | |
else | |
echo "Cancelled" | |
exit 2 | |
fi | |
remotes=$(git remote | cut -f1) | |
for branch in $oldbranches; do | |
for remote in $remotes; do | |
git push $remote :$branch | |
done | |
done | |
echo | |
# Confirm new push | |
read -r -p "Would you like to push renamed branches to all remotes? [y/N] " response | |
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then | |
echo "OK" | |
echo "" | |
else | |
echo "Cancelled" | |
exit 2 | |
fi | |
# Push all new branches | |
newbranches_len=${#newbranches[@]} | |
for (( i=0; i < ${newbranches_len}; i++ )); do | |
for remote in $remotes; do | |
git push $remote ${newbranches[$i]} | |
done | |
done | |
echo | |
echo | |
echo "Finished renaming $newbranches_len branches." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment