After using hub browse for a while, which does a similar job, I wrote this:
#!/bin/bash
branch=$(git name-rev --name-only HEAD)
if [ -z "$branch" ]; then
echo >&2 "Cannot determine branch. Detached head? Using 'master'"
branch="master"
fi
tracking_remote=$(git config branch.$branch.remote)
if [ -z "$tracking_remote" ]; then
echo >&2 "No remote branch found for branch $branch. Using 'origin'"
tracking_remote="origin"
fi
remote_url=$(git config remote.$tracking_remote.url)
if [ -z "$remote_url" ]; then
echo >&2 "No remote url found for remote $tracking_remote."
exit 1
fi
remote=$(echo "$remote_url"|sed -e 's/git@/http:\/\//;s/net:/net\//;s/.git$//')
commit=$(git --no-pager log -n1 --pretty=format:%H)
if [ -n "$1" ] ; then
path="blob/$commit/$1"
else
path="tree/$commit"
fi
if [ -n "$2" ] ; then
start="#L$2"
fi
if [ -n "$3" ] ; then
end="-L$3"
fi
open "$remote/$path$start$end"
... my use case was usually to share a link to a specific file or lines from a file to a slack room, so my script ('gitlink') took a file and optionally line numbers as args. I pick up the current branch instead of taking a branch as an arg. I also link to a specific commit instead of the branch, to prevent historical links bitrotting. Anyway, feel free to use/ignore any of this.
After using
hub browse
for a while, which does a similar job, I wrote this:... my use case was usually to share a link to a specific file or lines from a file to a slack room, so my script ('gitlink') took a file and optionally line numbers as args. I pick up the current branch instead of taking a branch as an arg. I also link to a specific commit instead of the branch, to prevent historical links bitrotting. Anyway, feel free to use/ignore any of this.