Skip to content

Instantly share code, notes, and snippets.

@doekman

doekman/git-url.sh

Last active Dec 4, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.