Skip to content

Instantly share code, notes, and snippets.

@thomasnordquist
Created June 29, 2018 11:12
Show Gist options
  • Save thomasnordquist/7998266efaaa5b233268d821d142232a to your computer and use it in GitHub Desktop.
Save thomasnordquist/7998266efaaa5b233268d821d142232a to your computer and use it in GitHub Desktop.
Creates a code coverage bash with bash "only"
#!/bin/bash
#
# Creates a coverage badge svg with bash "only"
# Intent is to create a coverage badge in a travis job and uploading it to S3 so it can be displayed in a projects readme
#
# Uses: bash, read, cut, sed
#
# Usage: makeCoverageBadge.sh percent target_svg
# Example: makeCoverageBadge.sh 81.83 coverage.svg
#
#
#
# License:
# The badge template is based on the shields.io badges and are licensed under a CC0 License
# https://github.com/badges/shields/blob/master/LICENSE.md
#
# This script itself may be used and altered as pleased.
#
COVERAGE=$1 # Coverage in percent with two decimals: 81.34
OUTPUT=$2 # Name/Location of the svg
read -r -d '' TEMPLATE << EOM
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="114" height="20">
<linearGradient id="b" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1" />
<stop offset="1" stop-opacity=".1" />
</linearGradient>
<clipPath id="a">
<rect width="114" height="20" rx="3" fill="#fff" />
</clipPath>
<g clip-path="url(#a)">
<path fill="#555" d="M0 0h59v20H0z" />
<path fill="__COLOR__" d="M59 0h60v20H59z" />
<path fill="url(#b)" d="M0 0h114v20H0z" />
</g>
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110">
<text x="305" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="490">coverage</text>
<text x="305" y="140" transform="scale(.1)" textLength="490">coverage</text>
<text x="860" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="450">__PERCENT__</text>
<text x="860" y="140" transform="scale(.1)" textLength="450">__PERCENT__</text>
</g>
</svg>
EOM
function colorForCoverage() {
COVERAGE=$1
# Remove decimal precision as bash can only use integers in calculations
GOOD_FACTOR=$(echo -n "$COVERAGE" | cut -d"." -f1)
GOOD_COLOR=(68 204 17)
BAD_FACTOR=$(( 100 - GOOD_FACTOR ))
BAD_COLOR=(224 93 68)
RED=$(( BAD_COLOR[0]*BAD_FACTOR/100 + GOOD_COLOR[0]*GOOD_FACTOR/100 ))
GREEN=$(( BAD_COLOR[1]*BAD_FACTOR/100 + GOOD_COLOR[1]*GOOD_FACTOR/100 ))
BLUE=$(( BAD_COLOR[2]*BAD_FACTOR/100 + GOOD_COLOR[2]*GOOD_FACTOR/100 ))
# Build SVG color string
echo -n "rgb($RED,$GREEN,$BLUE)"
}
COLOR=$(colorForCoverage "$COVERAGE")
(echo "$TEMPLATE") \
| sed -e "s/__PERCENT__/$COVERAGE%/g" \
| sed -e "s/__COLOR__/'$COLOR'/g" \
> "$OUTPUT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment