1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3 4""" 5This script generates a "coverage" badge as a svg file from 6the html report from coverage.py 7 8Usage: 9 10 $ ./coverage_badge.py htmlcov/ coverage.svg 11 12""" 13 14import os 15 16# this template was generated from shields.io on 2015-10-11 17template = """ 18<svg xmlns="http://www.w3.org/2000/svg" width="92" height="20"> 19<linearGradient id="b" x2="0" y2="100%"> 20<stop offset="0" stop-color="#bbb" stop-opacity=".1"/> 21<stop offset="1" stop-opacity=".1"/> 22</linearGradient> 23<mask id="a"> 24<rect width="92" height="20" rx="3" fill="#fff"/> 25</mask> 26<g mask="url(#a)"> 27<path fill="#555" d="M0 0h63v20H0z"/> 28<path fill="{0:s}" d="M63 0h29v20H63z"/> 29<path fill="url(#b)" d="M0 0h92v20H0z"/> 30</g> 31<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva, 32 sans-serif" font-size="11"> 33<text x="31.5" y="15" fill="#010101" fill-opacity=".3">coverage</text> 34<text x="31.5" y="14">coverage</text> 35<text x="76.5" y="15" fill="#010101" fill-opacity=".3">{1:s}%</text> 36<text x="76.5" y="14">{1:s}%</text> 37</g> 38</svg> 39""" 40 41 42def get_coverage(htmldir): 43 for line in open(os.path.join(htmldir, "index.html"), "rt"): 44 if "pc_cov" in line: 45 return int(line.split("pc_cov")[1].split(">")[1].split("<")[0].rstrip("%")) 46 raise ValueError("Could not find pc_cov in index.html") 47 48 49def write_cov_badge_svg(path, percent): 50 colors = "#e05d44 #fe7d37 #dfb317 #a4a61d #97CA00 #4c1".split() 51 limits_le = 50, 60, 70, 80, 90, 100 52 c = next(clr for lim, clr in zip(limits_le, colors) if percent <= lim) 53 with open(path, "wt") as f: 54 f.write(template.format(c, str(percent))) 55 56 57if __name__ == "__main__": 58 import sys 59 60 assert len(sys.argv) == 3 61 cov_percent = get_coverage(sys.argv[1]) 62 write_cov_badge_svg(sys.argv[2], cov_percent) 63