Skip to content

Instantly share code, notes, and snippets.

@idris
Created November 13, 2012 04:03
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 idris/4063859 to your computer and use it in GitHub Desktop.
Save idris/4063859 to your computer and use it in GitHub Desktop.
command-line utility that opens a browser to the given file/directory/commit in GitHub. Now has blame command which opens github blame page.
#!/bin/bash
function parse_git_branch {
local branch=`cd $DIR;git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`
if [ "$branch" == "" ]; then
exit 1
else
echo $branch
fi
}
function parse_github_repo {
echo `cd $DIR;git config -l | grep 'remote.origin.url' | sed -En 's/remote.origin.url=(git|https?)(@|:\/\/)github.com(:|\/)(.+)\/(.+).git/\4\/\5/p'`
}
function get_path {
if [ -d $FILE ]; then
FOO=`(cd $FILE; pwd)`
else
FOO=`(cd $DIR; pwd)`/`basename $FILE`
fi
PWD=`cd $DIR;cd $(git rev-parse --show-toplevel);pwd`
LEN=${#PWD}
LEN=$((LEN+1))
echo ${FOO:LEN}
}
function tree_or_blob {
if [ -d $FILE ]; then
echo 'tree'
else
echo 'blob'
fi
}
DIR='.'
if [ "blame" = "$1" ]; then
DIR=`dirname $2`
FILE=$(basename $2)
URL="https://github.com/$(parse_github_repo)/blame/$(parse_git_branch)/$(get_path)"
elif [ "pr" = "$1" ]; then
URL="https://github.com/$(parse_github_repo)/pull/new/$(parse_git_branch)"
else
# this old way will not validate partial sha but should be much faster
# if [ "$(git merge-base $1 $(parse_git_branch) )" = "$1" ]; then
# if no argument is passed in, assuming we want the latest commit
if [ "" = "$1" ]; then
sha=`git rev-parse --verify HEAD`
else
sha=`git rev-list $1 2>/dev/null | grep $1`
fi
if [ $sha ]; then
URL="https://github.com/`parse_github_repo`/commit/$sha"
else
FILE=$1
if [ -d $FILE ]; then
DIR=$FILE
else
DIR=`dirname $FILE`
fi
URL="https://github.com/$(parse_github_repo)/$(tree_or_blob)/$(parse_git_branch)/$(get_path)"
fi
fi
echo $URL | pbcopy
if [ "`which gnome-www-browser`" != "" ]; then
gnome-www-browser $URL
else
open $URL
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment