GitHub Action to clear cache on Images in README
Jakub T. Jankiewicz
Posted on December 26, 2021
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:
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/...
-
-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 {}
(Make sure to use Tab character for indentation in Makefile, Dev.to convert them to spaces).
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
If you want to see my whole workflow file check my repo buid.yaml file.
EDIT This solution didn't work with recent updates from GitHub. The reason is that GitHub doesn't return HTML anymore. You can use -H "Accept: text/html"
the option to curl but the output HTML don't have the README. So in fact GitHub doesn't render the HTML without JavaScript.
Here is updated Makefile:
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 {}
when you download the file you get JSON in response but it have the images only quote is escaped \"
and to put the backslash into string you need to escape it, so this become \\"
. The rest of the code is the same.
And that's it. If you like this post, you can follow me on twitter at @jcubic and check my home page.
Posted on December 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.