Skip to content

Commit

Permalink
Output format pt 1
Browse files Browse the repository at this point in the history
  • Loading branch information
lcampos committed Jul 20, 2024
1 parent de87f12 commit d29c466
Show file tree
Hide file tree
Showing 7 changed files with 280 additions and 18 deletions.
157 changes: 151 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions packages/cli/cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env -S node --no-warnings
/* eslint-disable */
process.removeAllListeners("warning");
import "./dist/index.js";
4 changes: 4 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
"engines": {
"node": ">=18.0.0"
},
"bin": {
"ratemyopenapi": "cli.js"
},
"devDependencies": {
"@types/mime-types": "^2.1.4",
"@types/node": "^18.18.10",
Expand All @@ -38,6 +41,7 @@
"chalk": "^5.1.2",
"dotenv": "^16.4.5",
"mime-types": "^2.1.35",
"ora": "^8.0.1",
"pino": "^9.3.1",
"pino-pretty": "^11.2.1"
},
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/cmds/report.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { syncReport, SyncReportArguments } from "../sync-report/handler.js";
import { SyncReportArguments } from "sync-report/interfaces.js";
import { syncReport } from "../sync-report/handler.js";
import { Argv } from "yargs";

export default {
Expand Down
26 changes: 26 additions & 0 deletions packages/cli/src/common/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,29 @@ export async function printTableToConsoleAndExitGracefully(table: any) {
printTableToConsole(table);
process.exit(0);
}

export function printScoreResult(
message: string,
score: number,
options?: {
overrideGreen?: number;
overrideYellow?: number;
overrideRed?: number;
},
) {
const greenScore =
options && options.overrideGreen ? options.overrideGreen : 80;
const yellowScore =
options && options.overrideYellow ? options.overrideYellow : 60;
const redScore = options && options.overrideRed ? options.overrideRed : 59;

if (score >= greenScore) {
console.log(`${message} ${chalk.bold.green(score)}`);
} else if (score >= yellowScore && score < greenScore) {
console.log(`${message} ${chalk.bold.yellow(score)}`);
} else if (score <= redScore) {
console.log(`${message} ${chalk.bold.red(score)}`);
} else {
console.log(`${message} ${score}`);
}
}
61 changes: 50 additions & 11 deletions packages/cli/src/sync-report/handler.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,49 @@
import {
printCriticalFailureToConsoleAndExit,
printDiagnosticsToConsole,
printResultToConsole,
printResultToConsoleAndExitGracefully,
printScoreResult,
} from "../common/output.js";
import { existsSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import { ApiError } from "@zuplo/errors";
import { readFile } from "node:fs/promises";
import { lookup } from "mime-types";
import ora from "ora";
import chalk from "chalk";
import { APIResponse, SyncReportArguments } from "./interfaces.js";

export interface SyncReportArguments {
dir: string;
"api-key": string;
filename: string;
}
const okMark = "\x1b[32m✔\x1b[0m";
const failMark = "\x1b[31m✖\x1b[0m";

export async function syncReport(argv: SyncReportArguments) {
printDiagnosticsToConsole(`Rate Open API file ${argv.filename}`);
printDiagnosticsToConsole(`Press Ctrl+C to cancel.\n`);
const spinner = ora("Loading file for processing").start();

process.on("SIGTERM", () => {
spinner.stop();
printResultToConsoleAndExitGracefully("\nProcess has been canceled\n");
});
process.on("SIGINT", () => {
spinner.stop();
printResultToConsoleAndExitGracefully("\nProcess has been canceled\n");
});

// @TODO - remove this in favor of bin configs
process.env.NODE_NO_WARNINGS = "1";
process.removeAllListeners("warning");

const sourceDirectory = resolve(join(relative(process.cwd(), argv.dir)));

const openApiFilePath = join(sourceDirectory, argv.filename);
if (!existsSync(openApiFilePath)) {
spinner.stopAndPersist({ symbol: failMark });
printCriticalFailureToConsoleAndExit(
`The Open API file path provided does not exist: ${argv.filename}. Please specify an existing Open API file and try again.`,
);
}
spinner.stopAndPersist({ symbol: okMark });

// Read the file as a buffer
const data = await readFile(openApiFilePath, "utf-8");
Expand All @@ -36,7 +56,8 @@ export async function syncReport(argv: SyncReportArguments) {
const formData = new FormData();
formData.set("apiFile", file, argv.filename);

printDiagnosticsToConsole(`Processing file ${argv.filename}`);
spinner.start();
spinner.text = "Analizing file";

try {
const fileUploadResults = await fetch(
Expand All @@ -51,16 +72,34 @@ export async function syncReport(argv: SyncReportArguments) {
);

if (fileUploadResults.status !== 200) {
spinner.fail("Analizing file\n");
const error = (await fileUploadResults.json()) as ApiError;
printCriticalFailureToConsoleAndExit(`${error.detail ?? error.message}`);
} else {
// @TODO - show a nice table
const res = await fileUploadResults.json();
printResultToConsole(
`File upload success: ${JSON.stringify(res, null, 2)}`,
spinner.succeed("Analizing file\n");
const res = (await fileUploadResults.json()) as APIResponse;

const simpleJSON = {
...res.results.simpleReport,
...{ reportId: res.reportId, reportUrl: res.reportUrl },
};

// @TODO support more output modes e.g. JSON, GH Actions, etc

console.log(`${chalk.bold.blue("==>")} ${chalk.bold("Results")}\n`);
printScoreResult("Overall", simpleJSON.score);
console.log("======");
printScoreResult("- Docs", simpleJSON.docsScore);
printScoreResult("- Completeness", simpleJSON.completenessScore);
printScoreResult("- SDK Generation", simpleJSON.sdkGenerationScore);
printScoreResult("- Security", simpleJSON.securityScore);
console.log("======\n");
console.log(
`View details of your report at ${chalk.magenta(simpleJSON.reportUrl)}\n`,
);
}
} catch (err) {
spinner.fail("Analizing file\n");
// @TODO - show a nice useful error
printCriticalFailureToConsoleAndExit(
`Error on file upload: ${JSON.stringify(err)}`,
Expand Down
Loading

0 comments on commit d29c466

Please sign in to comment.