All files badges.ts

95.45% Statements 21/22
75% Branches 18/24
100% Functions 3/3
95.45% Lines 21/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                                1x 1x         8x 8x 8x   8x 8x     8x     8x             8x 20x 1x   19x 7x   12x     8x             8x 1x 1x   1x     8x  
import { badgen } from 'badgen';
import { readFileSync } from 'fs';
import svgToTinyDataUri from 'mini-svg-data-uri';
import get from 'lodash.get';
 
// Copied from `badgen` because it's not exported
export type StyleOption = 'flat' | 'classic';
 
export interface BadgenOptions {
  status: string;
  subject?: string;
  color?: string;
  label?: string;
  style?: StyleOption;
  jsonPath?: string;
  labelColor?: string;
  icon?: string;
  iconWidth?: number;
  scale?: number;
}
 
export interface BadgeOption extends BadgenOptions {
}
 
const getIconString = (path: string) => {
  return readFileSync(path, 'utf8');
}
 
 
export function badge(option: BadgeOption, summary: object) {
  const { label = 'coverage', style = 'classic', jsonPath = 'total.statements.pct' } = option || {}
  let pct: any = summary;
  pct = get(summary, jsonPath, 0);
 
  Eif (!isNaN(Number(pct))) {
    pct = Number(pct);
  }
 
  Iif (typeof pct !== 'number') {
    throw new Error(`${jsonPath} evaluates to ${JSON.stringify(pct)} and is not a suitable path in the JSON coverage data`);
  }
  const colorData = {
    '#49c31a': [100],
    '#97c40f': [99.99, 90],
    '#a0a127': [89.99, 80],
    '#cba317': [79.99, 60],
    '#ce0000': [59.99, 0],
  }
  const color = Object.keys(colorData).find((value: keyof typeof colorData, idx) => {
    if (colorData[value].length === 1 && pct >= colorData[value][0]) {
      return true
    }
    if (colorData[value].length === 2 && pct <= colorData[value][0] && pct >= colorData[value][1]) {
      return true
    }
    return false;
  });
 
  const badgenArgs: BadgenOptions = {
    style,
    label,
    status: `${pct < 0 ? 'Unknown' : `${pct}%`}`,
    color: (color || 'e5e5e5').replace(/^#/, ''),
  };
 
  if(option.icon) {
    const svgString = getIconString(option.icon) as string;
    const svgDataUri = svgToTinyDataUri(svgString);
 
    badgenArgs.icon = svgDataUri;
  }
 
  return badgen(badgenArgs);
}