Skip to content

Instantly share code, notes, and snippets.

@doekman
Last active December 4, 2019 16:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doekman/45acdb0ceedd9dc9dc6105d0b058b06a to your computer and use it in GitHub Desktop.
Save doekman/45acdb0ceedd9dc9dc6105d0b058b06a to your computer and use it in GitHub Desktop.
Prints the URL of the remote origin of the current git repository, optionally with a SHA1 commit
#!/usr/bin/env bash
# Unofficial Bash Strict Mode
set -euo pipefail
IFS=$'\n\t'
function git_url_to_https {
local git_url
git_url=$(cat)
if [[ $git_url =~ ^git@([^:]+):(.+)(\.git)?$ ]]; then
git_url="https://${BASH_REMATCH[1]}/${BASH_REMATCH[2]}"
fi
if [[ $git_url =~ \.git$ ]]; then
git_url=${git_url:0:${#git_url}-4}
fi
if [[ -n ${sha1:-} ]]; then
if [[ $git_url =~ ^https?://github.com/ ]]; then
git_url="$git_url/commit/$sha1"
elif [[ $git_url =~ ^https?://bitbucket.org/ ]]; then
git_url="$git_url/commits/$sha1"
elif [[ $git_url =~ ^https?://([^/]+)/ ]]; then
>&2 echo "Adding SHA1-commit to URL is not supported for '${BASH_REMATCH[1]}'."
exit 1
else
>&2 echo "Adding SHA1-commit to URL is not supported for unknown URL type '${git_url}'."
exit 1
fi
fi
if [[ -n $git_url ]]; then
echo "${git_url}"
fi
}
while [[ $# -gt 0 ]]; do
case $1 in
-* | -h | --help | -\? ) >&2 echo "Usage: $(basename $0 .sh) [sha1]"; exit 0;;
*) sha1="$1";;
esac
shift
done
if [[ -n ${sha1:-} && ${#sha1} -lt 8 ]]; then
sha1="$(git rev-parse $sha1)"
fi
git config --get remote.origin.url | git_url_to_https
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment