Home Manual Reference Source Test Repository

src/Plugin.js

import { join } from 'path';
import { readFileSync } from 'fs';
import { EOL } from 'os';

/**
 * The require-coverage plugin
 */
export default class Plugin {

  /**
   * The default options to use
   * @type {Object}
   * @property {Number} required=90 The coverage percentage required
   */
  static get DefaultOptions() {
    return {
      required: 90,
    };
  }

  /**
   * Handles options passed through the plugin key inside esdoc.json
   * @param {Object} [options] The options to use
   * @param {Number} [options.required=Plugin.DefaultOptions.required] The coverage percentage
   * required
   */
  handleOptions(options) {
    const opts = Object.assign(Plugin.DefaultOptions, options);

    /**
     * The coverage percentage required
     * @type {Number}
     */
    this._required = opts.required;
  }

  /**
   * Handles configuration passed in esdoc.json
   * @param {Object} config The ESDoc configuration stored inside esdoc.json
   * @param {String} config.destination Needed for plugin to work
   */
  handleConfig(config) {
    /**
     * Path to the coverage.json file generated by ESDoc
     */
    this._coverageFilePath = join(config.destination, 'coverage.json');
  }

  /**
   * Checks the docs coverage against the limit specified in options
   * @throws {Error} Throws an error if coverage.json-file cannot be found
   * @throws {Error} Throws an error if coverage percentage is less than required
   */
  checkCoverage() {
    let coverageReport;

    try {
      coverageReport = JSON.parse(readFileSync(this._coverageFilePath));
    } catch (_) {
      throw new Error('coverage.json file not found. Double-check ESDoc finished.');
    }

    const covered = parseFloat(/([0-9.]+)%/.exec(coverageReport.coverage)[1], 10);

    if (covered < this._required) {
      throw new Error(`Coverage is at ${covered}%, (${this._required}% required)${EOL}`);
    }
  }

}