Skip to content

Instantly share code, notes, and snippets.

@idris

idris/github.sh

Created Jan 20, 2011
Embed
What would you like to do?
command-line utility that opens a browser to the given file/directory in GitHub.
#!/bin/bash
FILE=$1
if [ -d $FILE ]; then
DIR=$FILE
else
DIR=`dirname $FILE`
fi
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(@|:\/\/)github.com(:|\/)(.+)\/(.+).git/\3\/\4/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
}
URL="https://github.com/$(parse_github_repo)/$(tree_or_blob)/$(parse_git_branch)/$(get_path)"
if [ "`which gnome-www-browser`" != "" ]; then
gnome-www-browser $URL
else
open $URL
fi
@idris

This comment has been minimized.

Copy link
Owner Author

@idris idris commented Jan 20, 2011

The parse_github_repo function came from: http://willwont.blogspot.com/2009/10/github-from-command-line.html

@idris

This comment has been minimized.

Copy link
Owner Author

@idris idris commented Jan 20, 2011

This second revision makes it so that you don't have to be in the git repo to run the command.

Also, thanks to marc.guenther for the --show-toplevel tip

@patrickwebs

This comment has been minimized.

Copy link

@patrickwebs patrickwebs commented Jan 21, 2011

If you want it to work on linux (Gnome), I'd replace the bottom line with:

 if [ "`which gnome-www-browser`" != "" ]; then
     gnome-www-browser $URL
 else
     open $URL
 fi

@idris

This comment has been minimized.

Copy link
Owner Author

@idris idris commented Jan 21, 2011

Done! Thanks

@ryanmcgrath

This comment has been minimized.

Copy link

@ryanmcgrath ryanmcgrath commented May 6, 2011

You might be happier with life if you didn't write things in Bash.

Just sayin'. >_>

@EnotionZ

This comment has been minimized.

Copy link

@EnotionZ EnotionZ commented May 6, 2011

Ryan, haven't you been writing PHP the past 2 weeks? Just sayin'

@ryanmcgrath

This comment has been minimized.

Copy link

@ryanmcgrath ryanmcgrath commented May 7, 2011

Exactly, I know pain when it's staring me in the face, so my word is legit. ;0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment