|
| 1 | +import console from 'console'; |
| 2 | + |
| 3 | +import { OpenAPIReader, OpenAPIWriter } from '@fresha/openapi-model/build/3.0.3'; |
| 4 | +import yargs from 'yargs'; |
| 5 | +import { hideBin } from 'yargs/helpers'; |
| 6 | + |
| 7 | +import { createFormatter } from './formatters'; |
| 8 | +import { loadConfigFromFile, createLinter } from './linter'; |
| 9 | + |
| 10 | +try { |
| 11 | + const argv = yargs(hideBin(process.argv)) |
| 12 | + .epilog( |
| 13 | + 'For more information, see https://github.com/fresha/api-tools/tree/main/packages/openapi-lint', |
| 14 | + ) |
| 15 | + .usage('Usage: $0 [OPTIONS] FILES') |
| 16 | + .string('config') |
| 17 | + .alias('config', 'c') |
| 18 | + .describe('config', 'Path to configuration file') |
| 19 | + .boolean('print-config') |
| 20 | + .describe('print-config', 'Print configuration and exit') |
| 21 | + .number('max-warnings') |
| 22 | + .describe('max-warnings', 'Number of warnings to trigger nonzero exit code') |
| 23 | + .boolean('fix') |
| 24 | + .describe('fix', 'Automatically fix problems') |
| 25 | + .choices('formatter', ['simple', 'json']) |
| 26 | + .default('formatter', 'simple') |
| 27 | + .alias('formatter', 'f') |
| 28 | + .boolean('verbose') |
| 29 | + .alias('verbose', 'v') |
| 30 | + .describe('verbose', 'Print more information on console') |
| 31 | + .parseSync(); |
| 32 | + |
| 33 | + const config = loadConfigFromFile(argv.config ?? '.openapi-lint.yaml'); |
| 34 | + if (argv.printConfig) { |
| 35 | + config.print(); |
| 36 | + } |
| 37 | + |
| 38 | + const linter = createLinter({ |
| 39 | + config, |
| 40 | + maxWarnings: argv.maxWarnings ?? -1, |
| 41 | + autoFix: !!argv.fix, |
| 42 | + verbose: !!argv.verbose, |
| 43 | + }); |
| 44 | + |
| 45 | + for (const elem of argv._) { |
| 46 | + const fpath = String(elem); |
| 47 | + try { |
| 48 | + const openapi = new OpenAPIReader().parseFromFile(fpath); |
| 49 | + openapi.setExtension('__filename', fpath); |
| 50 | + |
| 51 | + if (linter.run(openapi)) { |
| 52 | + const writer = new OpenAPIWriter(); |
| 53 | + openapi.deleteExtension('__filename'); |
| 54 | + writer.writeToFile(openapi, fpath); |
| 55 | + } |
| 56 | + } catch (err) { |
| 57 | + if (err instanceof Error) { |
| 58 | + console.log(err instanceof Error ? err.message : err); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + const formatter = createFormatter(argv.formatter); |
| 64 | + formatter.format(linter.result); |
| 65 | + |
| 66 | + process.exit(linter.result.isFailure ? 1 : 0); |
| 67 | +} catch (err) { |
| 68 | + console.log(err instanceof Error ? err.message : err); |
| 69 | + process.exit(1); |
| 70 | +} |
0 commit comments