-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli-mode.ts
More file actions
202 lines (192 loc) · 10.4 KB
/
cli-mode.ts
File metadata and controls
202 lines (192 loc) · 10.4 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import * as fs from "node:fs";
import { join } from "path";
import Parsers from "@stoplight/spectral-parsers";
import { Document } from "@stoplight/spectral-core";
import { importAndCreateRuleInstances } from "./util/ruleUtil.ts"; // Import the helper function
import util from 'util';
import {RapLPCustomSpectral} from "./util/RapLPCustomSpectral.ts";
import {DiagnosticReport, RapLPDiagnostic} from "./util/RapLPDiagnostic.ts";
import {AggregateError} from "./util/RapLPCustomErrorInfo.ts";
import chalk from 'chalk';
import { validateYamlInput } from "./util/baseUtil.ts"
import { ExcelReportProcessor } from "./util/excelReportProcessor.ts";
declare var AggregateError: {
prototype: AggregateError;
new(errors: any[], message?: string): AggregateError;
};
const writeFileAsync = util.promisify(fs.writeFile);
const appendFileAsync = util.promisify(fs.appendFile);
export type CliArgs = {
file?: string;
categories?: string;
logError?: string;
append: boolean;
logDiagnostic?: string;
dex?: string
}
export async function execCLI<T extends CliArgs>(argv: T) {
try {
// Parse command-line arguments using yargs
const apiSpecFileName = (argv.file as string) || "";
const ruleCategories = argv.categories ? (argv.categories as string).split(",") : undefined;
const logErrorFilePath = argv.logError as string | undefined;
const logDiagnosticFilePath = argv.logDiagnostic as string | undefined;
try {
const fileContent = fs.readFileSync(apiSpecFileName, "utf-8");
try {
validateYamlInput(fileContent);
} catch (error) {
if (error instanceof Error) {
const cause = error.cause;
switch (cause) {
case 'INVALID_YAML':
console.error('Validation error: The YAML content is invalid or empty. Please provide a valid YAML file.');
break;
case 'MISSING_KEYS':
console.error(`Validation error: ${error.message}. Ensure the file includes required keys like 'openapi', 'info', and 'paths'.`);
break;
case 'SYNTAX_ERROR':
console.error(`Validation error: There is a syntax error in your YAML file. ${error.message}`);
break;
default:
console.error(`Unexpected validation error: ${error.message}`);
}
return;
} else {
console.error('Unknown validation error occurred.');
return;
}
}
// Import and create rule instances in RAP-LP
const enabledRulesAndCategorys = await importAndCreateRuleInstances(ruleCategories);
// Load API specification into a Document object
const apiSpecDocument = new Document(
fs.readFileSync(join(apiSpecFileName), "utf-8").trim(),
Parsers.Yaml,
apiSpecFileName
);
try {
/**
* CustomSpectral
*/
const customSpectral = new RapLPCustomSpectral();
customSpectral.setCategorys(enabledRulesAndCategorys.instanceCategoryMap);
customSpectral.setRuleset(enabledRulesAndCategorys.rules);
const result = await customSpectral.run(apiSpecDocument);
const customDiagnostic = new RapLPDiagnostic();
customDiagnostic.processRuleExecutionInformation(result,enabledRulesAndCategorys.instanceCategoryMap);
const diagnosticReports: DiagnosticReport[] = customDiagnostic.processDiagnosticInformation();
if(argv.dex != null) {
const reportHandler = new ExcelReportProcessor({
outputFilePath: argv.dex,
});
reportHandler.generateReportDocument(diagnosticReports)
}
/**
* Chalk impl.
* @param allvarlighetsgrad
* @returns
*/
// Run Spectral on the API specification and log the result
const colorizeSeverity = (allvarlighetsgrad: string) => {
switch (allvarlighetsgrad) {
case 'ERROR': // Error
return chalk.red('Error');
case 'WARNING': // Warning
return chalk.yellow('Warning');
case 'HINT': // Info
return chalk.greenBright('Hint');
default:
return chalk.white('Info');
}
};
const formatLintingResult = (result: any) => {
return `allvarlighetsgrad: ${colorizeSeverity(result.allvarlighetsgrad)} \nid: ${result.id} \nkrav: ${result.krav} \nområde: ${result.omrade} \nsökväg:[${result.sokvag}] \nomfattning:${JSON.stringify(result.omfattning,null,2)} `;
};
//Check specified option from yargs input
const currentDate = new Date() //.toISOString(); // Get current date and time in ISO format
const formattedDate = `${currentDate.getFullYear()}-${padZero(currentDate.getMonth() + 1)}-${padZero(currentDate.getDate())} ${padZero(currentDate.getHours())}:${padZero(currentDate.getMinutes())}:${padZero(currentDate.getSeconds())}`;
function padZero(num: number): string {
return num < 10 ? `0${num}` : `${num}`;
}
if (logDiagnosticFilePath) {
let allDiagnosticReports = JSON.stringify(diagnosticReports, null, 2);
let logEntry = `${formattedDate}\n${allDiagnosticReports}\n`; // Prepend datestamp to log entry
let utf8EncodedContent = Buffer.from(logEntry, 'utf8');
//Log to disc
await writeFileAsync(logDiagnosticFilePath,utf8EncodedContent);
console.log(chalk.green(`Skriver diagnostiseringsinformation från RAP-LP till ${logDiagnosticFilePath}`));
}else {
//STDOUT
if (customDiagnostic.diagnosticInformation.executedUniqueRules!=undefined &&
customDiagnostic.diagnosticInformation.executedUniqueRules.length>0) {
console.log(chalk.green("<<<Verkställda och godkända regler - RAP-LP>>>\r"));
console.log(chalk.whiteBright("STATUS\tOMRÅDE") + " / " +chalk.whiteBright("IDENTIFIKATIONSNUMMER")) ;
customDiagnostic.diagnosticInformation.executedUniqueRules.forEach(item => {
console.log(chalk.bgGreen("OK") + "\t" + item.omrade + " / " + item.id) ;
});
}
if (customDiagnostic.diagnosticInformation.executedUniqueRulesWithError!=undefined &&
customDiagnostic.diagnosticInformation.executedUniqueRulesWithError.length>0) {
console.log(chalk.green("<<<Verkställda och ej godkända regler - RAP-LP>>>\r"));
console.log(chalk.whiteBright("STATUS\tOMRÅDE") + " / " + chalk.whiteBright("IDENTIFIKATIONSNUMMER")) ;
customDiagnostic.diagnosticInformation.executedUniqueRulesWithError.forEach(item => {
console.log(chalk.bgRed("EJ OK") + "\t" + item.omrade + " / " + item.id) ;
});
}
if (customDiagnostic.diagnosticInformation.notApplicableRules!=undefined &&
customDiagnostic.diagnosticInformation.notApplicableRules.length>0) {
console.log(chalk.grey("<<<Ej tillämpade regler - RAP-LP>>>\r"));
console.log(chalk.whiteBright("STATUS\tOMRÅDE") + " / " + chalk.whiteBright("IDENTIFIKATIONSNUMMER")) ;
customDiagnostic.diagnosticInformation.notApplicableRules.forEach(item => {
console.log(chalk.bgGrey("N/A") + "\t" + item.omrade + "/" + item.id);
});
}
}
if (logErrorFilePath ) {
let content = JSON.stringify(result, null, 2);
let logEntry = `${formattedDate}\n${content}\n`; // Prepend datestamp to log entry
let utf8EncodedContent = Buffer.from(logEntry, 'utf8');
if (argv.append) {
await appendFileAsync(logErrorFilePath,utf8EncodedContent);
console.log(chalk.green(`Skriver inspektion/valideringsinformation från RAP-LP till ${logErrorFilePath}`));
}else {
//Log to disc
await writeFileAsync(logErrorFilePath,utf8EncodedContent);
console.log(chalk.green(`Skriver inspektion/valideringsinformation från RAP-LP till ${logErrorFilePath}`));
}
}else {
//Verbose error logging goes here with detailed result
console.log(chalk.whiteBright('\n<<Regelutfall RAP-LP>> \n'));
result.forEach(item => {
console.log(formatLintingResult(item));
});
}
} catch (spectralError: any) {
logErrorToFile(spectralError); // Log stack
console.error(chalk.red("Ett fel uppstod vid initiering/körning av regelklasser! Undersök felloggen för RAP-LP för mer information om felet"));
}
} catch (initializingError: any) {
logErrorToFile(initializingError);
// console.error(chalk.red(initializingError));
console.error(chalk.red("Ett fel uppstod vid inläsning av moduler och skapande av regelklasser! Undersök felloggen för RAP-LP för mer information om felet"));
}
} catch (error: any) {
logErrorToFile(error);
console.error(chalk.red("Ett oväntat fel uppstod! Undersök felloggen för RAP-LP för mer information om felet", error.message));
}
function logErrorToFile(error: any) {
const errorMessage = `${new Date().toISOString()} - ${error.stack}\n`;
fs.appendFileSync('rap-lp-error.log', errorMessage);
if (error.errors) {
const detailedMessage = `${new Date().toISOString()} - ${JSON.stringify(error.errors, null, 2)}\n`;
fs.appendFileSync('rap-lp-error.log', detailedMessage);
}
if (error instanceof AggregateError) {
error.errors.forEach((err: any, index: number) => {
const causeMessage = `Cause ${index + 1}: ${err.stack || err}\n`;
fs.appendFileSync('rap-lp-error.log', causeMessage);
});
}
}
}