Search code examples
jsongithubcolorsbadgeshields.io

Custom GitHub badges with dynamic color


I struggle with creating a shields.io badge which changes color dynamically.

I am able to use the JSON response to parse a text into a badge and set the color to orange:

https://img.shields.io/badge/dynamic/json.svg?label=custom&url=https://jsonplaceholder.typicode.com/posts&query=$[1].id&colorB=orange

enter image description here

Works well...


However, I want to change the color according to a rule. I might return the HEX color in JSON as well to be parsed into the badge. I tried the public API to get a random color and test the behavior:

http://www.colr.org/json/color/random

I get the first randomly get color with JsonPath $.colors[0].hex and place it o the badge URL as both as the dynamic value and color:

https://img.shields.io/badge/dynamic/json.svg?label=custom&url=http://www.colr.org/json/color/random&query=$.colors[0].hex&colorB=$.colors[0].hex

Regardless of the randomly chosen color, the result is always somehow green (the last generated result was #D0BB79:

enter image description here

I would expect something like this which correctly matches the #D0BB79 color:

enter image description here

How to make the color dynamic as well? The sample dynamically colorful badges are provided with Coveralls.io, Codecov.io or SonarCloud.io.


Solution

  • I had similar trouble, and ended up using a command line tool called anybadge which takes thresholds as parameters. This allows you to generate a badge with dynamic color in one command:

    anybadge -l pylint -v 2.22 -f pylint.svg 2=red 4=orange 8=yellow 10=green
    

    Colors can be defined by hex color code or a pre-defined set of color names.

    The main difference here is that this isn't done by referencing a URL, so can't be embedded in the same way. I use this in my CI pipeline to generate various badges, then store them as project artifacts and reference them in my project README.md.