Skip to content

Instantly share code, notes, and snippets.

@staticfloat
Last active April 13, 2019 00:23
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 staticfloat/a19b5a4382a09a030b7eebee8f468983 to your computer and use it in GitHub Desktop.
Save staticfloat/a19b5a4382a09a030b7eebee8f468983 to your computer and use it in GitHub Desktop.
github_remote
#!/usr/bin/env bash
## Helper script to turn an `https://` clone of a github repository into something that you
## can push from. Supports both invocation as `github_remote`, as well as with an optional
## username, to add a particular user's fork as a remote, e.g. `github_remote avik-pal`.
ORIGIN_URL=$(git remote get-url origin 2>/dev/null)
if [[ -z "${ORIGIN_URL}" ]]; then
echo "ERROR: No origin remote?!"
exit 1
fi
# Match ORIGIN_URL to http(s) github url stem:
ORIGIN_PATH=$(echo ${ORIGIN_URL} | sed -ne 's&https*://github.com/\(.*\)&\1&p')
if [[ -z "${ORIGIN_PATH}" ]]; then
# Try git@ github url stem:
ORIGIN_PATH=$(echo ${ORIGIN_URL} | sed -ne 's&git\@github.com\:\(.*\)&\1&p')
if [[ -z "${ORIGIN_PATH}" ]]; then
echo "ERROR: Unable to strip github stem from ${ORIGIN_URL}"
exit 1
fi
fi
# First, ensure the push url for origin is using SSH:
if [[ $(git remote get-url --push origin 2>/dev/null) != git* ]]; then
ORIGIN_PUSH_URL="git@github.com:${ORIGIN_PATH}"
git remote set-url --push origin "${ORIGIN_PUSH_URL}"
echo "Successfully set 'origin' to push -> ${ORIGIN_PUSH_URL}"
fi
# Change this to your github username
if [[ -z "$1" ]]; then
GITHUB_USER="staticfloat"
else
GITHUB_USER="$1"
fi
GITHUB_URL=$(git remote get-url "${GITHUB_USER}" 2>/dev/null)
if [[ -z "${GITHUB_URL}" ]]; then
# Add the `${GITHUB_USER}/<repo name>` fork as a target.
GITHUB_URL="git@github.com:${GITHUB_USER}/$(basename ${ORIGIN_PATH})"
git remote add "${GITHUB_USER}" "${GITHUB_URL}"
echo "Successfully added remote '${GITHUB_USER}' -> ${GITHUB_URL}; fetching..."
git fetch -a "${GITHUB_USER}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment