Linking to Github

It was rightly pointed out yesterday that it’s dangerous to link to lines or blocks of code on Github without explicitly specifying the commit hash in the URL. On this theme, consider this git command:

$ git browse -u -- commit/$(git rev-parse HEAD)

This emits the Github URL to the HEAD commit on the current branch, specifying the commit hash in the URL. Note that the browse subcommand is provided by the excellent hub library.

Pasting links to commits is common, both for mailing list posts and within discussion on Github itself. Getting the correct URL quickly is useful.

We can streamline further using an alias:

# ~/.gitconfig

url = !hub browse -u -- commit/$(git rev-parse HEAD)

so we can run:

$ git url

to get the expanded HEAD URL. Even better, we can parameterise:

# ~/.gitconfig

url = "!f() { sha=$(git rev-parse ${1:-HEAD}); hub browse -u -- commit/$sha; }; f"

so we can now specify a commit:

$ git url

$ git url head

$ git url head^

Several times a day, I run one of the above, piping the output into the clipboard for easy pasting:

$ git url | clipboard


# ~/.bashrc

alias clipboard='pbcopy'  # osx clipboard

Here’s a few more useful git aliases based on the browse subcommand:

# ~/.gitconfig

commits = !hub browse -- commits
issues = !hub browse -- issues
wiki = !hub browse -- wiki
settings = !hub browse -- settings

Tagged with: git, commandlinefu
Filed in: tips
Revision history

Previous: Continuously rebuild your project
Next: Integrating Django application metrics into Zabbix

Copyright © 2005-2017 David Winterbottom
Content licensed under CC BY-NC-SA 4.0.