All files / src/cli-validator/utils jsonResults.js

100% Statements 25/25
81.25% Branches 13/16
100% Functions 5/5
100% Lines 25/25

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 7228x 28x     28x   28x                   10x 10x                   52x   52x 52x 52x 205x 217x 993x     993x   993x           233x     233x   233x 3x             993x 91x   993x         52x     28x 28x  
const each = require('lodash/each');
const getPathAsArray = require('./getPathAsArray');
 
// get line-number-producing, 'magic' code from Swagger Editor
const getLineNumberForPath = require(__dirname + '/../../plugins/ast/ast')
  .getLineNumberForPath;
const validatorVersion = require('../../../package.json').version;
 
// function to print the results as json to the console.
function printJson(
  results,
  originalFile = null,
  verbose = false,
  errorsOnly = false
) {
  // render the results to json in the console with 2 char spacing
  results = formatResultsAsObject(results, originalFile, verbose, errorsOnly);
  console.log(JSON.stringify(results, null, 2));
}
 
function formatResultsAsObject(
  results,
  originalFile = null,
  verbose = false,
  errorsOnly = false
) {
  // initialize the results with the validator version
  const formattedResults = { version: validatorVersion };
 
  const allErrorCategories = ['errors', 'warnings', 'infos', 'hints'];
  const types = errorsOnly ? ['errors'] : allErrorCategories;
  types.forEach(type => {
    each(results[type], problems => {
      problems.forEach(problem => {
        let path = problem.path;
 
        // path needs to be an array to get the line number
        path = getPathAsArray(path);
 
        if (originalFile) {
          // get line number from the path of strings to the problem
          // as they say in src/plugins/validation/semantic-validators/hook.js,
          //
          //                  "it's magic!"
          //
          const line = getLineNumberForPath(originalFile, path);
 
          // add the line number to the result JSON
          problem.line = line;
 
          if (verbose && problem.componentPath) {
            problem.componentLine = getLineNumberForPath(
              originalFile,
              getPathAsArray(problem.componentPath)
            );
          }
        }
        // initialize object for this type of error (e.g. error, warning, info, hint)
        if (!formattedResults[type]) {
          formattedResults[type] = [];
        }
        formattedResults[type].push(problem);
      });
    });
  });
 
  return formattedResults;
}
 
module.exports.formatResultsAsObject = formatResultsAsObject;
module.exports.printJson = printJson;