Skip to content

Instantly share code, notes, and snippets.

@davidhq
Last active March 19, 2016 19:36
Show Gist options
  • Save davidhq/3189fd34ca415cb10547 to your computer and use it in GitHub Desktop.
Save davidhq/3189fd34ca415cb10547 to your computer and use it in GitHub Desktop.
# git helpers - davidhq
function git_repo {
local root=$(git rev-parse --show-toplevel || echo ".")
local cwd=`pwd`
cd $root
local origin=$(git remote -v | grep origin | grep push | sed 's/origin//g' | sed 's/[email protected]://g' | sed 's/https:\/\/github.com\///g' | sed 's/.git (push)//g' | xargs)
cd $cwd
eval "$1=$origin"
}
# Opens Github project in browser from command line
# og - opens current branch
# og [branch] - opens selected branch
# og copy - copies to clipboard
# og commits - opens commits tab
function og {
if ! $(git rev-parse --is-inside-work-tree > /dev/null 2>&1); then
>&2 printf "${RED}Not a git repository${NC}\n"
return 1
fi
local repo=''
git_repo repo
local origin="https://github.com/${repo}"
local branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$1" == 'copy' ]; then
# copy to clipboard
echo $origin | tr -d '\n' | pbcopy # chomp before copy
elif [ "$1" == 'commits' ]; then
# open commits tab
open "${origin}/commits/${branch}"
elif [ -n "$1" ]; then
open "${origin}/tree/${1}"
elif [ "$branch" != "master" ]; then
open "${origin}/tree/${branch}"
else
open $origin
fi
}
# Usage inside a git repository:
# gc utils/file.js
# to get:
# https://github.com/[user]/[repo]/blob/[branch]/utils/file.js
# copied to clipboard and printed on the command line (you can use newest iTerm2 to being able to click on urls from terminal with CMD+click)
function gc {
if ! $(git rev-parse --is-inside-work-tree > /dev/null 2>&1); then
>&2 printf "${RED}Not a git repository${NC}\n"
return 1
fi
local repo=''
git_repo repo
if [ -z "$1" ]; then
echo "Usage: gc folder/file.txt"
else
local repo_root=$(git rev-parse --show-toplevel || echo ".")
local file_path=$(readlink -f "$1" | tr -d '\n')
local branch=$(git rev-parse --abbrev-ref HEAD)
local url_cluttered="https://github.com/${repo}/blob/${branch}/${file_path}"
local url=$(echo $url_cluttered | sed "s#${repo_root}/##")
echo $url | tr -d '\n' | pbcopy
printf "Clipboard: ${YELLOW}$url${NC}\n"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment