Last active
October 8, 2019 20:52
-
-
Save wilsoniya/5da12f6d3b5efa58e8909d32d6869487 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# gh_open.sh | |
# ========== | |
# A little utility to open a web browser to the github page for a given file at | |
# an optional line number, taking into account current git revision. This | |
# script is handy in coordination with your favorite text editor. Ever look at | |
# some code and wish you could quickly send your buddy a URL of exactly what | |
# you're seeing? Just map gh_open.sh to a keyboard shortcut. For best results | |
# add gh_open.sh to a directory in your $PATH. | |
# | |
# Vim, e.g. | |
# --------- | |
# nnoremap <leader>g :!gh_open.sh % <C-r>=line('.')<CR><CR> | |
# | |
# resolves the absolute path to a given relative file path | |
function _realpath() { | |
rel_path="${1}" | |
if hash realpath; then | |
realpath "${rel_path}" | |
elif hash python; then | |
python -c "import os; print(os.path.realpath('$rel_path'))" | |
else | |
>&2 echo "ERROR: realpath not available" | |
exit 3 | |
fi | |
} | |
prog="${0}" | |
fpath="${1}" | |
shift | |
line_num="${1}" | |
if [[ -z "${line_num}" ]]; then | |
line_suffix= | |
else | |
line_suffix="#L${line_num}" | |
fi | |
if [[ -z "${fpath}" ]]; then | |
>&2 echo "ERROR: file path must be specified." | |
>&2 echo "${prog} FILE [LINE_NUMBER]" | |
exit 1 | |
fi | |
abs_fpath=$(_realpath "${fpath}") | |
pushd $(dirname "${abs_fpath}") > /dev/null | |
# ensure we're in a git repo | |
git status &> /dev/null | |
if [[ "0" -ne $? ]]; then | |
>&2 echo "Given file must be within a git repository." | |
popd &> /dev/null | |
exit 2 | |
fi | |
gh_url_base=$( \ | |
git remote -v \ | |
| grep fetch \ | |
| head -n1 \ | |
| awk '{ print $2 }' \ | |
| sed -e 's/git@//' -e 's/:/\//' -e 's/\.git$//' \ | |
) | |
repo_relative_fpath=$(git ls-files --full-name "${abs_fpath}") | |
git_hash=$(git rev-parse HEAD) | |
url="https://${gh_url_base}/blob/${git_hash}/${repo_relative_fpath}${line_suffix}" | |
# open the GH url in-browser using an available command | |
if hash xdg-open; then | |
xdg-open "${url}" | |
elif hash open; then | |
open "${url}" | |
else | |
echo "Please manually open URL: ${url}" | |
fi | |
popd &> /dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment