openapispectral

How to output effective spectral ruleset?


When using the Spectral linter I can create a custom ruleset which extends existing ready to use rulesets.

For example, I can create the following ruleset:

extends:
  - [spectral:oas, recommended]
  - ./customRules.yml

rules:
  contact-properties: off
  operation-singular-tag: off

This extends the existing "spectral:oas" ruleset and a custom ruleset. Additionally, it turns off a couple of the rules.

My question is, how can I now output which rules are effectively active in the final ruleset?


Solution

  • By using the spectral JS library it is possible to list the resulting rules with a small JavaScript code.

    import * as fs from "node:fs";
    import { fileURLToPath } from "node:url";
    import * as path from "node:path";
    import { join } from "path";
    import { bundleAndLoadRuleset } from "@stoplight/spectral-ruleset-bundler/with-loader";
    import spectralCore from "@stoplight/spectral-core";
    const { Spectral } = spectralCore;
    import spectralRuntime from "@stoplight/spectral-runtime";
    const { fetch } = spectralRuntime;
    
    const rulesetPath =  join(
      path.dirname(fileURLToPath(import.meta.url)),
      "myRuleSet.yaml"
    );
    
    
    const spectral = new Spectral();
    
    spectral.setRuleset(await bundleAndLoadRuleset(rulesetPath, { fs, fetch }));
    
    const rules = spectral.ruleset.rules;
    
    // Iterate over the rules:
    for (const [ruleName, rule] of Object.entries(rules)) {
      console.log(`Rule name: ${ruleName}`);
      
      console.log('Rule message: ', rule.message);
      console.log('Rule description: ', rule.description);
      console.log('Is active: ', rule.enabled);
      console.log('Rule severity: ', rule.severity);
    }
    

    It uses the bundleAndLoadRuleset method to load the ruleset. Then we can iterate the spectra.ruleset.rules object to get information about the resolved rules.

    I have tested the previous script with the following versions of the spectral libraries:

     "@stoplight/spectral-ruleset-bundler": "^1.6.3",
     "@stoplight/spectral-rulesets": "^1.22.0",
    

    and ran the script in node v22.16.0.

    The script is based on the example from Stoplight Documentation