Skip to content

Instantly share code, notes, and snippets.

@ianmiell
Created April 1, 2021 08:05
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 ianmiell/cafb0093017d0e1e3af02c5dde2a1bbc to your computer and use it in GitHub Desktop.
Save ianmiell/cafb0093017d0e1e3af02c5dde2a1bbc to your computer and use it in GitHub Desktop.
Script to get git repo link
#!/bin/bash
# based on: https://stackoverflow.com/questions/47524709/how-to-get-the-full-path-of-a-file-in-a-git-remote-repo
#set -o xtrace
set -o errexit
set -o nounset
set -o pipefail
function usage {
echo "$0 [ -h/--help ] [ FILENAME ]"
exit 0
}
if [[ $1 == '--help' ]] || [[ $1 == '-h' ]]
then
usage
fi
if ! git rev-parse --show-toplevel >/dev/null 2>&1
then
echo "Not in git repo"
exit 1
fi
git_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)"
relative_path="$(git rev-parse --show-prefix | sed 's/\/$//')"
GIT_REMOTE_URL_UNFINISHED="http://$(git config --get remote.origin.url | sed 's/^ssh/http/; s/git@//; s/.git$//; s/:/\//')"
GIT_REMOTE_URL="$(dirname "${GIT_REMOTE_URL_UNFINISHED}")/$(basename "${GIT_REMOTE_URL_UNFINISHED}")"
#if the feature branch name contains "/", transform it as per URL Encoding
git_branch_in_url="$(echo "${git_branch}" | sed 's/\//%2F/g')"
GIT_REMOTE_URL="${GIT_REMOTE_URL}/tree/${git_branch_in_url}/${relative_path}/${1}"
if [[ $(uname) == 'Darwin' ]]
then
open "${GIT_REMOTE_URL}"
else
echo "${GIT_REMOTE_URL}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment