Open GitHub when pushing a new branch

When I push a new branch to remote in git, 99% of the time my next step will be going to http://github.com, locating the repo, and opening a PR (pull request) for the changes. Wouldn't it be nice if the opening of the repo page would happen automagically? Yes, it would. It can save you multiple seconds every day! Okay, maybe not life-changing, but it sounds like a nice hack anyway, so here we go.

Using a git hook

I figured I could use a git hook to start up the browser and go to the right repo. It turns out there is no post-push hook, but for this purpose, a pre-push hook will also do the job. If you copy the bash script below to <repo-base>/.git/hooks/pre-push and make it executable, each time you push a new branch to remote, the GitHub page for the repo will open. There you'll see the changes and can open the PR.
#!/bin/bash 
# the hook is executed in the root of the repo, so assuming repo name is current dir 
REPO=$(basename "$(pwd)") 
BRANCH=$(git rev-parse --abbrev-ref HEAD) 
echo "Pushing to repo $REPO, branch $BRANCH" 
git show-branch "remotes/origin/$BRANCH" 
EXISTS=$? 
if [[ "$EXISTS" -eq 0 ]] 
then 
  echo "The branch $BRANCH already exists on remote, nothing to do" 
  exit 0 
fi 
 
echo "The branch $BRANCH does not exist on remote, opening Github page" 
URL="https://github.com/$REPO" 
firefox "$URL" 
The script checks if the branch already exists on remote. In case it does, this won't be the first commit, so probably a PR has already been created, and there's no need to open the repo page. Whether this makes sense or not will of course depend on your workflow.

Applying the hook everywhere

In case you like this hook, you will want to use it in every locally cloned repo. One way is to create a directory ~/.git-template/hooks and put the git hook in there. Now make this your default git template source by running:
 $ git config --global init.templatedir '~/.git-template' 
From now on, each newly cloned repo will have this hook configured by default. For existing repos, you can run git init in the root of the repo. This will also copy the hooks from your template directory, but won't otherwise change the existing configuration of that repo.


related blogs: