all files / lib/ index.js

95.65% Statements 22/23
91.67% Branches 11/12
100% Functions 3/3
95.65% Lines 22/23
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                                                                                         
"use strict";
 
// For generating the coverage badge
var path = require("path");
var downloader = require("./downloader");
var reportParser = require("./istanbulReportParser");
var defaultThresholds = require("./defaultThresholds");
var extend = require("xtend");
 
// exporting the plugin main function
module.exports = istanbulCoberturaBadger;
 
/**
 * Creates a code coverage badge based on the cobertura report generated by istanbul.
 *
 * @param {Object} opts is the set of properties provided to the api.
 * @param {Function} callback is the CPS function to get the results.
 */
function istanbulCoberturaBadger(opts, callback) {
  // Resolve the options
  opts = extend({
    // Setting the default coverage file generated by istanbul cobertura report.
    istanbulReportFile: "./coverage/cobertura-coverage.xml",
    // The default location for the destination being the coverage directory from istanbul.
    destinationDir: null,
    // The shields host to be used for retrieving the badge. https://github.com/badges/shields
    shieldsHost: process.env.SHIELDS_HOST || "https://img.shields.io",
    // The style of shield icon to generate (plastic, flat-square, flat)
    shieldStyle: "flat",
    // The name of the badge file to be generated
    badgeFileName: "coverage",
    // The thresholds to be used to give colors to the badge.
    thresholds: defaultThresholds
  }, opts);
 
  opts.badgeFormat = opts.badgeFormat || "svg";
 
  reportParser(opts.istanbulReportFile, function(err, report) {
    if (err) {
      return callback(err);
    }
 
    // The color depends on the fixed thresholds (RED: 0 >= % < 60) (YELLOW: 60 >= % < 90) (GREEN: % >= 90)
    var color = report.overallPercent >= opts.thresholds.excellent ? "brightgreen" :
      (report.overallPercent >= opts.thresholds.good ? "yellow" : "red");
 
    // The shields service that will give badges.
    var url = opts.shieldsHost + "/badge/coverage-" + report.overallPercent;
    url += "%25-" + color + "." + opts.badgeFormat + "?style=" + opts.shieldStyle;
 
    // Save always as coverage image.
    var badgeFileName = path.join(opts.destinationDir, opts.badgeFileName + "." + opts.badgeFormat);
 
    downloader(url, badgeFileName, function(err, downloadResult) {
      Iif (err) {
        return callback(err);
      }
 
      report.url = url;
      report.badgeFile = downloadResult;
      report.color = color;
 
      return callback(null, report);
    });
  });
}