Skip to content

Instantly share code, notes, and snippets.

@MichaelCurrin
Last active October 22, 2021 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelCurrin/9ee2f9b20302a5ab939936762102ca1a to your computer and use it in GitHub Desktop.
Save MichaelCurrin/9ee2f9b20302a5ab939936762102ca1a to your computer and use it in GitHub Desktop.
Open Repo shell tool

Open Repo shell tool

Open the current git repo directory on GitHub in your default browser.

Run this in a directory within a local git repo. The directory will be opened in your browser such as on GitHub.

Features

  • Works for any user or org, as long as .git directory exists at some level.
  • Recognizes subdirectories.
  • Handles branches.
  • Supports any host - GitHub, BitBucket, GitLab, etc.
  • Works with both SSH and HTTP remote urls .
    • git@github.com:USERNAME/REPO_NAME.git
    • https://github.com/USERNAME/REPO_NAME.git

Sample

$ open-repo
Opening: https://github.com/MichaelCurrin/unicron/tree/master

Installation

  1. Download or copy the contents of the script. You can omit .sh in the name - it just helps for syntax highlighting when viewed on GitHub.
  2. Add as a shell script in ~/bin directory or somewhere else in your PATH.
  3. Mark it as executable.
$ chmod +x open-repo
  1. Navigate to a git directory and run the script as you named like.
$ cd my-repo
$ open-repo

Usage

Here is a demo of running commands in the MichaelCurrin/unicron GitHub repo.

$ git clone git@github.com:MichaelCurrin/unicron.git
$ cd unicron

Open root

$ open-repo
Opening: https://github.com/MichaelCurrin/unicron/tree/master

Open subdirectory

$ cd docs
$ open-repo
Opening: https://github.com/MichaelCurrin/unicron/tree/master/docs/

Switch branches

$ git checkout my-feature
$ open-repo
Opening: https://github.com/MichaelCurrin/unicron/tree/my-feature/docs/
#!/usr/bin/env bash
# Open repo application.
#
# Documentation and latest code:
# https://gist.github.com/MichaelCurrin/9ee2f9b20302a5ab939936762102ca1a/
set -e
GET_REMOTE_URL_CMD="git remote get-url origin"
GET_BRANCH_CMD="git branch --show-current"
GET_DIR_CMD="git rev-parse --show-prefix"
is_repo() {
git rev-parse 2>/dev/null || (
echo 'Error: Not a git repo'
return 1
)
}
get_url() {
local REMOTE_URL=$($GET_REMOTE_URL_CMD)
local PARTS=($(echo "$REMOTE_URL" | sed 's/\.git// ; s/com[/:]/\
/'))
local NWO="${PARTS[1]}"
local BRANCH=$($GET_BRANCH_CMD)
local URL="https://github.com/$NWO/tree/$BRANCH"
local DIR_PATH=$($GET_DIR_CMD)
if [[ -n "$DIR_PATH" ]]; then
URL="$URL/$DIR_PATH"
fi
echo "$URL"
}
browse() {
local URL="$1"
echo "Opening: $URL"
open "$URL"
}
is_repo
URL=$(get_url)
browse "$URL"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment