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

92.27% Statements 179/194
89.74% Branches 70/78
89.47% Functions 17/19
92.23% Lines 178/193

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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 41929x 29x 29x 29x 29x 29x   29x     29x 29x   29x 29x 29x   29x 10x       10x     10x 12x           10x 10x       29x 16x 16x   16x   16x 16x 16x   19x 1x   18x 1x 1x       1x       17x 17x 17x 32x 1x 1x       1x       31x 31x 31x 80x         2x       2x   2x     2x 2x 2x 78x 1x 1x       1x       77x 77x       77x 77x 77x   77x 12x 12x 12x 12x 1x 1x 1x       1x     12x 65x   1x   1x 1x         77x 4x 4x                     16x 7x 7x 33x 23x   33x 33x 33x 98x 77x   98x 98x 98x 336x 277x           7x     9x   9x     16x     29x     88x         88x 1x 1x   87x             88x       88x 1x               1x 1x     88x 87x   1x 1x 1x                   1x 1x         88x     29x     52x     52x                                                       29x 49x 49x   49x 5x   2x 2x               3x   1x 1x                 49x 1x       49x 49x 47x       49x     29x 50x   50x     50x 4x 4x   46x         50x   50x 4x 4x 4x       1x 1x 1x           49x   49x     29x 1x     1x 1x 1x       1x       1x 1x 1x 1x     1x     29x   90x         90x 5x         90x 90x 275x 260x                 90x 85x     90x     29x 29x 29x 29x 29x 29x 29x  
const fs = require('fs');
const util = require('util');
const path = require('path');
const globby = require('globby');
const findUp = require('find-up');
const printError = require('./printError');
 
const defaultConfig = require('../../.defaultsForValidator');
 
// global objects
const readFile = util.promisify(fs.readFile);
const defaultObject = defaultConfig.defaults;
// Clear spectral rules from defaultObject, only use the explicit values in the validaterc file
defaultObject.spectral.rules = {};
const deprecatedRuleObject = defaultConfig.deprecated;
const configOptions = defaultConfig.options;
 
const printConfigErrors = function(problems, chalk, fileName) {
  const description = `Invalid configuration in ${chalk.underline(
    fileName
  )} file. See below for details.`;
 
  const message = [];
 
  // add all errors for printError
  problems.forEach(function(problem) {
    message.push(
      `\n - ${chalk.red(problem.message)}\n   ${chalk.magenta(
        problem.correction
      )}`
    );
  });
  Eif (message.length) {
    printError(chalk, description, message.join('\n'));
  }
};
 
const validateConfigObject = function(configObject, chalk) {
  const configErrors = [];
  let validObject = true;
 
  const deprecatedRules = Object.keys(deprecatedRuleObject);
 
  const allowedSpecs = Object.keys(defaultObject);
  const userSpecs = Object.keys(configObject);
  userSpecs.forEach(spec => {
    // Do not check "spectral" spec rules
    if (spec === 'spectral') {
      return;
    }
    if (!allowedSpecs.includes(spec)) {
      validObject = false;
      configErrors.push({
        message: `'${spec}' is not a valid spec.`,
        correction: `Valid specs are: ${allowedSpecs.join(', ')}`
      });
      return; // skip rules for categories for invalid spec
    }
 
    // check that all categories are valid
    const allowedCategories = Object.keys(defaultObject[spec]);
    const userCategories = Object.keys(configObject[spec]);
    userCategories.forEach(category => {
      if (!allowedCategories.includes(category)) {
        validObject = false;
        configErrors.push({
          message: `'${category}' is not a valid category.`,
          correction: `Valid categories are: ${allowedCategories.join(', ')}`
        });
        return; // skip rules for invalid category
      }
 
      // check that all rules are valid
      const allowedRules = Object.keys(defaultObject[spec][category]);
      const userRules = Object.keys(configObject[spec][category]);
      userRules.forEach(rule => {
        if (
          deprecatedRules.includes(rule) ||
          // account for rules with same name in different categories
          deprecatedRules.includes(`${category}.${rule}`)
        ) {
          const oldRule = deprecatedRules.includes(rule)
            ? rule
            : `${category}.${rule}`;
 
          const newRule = deprecatedRuleObject[oldRule];
          const message =
            newRule === ''
              ? `The rule '${oldRule}' has been deprecated. It will not be checked.`
              : `The rule '${oldRule}' has been deprecated. It will not be checked. Use '${newRule}' instead.`;
          console.log('\n' + chalk.yellow('[Warning] ') + message);
          delete configObject[spec][category][rule];
          return;
        } else if (!allowedRules.includes(rule)) {
          validObject = false;
          configErrors.push({
            message: `'${rule}' is not a valid rule for the ${category} category`,
            correction: `Valid rules are: ${allowedRules.join(', ')}`
          });
          return; // skip statuses for invalid rule
        }
 
        // check that all statuses are valid (either 'error', 'warning', 'info', 'hint' or 'off')
        const allowedStatusValues = ['error', 'warning', 'info', 'hint', 'off'];
        let userStatus = configObject[spec][category][rule];
 
        // if the rule supports an array in configuration,
        // it will be an array in the defaults object
        const defaultStatus = defaultObject[spec][category][rule];
        const ruleTakesArray = Array.isArray(defaultStatus);
        const userGaveArray = Array.isArray(userStatus);
 
        if (ruleTakesArray) {
          const userStatusArray = userGaveArray ? userStatus : [userStatus];
          userStatus = userStatusArray[0] || '';
          const configOption = userStatusArray[1] || defaultStatus[1];
          if (configOption !== defaultStatus[1]) {
            const result = validateConfigOption(configOption, defaultStatus[1]);
            Eif (!result.valid) {
              configErrors.push({
                message: `'${configOption}' is not a valid option for the ${rule} rule in the ${category} category.`,
                correction: `Valid options are: ${result.options.join(', ')}`
              });
              validObject = false;
            }
          }
          configObject[spec][category][rule] = [userStatus, configOption];
        } else if (userGaveArray) {
          // user should not have given an array
          validObject = false;
          // dont throw two errors
          userStatus = 'off';
          configErrors.push({
            message: `Array-value configuration options are not supported for the ${rule} rule in the ${category} category.`,
            correction: `Valid statuses are: ${allowedStatusValues.join(', ')}`
          });
        }
        if (!allowedStatusValues.includes(userStatus)) {
          validObject = false;
          configErrors.push({
            message: `'${userStatus}' is not a valid status for the ${rule} rule in the ${category} category.`,
            correction: `Valid statuses are: ${allowedStatusValues.join(', ')}`
          });
        }
      });
    });
  });
 
  // if the object is valid, resolve any missing features
  //   and set all missing statuses to their default value
  if (validObject) {
    const requiredSpecs = allowedSpecs;
    requiredSpecs.forEach(spec => {
      if (!userSpecs.includes(spec)) {
        configObject[spec] = {};
      }
      const requiredCategories = Object.keys(defaultObject[spec]);
      const userCategories = Object.keys(configObject[spec]);
      requiredCategories.forEach(category => {
        if (!userCategories.includes(category)) {
          configObject[spec][category] = {};
        }
        const requiredRules = Object.keys(defaultObject[spec][category]);
        const userRules = Object.keys(configObject[spec][category]);
        requiredRules.forEach(rule => {
          if (!userRules.includes(rule)) {
            configObject[spec][category][rule] =
              defaultObject[spec][category][rule];
          }
        });
      });
    });
    configObject.invalid = false;
  } else {
    // if the object is not valid, exit and tell the user why
    printConfigErrors(configErrors, chalk, '.validaterc');
 
    configObject.invalid = true;
  }
 
  return configObject;
};
 
const getConfigObject = async function(defaultMode, chalk, configFileOverride) {
  let configObject;
 
  const findUpOpts = {};
  let configFileName;
 
  // You cannot pass a full path into findUp as a file name, you must split the
  // path or else findUp redudantly prepends the path to the result.
  if (configFileOverride) {
    configFileName = path.basename(configFileOverride);
    findUpOpts.cwd = path.dirname(configFileOverride);
  } else {
    configFileName = '.validaterc';
  }
 
  // search up the file system for the first instance
  // of '.validaterc' or,
  // if a config file override is passed in, use find-up
  // to verify existence of the file
  const configFile = await findUp(configFileName, findUpOpts);
 
  // if the user does not have a config file, run in default mode and warn them
  // (findUp returns null if it does not find a file)
  if (configFile === null && !defaultMode) {
    console.log(
      '\n' +
        chalk.yellow('[Warning]') +
        ` No ${chalk.underline(
          '.validaterc'
        )} file found. The validator will run in ` +
        chalk.bold.cyan('default mode.')
    );
    console.log(`To configure the validator, create a .validaterc file.`);
    defaultMode = true;
  }
 
  if (defaultMode) {
    configObject = defaultObject;
  } else {
    try {
      const fileAsString = await readFile(configFile, 'utf8');
      configObject = JSON.parse(fileAsString);
    } catch (err) {
      // this most likely means there is a problem in the json syntax itself
      const description =
        'There is a problem with the .validaterc file. See below for details.';
      printError(chalk, description, err);
      return Promise.reject(2);
    }
 
    // validate the user object
    configObject = validateConfigObject(configObject, chalk);
    Iif (configObject.invalid) {
      return Promise.reject(2);
    }
  }
 
  return configObject;
};
 
const getFilesToIgnore = async function() {
  // search up the file system for the first instance
  // of the ignore file
  const ignoreFile = await findUp('.validateignore');
 
  // if file does not exist, thats fine. it is optional
  Eif (ignoreFile === null) return [];
 
  const pathToFile = `${path.dirname(ignoreFile)}/`;
 
  let filesToIgnore;
  try {
    const fileAsString = await readFile(ignoreFile, 'utf8');
 
    // convert each glob in ignore file to an absolute path.
    // globby takes args relative to the process cwd, but we
    // want these to stay relative to project root
    // also, ignore any blank lines
    const globsToIgnore = fileAsString
      .split('\n')
      .filter(line => line.trim().length !== 0)
      .map(glob => pathToFile + glob);
 
    filesToIgnore = await globby(globsToIgnore, {
      expandDirectories: true,
      dot: true
    });
  } catch (err) {
    filesToIgnore = [];
  }
 
  return filesToIgnore;
};
 
const validateLimits = function(limitsObject, chalk) {
  const allowedLimits = ['warnings'];
  const limitErrors = [];
 
  Object.keys(limitsObject).forEach(function(key) {
    if (!allowedLimits.includes(key)) {
      // remove the entry and notify the user
      delete limitsObject[key];
      limitErrors.push({
        message: `"${key}" limit not supported. This value will be ignored.`,
        correction: `Valid limits for .thresholdrc are: ${allowedLimits.join(
          ', '
        )}.`
      });
    } else {
      // valid limit option, ensure the limit given is a number
      if (typeof limitsObject[key] !== 'number') {
        // remove the entry and notify the user
        delete limitsObject[key];
        limitErrors.push({
          message: `Value provided for ${key} limit is invalid.`,
          correction: `${key} limit should be a number.`
        });
      }
    }
  });
 
  // give the user corrections for .thresholdrc file
  if (limitErrors.length) {
    printConfigErrors(limitErrors, chalk, '.thresholdrc');
  }
 
  //  sets all limits options not defined by user to default
  for (const limitOption of allowedLimits) {
    if (!(limitOption in limitsObject)) {
      limitsObject[limitOption] = Number.MAX_VALUE;
    }
  }
 
  return limitsObject;
};
 
const getLimits = async function(chalk, limitsFileOverride) {
  let limitsObject = {};
 
  const findUpOpts = {};
  let limitsFileName;
 
  if (limitsFileOverride) {
    limitsFileName = path.basename(limitsFileOverride);
    findUpOpts.cwd = path.dirname(limitsFileOverride);
  } else {
    limitsFileName = '.thresholdrc';
  }
 
  // search up the file system for the first instance
  // of the threshold file
  const limitsFile = await findUp(limitsFileName, findUpOpts);
 
  if (limitsFile !== null) {
    try {
      const fileAsString = await readFile(limitsFile, 'utf8');
      limitsObject = JSON.parse(fileAsString);
    } catch (err) {
      // this most likely means there is a problem in the json syntax itself
      const description =
        'There is a problem with the .thresholdrc file. See below for details.';
      printError(chalk, description, err);
      return Promise.reject(2);
    }
  }
 
  // returns complete limits object with all valid user settings
  // and default values for undefined limits
  limitsObject = validateLimits(limitsObject, chalk);
 
  return limitsObject;
};
 
const validateConfigOption = function(userOption, defaultOption) {
  const result = { valid: true };
  // determine what type of option it is
  let optionType;
  Object.keys(configOptions).forEach(option => {
    Eif (configOptions[option].includes(defaultOption)) {
      optionType = option;
    }
  });
  // if optionType doesn't match, there are no predefined options for this rule
  Iif (!optionType) {
    return result;
  }
  // verify the given option is valid
  const validOptions = configOptions[optionType];
  Eif (!validOptions.includes(userOption)) {
    result.valid = false;
    result.options = validOptions;
  }
 
  return result;
};
 
const getSpectralRuleset = async function(rulesetFileOverride, defaultRuleset) {
  // List of ruleset files to search for
  const ruleSetFilesToFind = [
    '.spectral.yaml',
    '.spectral.yml',
    '.spectral.json'
  ];
  if (rulesetFileOverride) {
    ruleSetFilesToFind.splice(0, 0, rulesetFileOverride);
  }
  let ruleSetFile;
 
  // search up the file system for the first ruleset file found
  try {
    for (const file of ruleSetFilesToFind) {
      if (!ruleSetFile) {
        ruleSetFile = await findUp(file);
      }
    }
  } catch {
    // if there's any issue finding a custom ruleset, then
    // just use the default
    ruleSetFile = defaultRuleset;
  }
 
  if (!ruleSetFile) {
    ruleSetFile = defaultRuleset;
  }
 
  return ruleSetFile;
};
 
module.exports.get = getConfigObject;
module.exports.validate = validateConfigObject;
module.exports.ignore = getFilesToIgnore;
module.exports.validateOption = validateConfigOption;
module.exports.validateLimits = validateLimits;
module.exports.limits = getLimits;
module.exports.getSpectralRuleset = getSpectralRuleset;