Last active
April 2, 2019 22:11
-
-
Save jmcker/5ec960e5526115c12e31d7618a9fc237 to your computer and use it in GitHub Desktop.
Switch all remotes in a git repo from HTTP to SSH (and vice-versa) with a single command. (Doesn't work perfectly right now. Be careful)
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 | |
TO_HTTP="false" | |
BASE_HOST="github.com" | |
function help-text() { | |
echo "git-protocol-switcher (git-prot)" | |
echo " Switch all remotes in a git repo from HTTP to SSH (and vice-versa) with a single command." | |
echo " This assumes a host of https://github.com" | |
echo | |
echo "Usage:" | |
echo " git-prot -h Display this message" | |
echo " git-prot Switch the current repo from HTTP to SSH" | |
echo " git-prot -p http Switch the current repo from SSH to HTTP" | |
echo | |
} | |
while getopts ":hp:" opt; do | |
case ${opt} in | |
h ) | |
help-text | |
exit 0 | |
;; | |
p ) | |
TO_HTTP="true" | |
;; | |
\? ) | |
echo "Unknown option: -$OPTARG" 1>&2 | |
help-text | |
exit 1 | |
esac | |
done | |
# Make sure we're in a valid repo | |
git rev-parse --git-dir >/dev/null 2>&1 | |
if [ $? -ne 0 ]; then | |
echo "This script can only be used inside a git repository." | |
help-text | |
exit 1 | |
fi | |
echo | |
for remote in $(git remote); do | |
old_url=$(git remote get-url ${remote}) | |
if [ "${TO_HTTP}" == "false" ]; then | |
# Reject URLs already in SSH | |
echo "${old_url}" | grep -iE ".*@${BASE_HOST}" >/dev/null 2>&1 | |
if [ $? -eq 0 ]; then | |
continue | |
fi | |
tail=${old_url#*.com/} | |
new_url="git@${BASE_HOST}:/${tail}" | |
else | |
# Reject URLs already in HTTP (case-insensitive) | |
echo "${old_url}" | grep -iE "http.?://" >/dev/null 2>&1 | |
if [ $? -eq 0 ]; then | |
continue | |
fi | |
tail=${old_url#*:/} | |
new_url="https://${BASE_HOST}/${tail}" | |
fi | |
echo "Switching ${remote} from:" | |
echo " ${old_url}" | |
echo " to" | |
echo " ${new_url}" | |
git remote set-url ${remote} ${new_url} | |
if [ $? -eq 0 ]; then | |
echo "Success" | |
else | |
echo "Failed. Error code: $?" | |
fi | |
echo | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment