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

refactor: introduce Document #876

Merged
merged 5 commits into from
Jan 11, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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
14 changes: 5 additions & 9 deletions docs/guides/javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,18 @@ Assuming it has been installed as a Node module via NPM/Yarn, it can be used to
## Linting a YAML string

```js
const { Spectral } = require('@stoplight/spectral');
const { getLocationForJsonPath, parseWithPointers } = require("@stoplight/yaml");
const { Spectral, Document, Parsers } = require('@stoplight/spectral');

const myOpenApiDocument = parseWithPointers(`responses:
const myOpenApiDocument = new Document(`responses:
'200':
description: ''
schema:
$ref: '#/definitions/error-response'
`);
`, Parsers.Yaml);

const spectral = new Spectral();
spectral
.run({
parsed: myOpenApiDocument,
getLocationForJsonPath,
})
.run(myOpenApiDocument)
.then(console.log);
```

Expand All @@ -33,7 +29,7 @@ Find out how to add formats, rules and functions below.

## Linting an Object

Instead of passing a string to `parseWithPointers`, you can pass in JavaScript object, with or without `$ref`'s.
Instead of passing a string to `Document`, you can pass in JavaScript object, with or without `$ref`'s.

```js
const { Spectral } = require('@stoplight/spectral');
Expand Down
43 changes: 43 additions & 0 deletions src/__tests__/document.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { IParsedResult, isParsedResult } from '../document';

describe('isParsedResult util', () => {
test('correctly identifies objects that fulfill the IParsedResult interface', () => {
// @ts-ignore
expect(isParsedResult()).toBe(false);

expect(isParsedResult('')).toBe(false);
expect(isParsedResult([])).toBe(false);
expect(isParsedResult({})).toBe(false);
expect(
isParsedResult({
parsed: undefined,
}),
).toBe(false);

expect(
isParsedResult({
parsed: [],
}),
).toBe(false);

expect(
isParsedResult({
parsed: {
data: {},
},
}),
).toBe(false);

const obj: IParsedResult = {
getLocationForJsonPath: jest.fn(),
parsed: {
data: {},
ast: {},
lineMap: [],
diagnostics: [],
},
};

expect(isParsedResult(obj)).toBe(true);
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { cloneDeep } from 'lodash';
import { formatParserDiagnostics } from '../error-messages';
import { formatParserDiagnostics } from '../errorMessages';

describe('Error messages', () => {
describe('parser diagnostics', () => {
Expand Down Expand Up @@ -68,7 +68,7 @@ describe('Error messages', () => {
},
];

expect(formatParserDiagnostics(cloneDeep(diagnostics))).toEqual([
expect(formatParserDiagnostics(cloneDeep(diagnostics), null)).toEqual([
{
...diagnostics[0],
path: ['test'],
Expand Down Expand Up @@ -145,7 +145,7 @@ describe('Error messages', () => {
},
];

expect(formatParserDiagnostics(cloneDeep(diagnostics))).toEqual([
expect(formatParserDiagnostics(cloneDeep(diagnostics), null)).toEqual([
{
...diagnostics[0],
path: [],
Expand Down
9 changes: 1 addition & 8 deletions src/__tests__/linter.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { getLocationForJsonPath, parseWithPointers } from '@stoplight/json';
import { Resolver } from '@stoplight/json-ref-resolver';
import { DiagnosticSeverity } from '@stoplight/types';
import { parse } from '@stoplight/yaml';
Expand Down Expand Up @@ -705,13 +704,7 @@ responses:: !!foo

describe('reports duplicated properties for', () => {
test('JSON format', async () => {
const result = await spectral.run(
{
parsed: parseWithPointers('{"foo":true,"foo":false}', { ignoreDuplicateKeys: false }),
getLocationForJsonPath,
},
{ ignoreUnknownFormat: true },
);
const result = await spectral.run('{"foo":true,"foo":false}', { ignoreUnknownFormat: true });

expect(result).toEqual([
{
Expand Down
19 changes: 7 additions & 12 deletions src/__tests__/spectral.jest.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { getLocationForJsonPath, parseWithPointers } from '@stoplight/json';
import { normalize } from '@stoplight/path';
import { DiagnosticSeverity, Dictionary } from '@stoplight/types';
import * as fs from 'fs';
import * as nock from 'nock';
import * as path from 'path';

import { Document } from '../document';
import { isOpenApiv2 } from '../formats';
import * as Parsers from '../parsers';
import { httpAndFileResolver } from '../resolvers/http-and-file';
import { IRunRule, Spectral } from '../spectral';

Expand Down Expand Up @@ -98,21 +101,13 @@ describe('Spectral', () => {
});

test('should report issues for correct files with correct ranges and paths', async () => {
const documentUri = path.join(__dirname, './__fixtures__/document-with-external-refs.oas2.json');
const documentUri = normalize(path.join(__dirname, './__fixtures__/document-with-external-refs.oas2.json'));
const spectral = new Spectral({ resolver: httpAndFileResolver });
await spectral.loadRuleset('spectral:oas');
spectral.registerFormat('oas2', isOpenApiv2);
const parsed = {
parsed: parseWithPointers(fs.readFileSync(documentUri, 'utf8')),
getLocationForJsonPath,
source: documentUri,
};
const document = new Document(fs.readFileSync(documentUri, 'utf8'), Parsers.Json, documentUri);

const results = await spectral.run(parsed, {
resolve: {
documentUri,
},
});
const results = await spectral.run(document);

expect(results).toEqual(
expect.arrayContaining([
Expand Down
106 changes: 31 additions & 75 deletions src/__tests__/spectral.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { getLocationForJsonPath, parseWithPointers } from '@stoplight/json';
import { IGraphNodeData } from '@stoplight/json-ref-resolver/types';
import { DiagnosticSeverity, Dictionary } from '@stoplight/types';
import { DepGraph } from 'dependency-graph';
import { isParsedResult, Spectral } from '../spectral';
import { IParsedResult, IResolver, IRunRule, RuleFunction } from '../types';
import { merge } from 'lodash';

const merge = require('lodash/merge');
import { Document } from '../document';
import * as Parsers from '../parsers';
import { Spectral } from '../spectral';
import { IResolver, IRunRule, RuleFunction } from '../types';

const oasRuleset = JSON.parse(JSON.stringify(require('../rulesets/oas/index.json')));
const oasRulesetRules: Dictionary<IRunRule, string> = oasRuleset.rules;
Expand Down Expand Up @@ -175,11 +176,7 @@ describe('spectral', () => {
},
});

const target: IParsedResult = {
parsed: parseWithPointers(`{"foo":"bar"}`),
getLocationForJsonPath,
source: 'foo',
};
const target = new Document(`{"foo":"bar"}`, Parsers.Json, 'foo');

return expect(s.run(target)).resolves.toStrictEqual([
{
Expand All @@ -206,39 +203,37 @@ describe('spectral', () => {
const s = new Spectral();
const source = 'foo.yaml';

const parsedResult: IParsedResult = {
getLocationForJsonPath,
source,
parsed: parseWithPointers(
JSON.stringify(
{
paths: {
'/agreements': {
get: {
description: 'Get some Agreements',
responses: {
'200': {
$ref: '#/responses/GetAgreementsOk',
},
default: {},
const document = new Document(
JSON.stringify(
{
paths: {
'/agreements': {
get: {
description: 'Get some Agreements',
responses: {
'200': {
$ref: '#/responses/GetAgreementsOk',
},
summary: 'List agreements',
tags: ['agreements', 'pagination'],
default: {},
},
summary: 'List agreements',
tags: ['agreements', 'pagination'],
},
},
responses: {
GetAgreementsOk: {
description: 'Successful operation',
headers: {},
},
},
responses: {
GetAgreementsOk: {
description: 'Successful operation',
headers: {},
},
},
null,
2,
),
},
null,
2,
),
};
Parsers.Json,
source,
);

s.setRules({
'pagination-responses-have-x-next-token': {
Expand All @@ -250,7 +245,7 @@ describe('spectral', () => {
},
});

return expect(s.run(parsedResult, { resolve: { documentUri: source } })).resolves.toEqual([
return expect(s.run(document)).resolves.toEqual([
{
code: 'pagination-responses-have-x-next-token',
message: 'All collection endpoints have the X-Next-Token parameter in responses',
Expand All @@ -263,43 +258,4 @@ describe('spectral', () => {
});
});
});

test('isParsedResult correctly identifies objects that fulfill the IParsedResult interface', () => {
// @ts-ignore
expect(isParsedResult()).toBe(false);

expect(isParsedResult('')).toBe(false);
expect(isParsedResult([])).toBe(false);
expect(isParsedResult({})).toBe(false);
expect(
isParsedResult({
parsed: undefined,
}),
).toBe(false);

expect(
isParsedResult({
parsed: [],
}),
).toBe(false);

expect(
isParsedResult({
parsed: {
data: {},
},
}),
).toBe(false);

const obj: IParsedResult = {
getLocationForJsonPath: jest.fn(),
parsed: {
data: {},
ast: {},
lineMap: [],
diagnostics: [],
},
};
expect(isParsedResult(obj)).toBe(true);
});
});
22 changes: 9 additions & 13 deletions src/cli/services/linter/linter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { IParserResult } from '@stoplight/types';
import { getLocationForJsonPath } from '@stoplight/yaml';

import { Document } from '../../../document';
import {
isJSONSchema,
isJSONSchemaDraft2019_09,
Expand All @@ -12,10 +10,10 @@ import {
isOpenApiv3,
} from '../../../formats';
import { readParsable } from '../../../fs/reader';
import { parseYaml } from '../../../parsers';
import * as Parsers from '../../../parsers';
import { isRuleEnabled } from '../../../runner';
import { IRuleResult, Spectral } from '../../../spectral';
import { FormatLookup, IParsedResult } from '../../../types';
import { FormatLookup } from '../../../types';
import { ILintConfig } from '../../../types/config';
import { getRuleset, listFiles, skipRules } from './utils';
import { getResolver } from './utils/getResolver';
Expand Down Expand Up @@ -74,16 +72,14 @@ export async function lint(documents: Array<number | string>, flags: ILintConfig
console.info(`Linting ${targetUri}`);
}

const spec: IParserResult = parseYaml(await readParsable(targetUri, { encoding: flags.encoding }));

const parsedResult: IParsedResult = {
source: typeof targetUri === 'number' ? '<STDIN>' : targetUri,
parsed: spec,
getLocationForJsonPath,
};
const document = new Document(
await readParsable(targetUri, { encoding: flags.encoding }),
Parsers.Yaml,
typeof targetUri === 'number' ? '<STDIN>' : targetUri,
);

results.push(
...(await spectral.run(parsedResult, {
...(await spectral.run(document, {
ignoreUnknownFormat: flags.ignoreUnknownFormat,
resolve: {
documentUri: typeof targetUri === 'number' ? void 0 : targetUri,
Expand Down
Loading