Created
December 14, 2016 09:58
-
-
Save 321hendrik/69ae3a1c0fb14a25ca19281979f45de2 to your computer and use it in GitHub Desktop.
change the git host for your project (origin, submodules, package.json refs)
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 | |
# _Usage_ | |
# - modify the NEW_GIT_HOST, OLD_GIT_HOST variables below | |
# - make the script executable with `chmod u+x change_git_remote.sh` | |
# - run it from your project dir or give the path as first parameter | |
# configure host changes | |
NEW_GIT_HOST="new.git.host.com" | |
OLD_GIT_HOST="old.git.host.com" | |
# save execution directory | |
START_DIR=`pwd`; | |
# check if path to repository was given | |
if [ ! "$1" == "" ]; then | |
cd $1 | |
fi | |
# check if folder is a git repository | |
if [ ! -d ".git" ]; then | |
echo "" | |
echo "please run inside a git repository folder or supply path as first parameter" | |
echo "" | |
exit 1; | |
fi; | |
# get current git host | |
CURRENT_GIT_HOST=$(git remote -v | head -n 1 | cut -f2 -d@ | cut -f 1 -d:) | |
# check if current git host is already up to date | |
if [ "$CURRENT_GIT_HOST" == "$NEW_GIT_HOST" ]; then | |
echo "git host is already set to "$NEW_GIT_HOST | |
exit 0 | |
fi | |
# check if current git host is the one that should be replaced | |
if [ ! "$CURRENT_GIT_HOST" == "$OLD_GIT_HOST" ]; then | |
echo "old git host is not "$OLD_GIT_HOST | |
exit 1 | |
fi | |
echo "" | |
echo "changing repository url to new host: "$NEW_GIT_HOST | |
echo "" | |
# extract repo part from origin url | |
REPO_PART=$(git remote -v | head -n 1 | cut -f2 -d: | cut -f1 -d' ') | |
echo $REPO_PART | |
# set new remote url | |
NEW_REMOTE_URL="git@"$NEW_GIT_HOST":"$REPO_PART | |
echo "- set remote url to "$NEW_REMOTE_URL | |
git remote set-url origin $NEW_REMOTE_URL | |
# change submodule paths | |
if [ -f ".gitmodules" ]; then | |
echo "- changing submodule urls..." | |
NEW_HOST_REGEX_URL=$(echo $NEW_GIT_HOST | sed 's/\./\\./g') | |
OLD_HOST_REGEX_URL=$(echo $OLD_GIT_HOST | sed 's/\./\\./g') | |
sed -i.bak 's/'$OLD_HOST_REGEX_URL'/'$NEW_HOST_REGEX_URL'/g' .gitmodules | |
rm -f .gitmodules.bak | |
git submodule sync | |
fi | |
# change package.json refs | |
if [ -f "package.json" ]; then | |
echo "- changing package refs..." | |
NEW_HOST_REGEX_URL=$(echo $NEW_GIT_HOST | sed 's/\./\\./g') | |
OLD_HOST_REGEX_URL=$(echo $OLD_GIT_HOST | sed 's/\./\\./g') | |
sed -i.bak 's/'$OLD_HOST_REGEX_URL'/'$NEW_HOST_REGEX_URL'/g' package.json | |
rm -f package.json.bak | |
fi | |
echo "" | |
echo "repository remote changed" | |
echo "" | |
# go back to execution directory | |
cd $START_DIR |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment