-
-
Notifications
You must be signed in to change notification settings - Fork 241
/
linter.ts
64 lines (52 loc) · 2.24 KB
/
linter.ts
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
/* eslint-disable no-console */
import { Document, IRuleResult, Spectral } from '@stoplight/spectral-core';
import { readParsable, IFileReadOptions } from '@stoplight/spectral-runtime';
import * as Parsers from '@stoplight/spectral-parsers';
import { getRuleset, listFiles, segregateEntriesPerKind, readFileDescriptor } from './utils';
import { getResolver } from './utils/getResolver';
import { ILintConfig } from '../config';
import { CLIError } from '../../errors';
export async function lint(documents: Array<number | string>, flags: ILintConfig): Promise<IRuleResult[]> {
const spectral = new Spectral({
resolver: getResolver(flags.resolver),
});
const ruleset = await getRuleset(flags.ruleset);
spectral.setRuleset(ruleset);
if (flags.verbose === true) {
const rules = Object.values(ruleset.rules);
console.info(`Found ${rules.length} rules (${rules.filter(rule => rule.enabled).length} enabled)`);
}
const [globs, fileDescriptors] = segregateEntriesPerKind(documents);
const [targetUris, unmatchedPatterns] = await listFiles(globs, !flags.failOnUnmatchedGlobs);
const results: IRuleResult[] = [];
if (unmatchedPatterns.length > 0) {
if (flags.failOnUnmatchedGlobs) {
throw new CLIError(`Unmatched glob patterns: \`${unmatchedPatterns.join(',')}\``);
}
for (const unmatchedPattern of unmatchedPatterns) {
console.log(`Glob pattern \`${unmatchedPattern}\` did not match any files`);
}
}
for (const targetUri of [...targetUris, ...fileDescriptors]) {
if (flags.verbose === true) {
console.info(`Linting ${targetUri}`);
}
const document = await createDocument(targetUri, { encoding: flags.encoding }, flags.stdinFilepath ?? '<STDIN>');
results.push(
...(await spectral.run(document, {
ignoreUnknownFormat: flags.ignoreUnknownFormat,
})),
);
}
return results;
}
const createDocument = async (
identifier: string | number,
opts: IFileReadOptions,
source: string,
): Promise<Document<unknown, Parsers.YamlParserResult<unknown>>> => {
if (typeof identifier === 'string') {
return new Document(await readParsable(identifier, opts), Parsers.Yaml, identifier);
}
return new Document(await readFileDescriptor(identifier, opts), Parsers.Yaml, source);
};