Sunday, January 15, 2017

How to change GitHub repo's preview image (sort of)

 Do you like having a photo of yourself as GitHub avatar but hate having it pop up as a preview when you post a repo on social media? Reed on!



First things first, let me explain the "(sort of)" part o the title. Since there is no officially supported way from GitHub, at the time of writing, to achieve the desired result, the process described is a workaround, a hack, and thus entails a trade-off; you have to use a custom URL so anyone sharing directly the URL of your repo will get the original preview image.

To achieve our goal we are going to utilize GitHub's project page generator that will generate a URL in the form : <username>.github.io/<repoName> (and this will be the link you will be sharing instead of the direct repo link that would be github.com/<username>/<repoName>). To better understand the process, we will see a general and an applied example in parallel. So in our case we will take one of my GitHub repos as an example github.com/panagiks/RSPET and the generated link will be panagiks.github.io/RSPET.

GitHub's Project page generator

GitHub provides a few ways to generate project pages, but for the purpose of this post we'll go with the gh-pages branch approach. First, create a new branch in your repo named "gh-pages" (no quotes) and empty it (delete all and any files that were at the source branch). Now create an empty file in the root of the newly created branch named "index.html". Now go to the repo's settings page and scroll down to the "GitHub Pages" section. There, in the "Source" section, you should see "gh-pages branch" selected in the drop-down menu, if not select it.

Populating index.html

The point is to create a webpage that will have the appropriate "meta" tags for social media to present it as if it was your GitHub repo, just changing the tags that correspond to the preview image. First make sure that you have uploaded the desired (new) preview image to a CDN (Content Distribution Network), I prefer Flikr for this because it's free and you can easily keep all your images in one place and also have them resized, but feel free to use any CDN you prefer the only thing that matters is that you have a URL pointing to the image. First is our example for github.com/panagiks/RSPET and following is the head section of the general index.html:

In the body of index.html we only want it to redirect to the actual GitHub repo, to do that we do the following:



Final Notes

A helpful tool is Facebook's debug tool, from which you can see how Facebook will load and display your link as well as force its scrapper to rescrape your link. Finally, I intend to write a small script that will generate automatically the above "index.html" for any given GitHub repo, so stay tuned!
 

Edit

As promised, here's RGHPI, a script to automate the HTML generation step :)