This repository was archived by the owner on May 12, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathparseFile.ts
More file actions
107 lines (95 loc) · 2.17 KB
/
parseFile.ts
File metadata and controls
107 lines (95 loc) · 2.17 KB
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
import fs from 'fs';
import path from 'path';
import jsYaml from 'js-yaml';
import parseComments, { stringify } from 'comment-parser';
import commentsToOpenApi from './commentsToOpenApi';
import { OpenApiObject } from '../exported';
import yamlLOC from './yamlLOC';
const ALLOWED_KEYS = [
'openapi',
'info',
'servers',
'security',
'tags',
'externalDocs',
'components',
'paths',
];
function parseFile(
file: string,
linter: any,
verbose?: boolean
): { parsedFile: { spec: OpenApiObject; loc: number }[]; messages: any[] } {
const fileContent = fs.readFileSync(file, { encoding: 'utf8' });
const ext = path.extname(file);
if (ext === '.yaml' || ext === '.yml') {
try {
const spec = jsYaml.safeLoad(fileContent);
const invalidKeys = Object.keys(spec).filter(
(key) => !ALLOWED_KEYS.includes(key)
);
let messages: any = [];
if (invalidKeys.length > 0) {
invalidKeys.forEach((key) => {
messages.push({
severity: 1,
message: `unexpected key '${key}'`,
line: 0,
column: 0,
});
delete spec[key];
});
}
if (Object.keys(spec).find((key) => ALLOWED_KEYS.includes(key))) {
const loc = yamlLOC(fileContent);
return {
parsedFile: [{ spec: spec, loc: loc }],
messages: messages,
};
}
return { parsedFile: [], messages: messages };
} catch (e) {
if(!e.mark) {
return {
parsedFile: [],
messages: [
{
severity: 1,
message: `cannot parse yaml ${file}, skipping file.`,
line: 0,
column: 0
},
],
};
}
return {
parsedFile: [],
messages: [
{
severity: 2,
message: e.reason,
line: e.mark.line + 1, // eslint indexed by 1 for line.
column: e.mark.column,
},
],
};
}
} else {
const jsDocComments = parseComments(fileContent);
const rawCommentString = jsDocComments.reduce((acc, c) => {
acc += '\n' + stringify([c]);
return acc;
}, '');
const messages = linter.verify(rawCommentString, {
rules: {
warnings: 'warn',
errors: 'error',
},
});
return {
parsedFile: commentsToOpenApi(fileContent, verbose),
messages: messages,
};
}
}
export default parseFile;