Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: arrayish given #799

Merged
merged 3 commits into from
Nov 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ root = true
[*]
charset = utf-8

[*.{ts,js,yaml}]
[*.{ts,js,yaml,scenario}]
indent_style = space
indent_size = 2

Expand Down
8 changes: 7 additions & 1 deletion docs/getting-started/rulesets.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,15 @@ Now all the rules in this ruleset will only be applied if the specified format i

Custom formats can be registered via the [JS API](../guides/javascript.md), but the CLI is limited to using the predefined ones.

## Given

The `given` keyword is, besides `then`, the only required property on each rule definition.
It can be any valid JSONPath expression or an array of JSONPath expressions.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@P0lip Nit: From a reader's perspective, it's not very clear if, for the rule to pass, all the expressions have to satisfy the expectation or at least one of them.

[JSONPath Online Evaluator](http://jsonpath.com/) is a helpful tool to determine what `given` path you want.

## Severity

The `severity` keyword is optional and can be `error`, `warn`, `info`, or `hint`.
The `severity` keyword is optional and can be `error`, `warn`, `info`, or `hint`. The default value is `warn`.

## Then

Expand Down
20 changes: 20 additions & 0 deletions src/__tests__/linter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,26 @@ responses:: !!foo
expect(fakeLintingFunction.mock.calls[0][2].given).toEqual(['responses']);
expect(fakeLintingFunction.mock.calls[0][3].given).toEqual(target.responses);
});

test('given array of paths, should pass each given path through to lint function', async () => {
spectral.setRules({
example: {
message: '',
given: ['$.responses', '$..200'],
then: {
function: fnName,
},
},
});

await spectral.run(target);

expect(fakeLintingFunction).toHaveBeenCalledTimes(2);
expect(fakeLintingFunction.mock.calls[0][2].given).toEqual(['responses']);
expect(fakeLintingFunction.mock.calls[0][3].given).toEqual(target.responses);
expect(fakeLintingFunction.mock.calls[1][2].given).toEqual(['responses', '200']);
expect(fakeLintingFunction.mock.calls[1][3].given).toEqual(target.responses['200']);
});
});

describe('when given path is not set', () => {
Expand Down
6 changes: 3 additions & 3 deletions src/linter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const lintNode = (
});
}

let results: IRuleResult[] = [];
const results: IRuleResult[] = [];

for (const target of targets) {
const targetPath = givenPath.concat(target.path);
Expand All @@ -88,8 +88,8 @@ export const lintNode = (
},
) || [];

results = results.concat(
targetResults.map<IRuleResult>(result => {
results.push(
...targetResults.map<IRuleResult>(result => {
const escapedJsonPath = (result.path || targetPath).map(segment => decodePointerFragment(String(segment)));
const path = getClosestJsonPath(
rule.resolved === false ? resolved.unresolved : resolved.resolved,
Expand Down
12 changes: 11 additions & 1 deletion src/meta/rule.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,17 @@
"type": "boolean"
},
"given": {
"type": "string"
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
},
"resolved": {
"type": "boolean"
Expand Down
88 changes: 53 additions & 35 deletions src/runner.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Resolved } from './resolved';

const { JSONPath } = require('jsonpath-plus');

import { lintNode } from './linter';
import { Resolved } from './resolved';
import { getDiagnosticSeverity } from './rulesets/severity';
import { FunctionCollection, IGivenNode, IRule, IRuleResult, IRunRule, RunRuleCollection } from './types';
import { hasIntersectingElement } from './utils/';
Expand All @@ -26,8 +25,9 @@ export const runRules = (
rule.formats !== void 0 &&
(resolved.formats === null ||
(resolved.formats !== void 0 && !hasIntersectingElement(rule.formats, resolved.formats)))
)
) {
continue;
}

if (!isRuleEnabled(rule)) {
continue;
Expand All @@ -47,48 +47,66 @@ const runRule = (resolved: Resolved, rule: IRunRule, functions: FunctionCollecti
const target = rule.resolved === false ? resolved.unresolved : resolved.resolved;

const results: IRuleResult[] = [];
const nodes: IGivenNode[] = [];

// don't have to spend time running jsonpath if given is $ - can just use the root object
if (rule.given && rule.given !== '$') {
try {
for (const given of Array.isArray(rule.given) ? rule.given : [rule.given]) {
// don't have to spend time running jsonpath if given is $ - can just use the root object
if (given === '$') {
lint(
{
path: ['$'],
value: target,
},
resolved,
rule,
functions,
results,
);
} else {
JSONPath({
path: rule.given,
path: given,
json: target,
resultType: 'all',
callback: (result: any) => {
nodes.push({
path: JSONPath.toPathArray(result.path),
value: result.value,
});
lint(
{
path: JSONPath.toPathArray(result.path),
value: result.value,
},
resolved,
rule,
functions,
results,
);
},
});
} catch (e) {
console.error(e);
}
} else {
nodes.push({
path: ['$'],
value: target,
});
}

for (const node of nodes) {
try {
const thens = Array.isArray(rule.then) ? rule.then : [rule.then];
for (const then of thens) {
const func = functions[then.function];
if (!func) {
console.warn(`Function ${then.function} not found. Called by rule ${rule.name}.`);
continue;
}

results.push(...lintNode(node, rule, then, func, resolved));
return results;
};

function lint(
node: IGivenNode,
resolved: Resolved,
rule: IRunRule,
functions: FunctionCollection,
results: IRuleResult[],
): void {
try {
for (const then of Array.isArray(rule.then) ? rule.then : [rule.then]) {
const func = functions[then.function];
if (!func) {
console.warn(`Function ${then.function} not found. Called by rule ${rule.name}.`);
continue;
}

const validationResults = lintNode(node, rule, then, func, resolved);

if (validationResults.length > 0) {
results.push(...validationResults);
}
} catch (e) {
console.warn(`Encountered error when running rule '${rule.name}' on node at path '${node.path}':\n${e}`);
}
} catch (e) {
console.warn(`Encountered error when running rule '${rule.name}' on node at path '${node.path}':\n${e}`);
}

return results;
};
}
2 changes: 1 addition & 1 deletion src/types/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export interface IRule<T = string, O = any> {
recommended?: boolean;

// Filter the target down to a subset[] with a JSON path
given: string;
given: string | string[];

// If false, rule will operate on original (unresolved) data
// If undefined or true, resolved data will be supplied
Expand Down
40 changes: 40 additions & 0 deletions test-harness/scenarios/rules-matching-multiple-places.scenario
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
====test====
Rules matching multiple properties in the document
====document====
schemas:
user:
type: object
properties:
name:
type: number
age:
type: number
occupation:
type: boolean
address:
====command====
{bin} lint {document} -r {asset:ruleset}
====asset:ruleset====
rules:
valid-user-properties:
severity: error
given: [$.schemas.user.properties.name, $.schemas.user.properties.occupation]
then:
field: type
function: pattern
functionOptions:
match: /^string$/
require-user-and-address:
severity: error
given: [$.schemas.user, $.schemas.address]
then:
function: truthy
====status====
1
====stdout====
{document}
6:15 error valid-user-properties must match the pattern '/^string$/'
10:15 error valid-user-properties must match the pattern '/^string$/'
11:11 error require-user-and-address schemas.address is not truthy

✖ 3 problems (3 errors, 0 warnings, 0 infos, 0 hints)