A one-line command to accelerate Github Pull Requests

Context

Like most product teams out there, your Git flow probably consists of opening a new branch for each new feature, and sub-branches for each sub-feature, merging them back into the feature branch and then ultimately merging it all on master.

To accelerate development and review flows, it is critical that each developer opens a new pull request as soon as possible when working on a new branch.

This flow requires tedious operations every time you're starting working on an issue:

  1. Checkout from the current branch
  2. Make some "dummy" changes so you can validly open a pull request when pushing (because no pull requests can be opened when there isn't anything to compare)
  3. Commit the changes
  4. Push the newly created branch
  5. Open the URL provided by Github in your browser to open the pull request
  6. Create the pull request from the Github UI
  7. Come back to your terminal to start the actual work

Because there are many operations involved, it is easy/tempting to miss some steps and hence decrease the team efficiency as a whole.

As they are well aware of the pain of having to switch between terminal and web UI, the Github team fortunately has created hub, a CLI tool for Github which amongst others allows you to remotely open a pull request. However, I wanted an all-in-one solution for the operations above.

Prequisites

To use the below script, you will need to:

  • Install the hub CLI: brew install hub
  • Setup the CLI with your Github credentials: hub browse
  • Prepare an alias for the script. To keep things simple, I put it directly in my ~/.zshrc file which keeps all my terminal aliases

The script

The below script lets you directly create a branch and open a valid pull request against the current branch, by passign the new branch name as argument. All in a single command.

pr() { 
  # Save current branch name
  CURRENT_BRANCH=$(git branch | grep \* | cut -d ' ' -f2-)
  # Check out from current branch to new branch
  git checkout -b $1
  # Create empty commit to allow opening a PR
  git commit --allow-empty -m "Create branch"
  # Push the new branch and open a PR against the current branch, with branch name as PR title
  hub pull-request --push --base $CURRENT_BRANCH --message $1
}

Usage

Create a branch and open a pull request named 42-my-feature-branch against master:

# Assuming you're on master branch
> pr 42-my-feature-branch 

Create a sub-branch and pull request against the current feature branch:

# Assuming you're on 42-my-feature-branch
> pr 43-my-subfeature-branch

A possible improvement would be to ensure that no automated repo actions are triggered when empty commits are pushed.

Enjoy this trick!