Skip to content

Instantly share code, notes, and snippets.

@haxorjim
Forked from anderskig/Repo
Last active June 12, 2020 14:37
Show Gist options
  • Save haxorjim/100cd237f4338c7bcbfcaf104d1281a2 to your computer and use it in GitHub Desktop.
Save haxorjim/100cd237f4338c7bcbfcaf104d1281a2 to your computer and use it in GitHub Desktop.
Open a project file on GitHub.
#!/bin/bash
#
# Open the specified file on GitHub. It will use the master branch by default:
#
# gh app/controllers/application_controller.rb
#
# Specify the current branch:
#
# gh -c app/controllers/application_controller.rb
#
# Specify a specific branch:
#
# gh -b another-branch app/controllers/application_controller.rb
#
if [ -d .git ]; then
echo "Opening on Github..."
BRANCH="master"
while getopts "b:c:" option
do
case "$option" in
b) BRANCH=$OPTARG;;
c) BRANCH=$(git rev-parse --abbrev-ref HEAD);;
esac
done
shift $(($OPTIND-1))
FILE=$1
BASE=$(git config --get remote.origin.url | sed s/\\.git// | sed 's/:/\//' | sed 's/.*github.com/https:\/\/github.com/')
if [[ -z "$FILE" ]]; then
URL="$BASE/tree/$BRANCH"
else
RELATIVE_PATH=$(git ls-tree --full-name --name-only HEAD $FILE)
URL="$BASE/blob/$BRANCH/$RELATIVE_PATH"
fi
if which xdg-open > /dev/null
then
xdg-open $URL
elif which gnome-open > /dev/null
then
gnome-open $URL
elif which open > /dev/null
then
open $URL
fi
echo "Opened $URL"
else
echo "Not a git repo"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment