Open Git commit hashes in the browser directly from iTerm2

I came across a wonderful idea in Shrey Banga’s blog post Little known features of iTerm2 today. You can use the Smart Selection feature to have your terminal recognize git commit hashes and perform a certain action when opening (⌘+Click) them.

The solution presented in that blog post is using GitHub’s hub command-line tool, though. I’m trying to avoid GitHub where I can1, so both my personal and work related repositories are almost exclusively on self-hosted GitLab installations. Therefore I tried finding a more general way to achieve this. It’s actually pretty simple to come up with a solution that doesn’t require an external tool, as you can just use ‌git config --get remote.origin.url to extract the remote url. For both GitHub and GitLab, this value is easily translatable to the web interface.2

For example the sources to this blog are hosted at
https://gitlab.manu.space/websites/log.manuelgrabowski.de
and the corresponding remote url is
git@gitlab.manu.space:websites/log.manuelgrabowski.de.git
so all it takes is a few string replacements:

git config --get remote.origin.url | sed -e 's/:/\//' -e 's/\.git//' -e 's/git@/https:\/\//'

The full command you need to enter at the action for the Git commit hash RegEx in the Smart Selection settings is as follows:

open $(cd "\d" && git config --get remote.origin.url | sed -e 's/:/\//' -e 's/\.git//' -e 's/git@/https:\/\//')"/-/commit/\0"

  1. For which there are good reasons, but I also just like GitLab’s idea of CI a lot more. ↩︎

  2. I’m sure there are edge cases where that won’t work, but it should do the trick most of the time and can easily be adapted. ↩︎