DEV Community

Jakub T. Jankiewicz
Jakub T. Jankiewicz

Posted on

GitHub Action to clear cache on Images in README

So I have a few Open Source project on GitHub, where I have README with badges. And one of those badges is always coveralls status (code coverage tracking service).

It looks like this:

Code Coverage Badge

This is one of my recent Open Source projects called Gaiman.

The old way I was doing was getting the commit hash and appending it to the URL of the image.

But there is a better way. You basically send PURGE request to GitHub for their cached images. Those that have camo sub domain.

curl -w "\n" -s -X PURGE https://camo.githubusercontent.com/...
Enter fullscreen mode Exit fullscreen mode
  • -s option mean silent
  • -w "\n" mean add newline at the end
  • -X PURGE mean send PURGE request

And this clear the cache for this image. But you can automate this with GitHub actions. I always use make for my builds (default build system for GNU/Linux), so here is the Makefile I'm using:

CURL=curl
GREP=grep

README_TMP=readme.html
# change those for your project
USER=jcubic
REPO=gaiman

.PHONY: purge

purge:
    $(CURL) -s https://github.com/$(USER)/$(REPO)/blob/master/README.md > $(README_TMP)
    $(GREP) -Eo '<img src="[^"]+"' $(README_TMP) | $(GREP) camo | $(GREP) -Eo 'https[^"]+' | xargs -I {} $(CURL) -w "\n" -s -X PURGE {}
Enter fullscreen mode Exit fullscreen mode

The code use linux commands, curl to get the readme save it into a file, and extract the urls usig grep. Then call CURL again that will PURGE the images from cache.

Now to automate this you need to add workflow, the only need for the purge is if you have workflows already that change something so you basically add at the end:

- name: Purge README Images
  run: make purge
Enter fullscreen mode Exit fullscreen mode

If you want to see my whole workflow file check my repo buid.yaml file.

And that's it. If you like this post consider following me on twitter: @jcubic.

Discussion (0)