All files / src/cli-validator runValidator.js

88.69% Statements 149/168
77.27% Branches 51/66
87.5% Functions 7/8
88.96% Lines 145/163

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352  12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x       12x 53x     53x 1x 1x       52x 52x   52x 52x 52x 52x 52x   52x 52x   52x   52x     52x 1x         52x           52x               52x 52x 54x           54x 52x 52x           52x         52x 52x 52x 52x 54x 52x   2x 2x 2x             52x 2x                             52x 52x 52x   52x 52x 1x           52x 2x 2x         50x 50x             50x 50x   1x         49x       49x           49x     49x 49x         49x 50x 2x       50x 50x 50x   50x 50x   3x 3x 1x 1x 1x 1x 1x 1x   3x 47x 47x     49x           49x 49x 1x       2x       2x 2x 2x         48x 48x       48x 48x   1x 1x     1x 1x         48x         47x 47x   47x                   47x         47x 47x                       47x 2x 2x 2x       47x 26x     21x 21x 45x   21x 1x   1x     1x                 47x 4x     47x 10x   37x 31x                   6x 6x         49x             1x       12x  
#!/usr/bin/env node
const util = require('util');
const fs = require('fs');
const path = require('path');
const readYaml = require('js-yaml');
const isPlainObject = require('lodash/isPlainObject');
const last = require('lodash/last');
const chalk = require('chalk');
const jsonValidator = require('json-dup-key-validator');
const globby = require('globby');
const ext = require('./utils/fileExtensionValidator');
const config = require('./utils/processConfiguration');
const buildSwaggerObject = require('./utils/buildSwaggerObject');
const validator = require('./utils/validator');
const print = require('./utils/printResults');
const { printJson } = require('./utils/jsonResults');
const printError = require('./utils/printError');
const preprocessFile = require('./utils/preprocessFile');
const spectralValidator = require('../spectral/utils/spectral-validator');
const dedupFunction = require('../cli-validator/utils/noDeduplication');
const addPathsToComponents = require('./utils/addPathsToComponents');
const { Spectral } = require('@stoplight/spectral');
// import the init module for creating a .validaterc file
const init = require('./utils/init.js');
 
// this function processes the input, does the error handling,
//  and acts as the main function for the program
const processInput = async function(program) {
  let args = program.args;
 
  // require that arguments are passed in
  if (args.length === 0) {
    program.help();
    return Promise.reject(2);
  }
 
  // interpret the options
  const printValidators = !!program.print_validator_modules;
  const reportingStats = !!program.report_statistics;
 
  const turnOffColoring = !!program.no_colors;
  const defaultMode = !!program.default_mode;
  const jsonOutput = !!program.json;
  const errorsOnly = !!program.errors_only;
  const debug = !!program.debug;
 
  const configFileOverride = program.config;
  const rulesetFileOverride = program.ruleset;
 
  const limitsFileOverride = program.limits;
 
  const verbose = program.verbose > 0;
 
  // turn off coloring if explicitly requested
  if (turnOffColoring) {
    chalk.level = 0;
  }
 
  // if the 'init' command is given, run the module
  // and exit the program
  Iif (args[0] === 'init') {
    return await init.printDefaults(chalk);
  }
 
  // if the 'migrate' command is given, run the module
  // and exit the program
  Iif (args[0] === 'migrate') {
    return await init.migrate(chalk);
  }
 
  // otherwise, run the validator on the passed in files
  // first, process the given files to handle bad input
 
  // ignore files in .validateignore by comparing absolute paths
  const ignoredFiles = await config.ignore();
  const filteredArgs = args.filter(
    file => !ignoredFiles.includes(path.resolve(file))
  );
 
  // determine which files were removed from args because they were 'ignored'
  // then, print these for the user. this way, the user is alerted to why files
  // aren't validated
  const filteredFiles = args.filter(file => !filteredArgs.includes(file));
  Iif (filteredFiles.length) console.log();
  filteredFiles.forEach(filename => {
    console.log(
      chalk.magenta('[Ignored] ') + path.relative(process.cwd(), filename)
    );
  });
 
  args = filteredArgs;
 
  // at this point, `args` is an array of file names passed in by the user.
  // nothing in `args` will be a glob type, as glob types are automatically
  // converted to arrays of matching file names by the shell.
  const supportedFileTypes = ['json', 'yml', 'yaml'];
  const filesWithValidExtensions = [];
  let unsupportedExtensionsFound = false;
  args.forEach(arg => {
    if (ext.supportedFileExtension(arg, supportedFileTypes)) {
      filesWithValidExtensions.push(arg);
    } else {
      Eif (!unsupportedExtensionsFound) console.log();
      unsupportedExtensionsFound = true;
      console.log(
        chalk.yellow('[Warning]') +
          ` Skipping file with unsupported file type: ${arg}`
      );
    }
  });
 
  if (unsupportedExtensionsFound) {
    console.log(
      chalk.magenta(
        'Supported file types are JSON (.json) and YAML (.yml, .yaml)'
      )
    );
  }
 
  // globby is used in an unconventional way here. we are not passing in globs,
  // but an array of file names. what globby does is search through the file
  // system looking for files that match the names in the array. it returns a
  // list of matches (file names). Therefore, any files that are in
  // filesWithValidExtensions, but are NOT in the array globby returns, do
  // not actually exist. This is a convenient way of checking for file
  // existence before iterating through and running the validator on
  // every file.
  const filesToValidate = await globby(filesWithValidExtensions);
  const nonExistentFiles = filesWithValidExtensions.filter(
    file => !filesToValidate.includes(file)
  );
  if (nonExistentFiles.length) console.log();
  nonExistentFiles.forEach(file => {
    console.log(
      chalk.yellow('[Warning]') + ` Skipping non-existent file: ${file}`
    );
  });
 
  // if no passed in files are valid, exit the program
  if (filesToValidate.length === 0) {
    printError(chalk, 'None of the given arguments are valid files.');
    return Promise.reject(2);
  }
 
  // process the config file for the validations
  let configObject;
  try {
    configObject = await config.get(defaultMode, chalk, configFileOverride);
  } catch (err) {
    return Promise.reject(err);
  }
 
  // get limits from .thresholdrc file
  let limitsObject;
  try {
    limitsObject = await config.limits(chalk, limitsFileOverride);
  } catch (err) {
    return Promise.reject(err);
  }
 
  // define an exit code to return. this will tell the parent program whether
  // the validator passed or not
  let exitCode = 0;
 
  // fs module does not return promises by default
  // create a version of the 'readFile' function that does
  const readFile = util.promisify(fs.readFile);
  let originalFile;
  let input;
 
  // create an instance of spectral & load the spectral ruleset, either a user's
  // or the default ruleset
  const spectral = new Spectral({
    computeFingerprint: dedupFunction
  });
  try {
    await spectralValidator.setup(spectral, rulesetFileOverride, configObject);
  } catch (err) {
    return Promise.reject(err);
  }
 
  for (const validFile of filesToValidate) {
    if (filesToValidate.length > 1) {
      console.log(
        '\n    ' + chalk.underline(`Validation Results for ${validFile}:`)
      );
    }
    try {
      originalFile = await readFile(validFile, 'utf8');
      originalFile = preprocessFile(originalFile);
 
      const fileExtension = ext.getFileExtension(validFile);
      if (fileExtension === 'json') {
        // find and fix trailing commas
        const match = originalFile.match(/,\s*[}\]]/m);
        if (match) {
          const chars = originalFile.substring(0, match.index);
          const lineNum = (chars.match(/\n/g) || []).length + 1;
          const msg = `Trailing comma on line ${lineNum} of file ${validFile}.`;
          printError(chalk, chalk.red(msg));
          exitCode = 1;
          originalFile = originalFile.replace(/,(\s*[}\]])/gm, '$1');
        }
        input = JSON.parse(originalFile);
      } else Eif (fileExtension === 'yaml' || fileExtension === 'yml') {
        input = readYaml.safeLoad(originalFile);
      }
 
      Iif (!isPlainObject(input)) {
        throw `The given input in ${validFile} is not a valid object.`;
      }
 
      // jsonValidator looks through the originalFile for duplicate JSON keys
      //   this is checked for by default in readYaml
      const duplicateKeysError = jsonValidator.validate(originalFile);
      if (fileExtension === 'json' && duplicateKeysError) {
        throw duplicateKeysError;
      }
    } catch (err) {
      const description =
        'Invalid input file: ' +
        chalk.red(validFile) +
        '. See below for details.';
 
      printError(chalk, description, err);
      exitCode = 1;
      continue;
    }
 
    // change working directory to location of root api definition
    // this will allow the parser in `buildSwaggerObject` to resolve external refs correctly
    const originalWorkingDirectory = process.cwd();
    process.chdir(path.dirname(validFile));
 
    // validator requires the swagger object to follow a specific format
    let swagger;
    try {
      swagger = await buildSwaggerObject(input);
    } catch (err) {
      printError(chalk, 'There is a problem with the Swagger.', getError(err));
      Iif (debug) {
        console.log(err.stack);
      }
      exitCode = 1;
      continue;
    } finally {
      // return the working directory to its original location so that
      // the rest of the program runs as expected. using finally block
      // because this must happen regardless of result in buildSwaggerObject
      process.chdir(originalWorkingDirectory);
    }
 
    // run spectral and save the results
    let spectralResults;
    try {
      process.chdir(path.dirname(validFile));
      // let spectral handle the parsing of the original swagger/oa3 document
      spectralResults = await spectral.run(originalFile);
    } catch (err) {
      printError(chalk, 'There was a problem with spectral.', getError(err));
      if (debug) {
        console.log(err.stack);
      }
      exitCode = 1;
      continue;
    } finally {
      // return the working directory to its original location
      process.chdir(originalWorkingDirectory);
    }
 
    // run validator, print the results, and determine if validator passed
    let results;
    try {
      results = validator(swagger, configObject, spectralResults, debug);
    } catch (err) {
      printError(chalk, 'There was a problem with a validator.', getError(err));
      if (debug) {
        console.log(err.stack);
      }
      exitCode = 1;
      continue;
    }
 
    // the warning property tells the user if warnings are included as part of the output
    // if errorsOnly is true, only errors will be returned, so need to force this to false
    if (errorsOnly) {
      results.warning = false;
      results.info = false;
      results.hint = false;
    }
 
    // fail on errors or if number of warnings exceeds warnings limit
    if (results.error) {
      exitCode = 1;
    } else {
      // Calculate number of warnings and set exit code to 1 if warning limit exceeded
      let numWarnings = 0;
      for (const key of Object.keys(results.warnings)) {
        numWarnings += results.warnings[key].length;
      }
      if (numWarnings > limitsObject.warnings) {
        exitCode = 1;
        // add the exceeded warnings limit as an error
        Iif (!results.errors) {
          results.errors = {};
        }
        results.errors['warnings-limit'] = [
          {
            path: [],
            message: `Number of warnings (${numWarnings}) exceeds warnings limit (${limitsObject.warnings}).`
          }
        ];
      }
    }
 
    if (verbose) {
      addPathsToComponents(results, swagger.jsSpec);
    }
 
    if (jsonOutput) {
      printJson(results, originalFile, verbose, errorsOnly);
    } else {
      if (results.error || results.warning || results.info || results.hint) {
        print(
          results,
          chalk,
          printValidators,
          verbose,
          reportingStats,
          originalFile,
          errorsOnly
        );
      } else {
        console.log(chalk.green(`\n${validFile} passed the validator`));
        Eif (validFile === last(filesToValidate)) console.log();
      }
    }
  }
 
  return exitCode;
};
 
// if the error has a message property (it should),
// this is the cleanest way to present it. If not,
// print the whole error
function getError(err) {
  return err.message || err;
}
 
// this exports the entire program so it can be used or tested
module.exports = processInput;