Skip to content

Making a flexible 'pr' command

Posted on:April 7, 2023

Until recently, I’ve been using a very simple alias:

alias pr="gh pr create --web # Create a PR on GitHub opening in a new tab"

This alias uses the GitHub CLI to create a new PR using the current branch, and opens the new PR in the web so I can modify it. This is a great flow when you’re working exclusively on GitHub projects.

However, recently I’ve been working on a project that uses a self-hosted Gitea repository.

So, it would seem my GitHub CLI has no power here.

Théoden mocking my simplistic pr alias

But never fear!

It turns out you can open a PR on Gitea using the following URL structure:

https://<remote-url>/compare/<root-branch>...<current-branch>

So I wrote a small bash function that determines whether to use the github CLI, or the more generic PR url structure. Admittedly, this may not work with alternative git hosts, but it at least provides a flexible framework which can grow as needed.

function pr() {
  local remoteUrl=$(getGitRemoteUrl) # Helper function for: git remote -v | head -n 1 | awk '{ print $2 }'
  # If the remote URL contains "github.com", use the GitHub CLI
  if [[ "${remoteUrl}" == *"github.com"* ]]; then
    gh pr create --web # Create a PR on GitHub opening in a new tab
  else
    # Otherwise, use the generic URL structure
    local remoteWithoutGitEnding=$(getGitRemoteUrl | sed 's/\.git$//')
    # getPrimaryBranch returns "main" or "master" depending on the root branch for the current repo
    # getBranch returns the current branch name
    open "${remoteWithoutGitEnding}/compare/$(getPrimaryBranch)...$(getBranch)"
  fi
}

If I found myself working with other hosts with varying URL structures, I could easily modify this to be a case rather than an if statement.

Overall, this makes throwing up quick PRs much faster, and keeps me from needing to click around in the UI.


Thanks for reading! If you enjoyed this, you may also enjoy following me on twitter!