From 79b10bbb9b1e09bc3bda06da066fac528fbc1171 Mon Sep 17 00:00:00 2001 From: Shiv Jha-Mathur Date: Fri, 29 Apr 2022 00:36:11 +0530 Subject: [PATCH] Add `--json` option --- bin/swagger-cli.js | 18 ++++++++++++++++-- test/specs/validate.spec.js | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/bin/swagger-cli.js b/bin/swagger-cli.js index c1ae15f..dbd3124 100644 --- a/bin/swagger-cli.js +++ b/bin/swagger-cli.js @@ -96,6 +96,10 @@ function parseArgs () { .option("h", { alias: "help", type: "boolean", + }) + .option("j", { + alias: "json", + type: "boolean", }); // Show the version number on "--version" or "-v" @@ -123,6 +127,7 @@ function parseArgs () { wrap: args.wrap || Infinity, debug: args.debug, help: args.help, + json: args.json, } }; @@ -145,10 +150,19 @@ function parseArgs () { async function validate (file, options) { try { await api.validate(file, options); - console.log(file, "is valid"); + if (options.json) { + console.log(JSON.stringify({ valid: true, error: [] })); + } else { + console.log(file, "is valid"); + } } catch (error) { - errorHandler(error); + if (options.json) { + console.error(JSON.stringify({ valid: false, error })); + process.exit(1); + } else { + errorHandler(error); + } } } diff --git a/test/specs/validate.spec.js b/test/specs/validate.spec.js index b2c0d40..c06e333 100644 --- a/test/specs/validate.spec.js +++ b/test/specs/validate.spec.js @@ -13,6 +13,21 @@ describe("swagger-cli validate", () => { expect(output.stdout).to.equal("test/files/valid/single-file/api.yaml is valid\n"); }); + it("should validate a single-file API (JSON output)", () => { + let output = helper.run( + "--json", + "validate", + "test/files/valid/single-file/api.yaml" + ); + + expect(output.stderr).to.have.lengthOf(0); + expect(output.status).to.equal(0); + expect(JSON.parse(output.stdout)).to.deep.equal({ + valid: true, + error: [], + }); + }); + it("should validate a multi-file API", () => { let output = helper.run("validate", "test/files/valid/multi-file/api.yaml"); @@ -53,6 +68,25 @@ describe("swagger-cli validate", () => { expect(output.stderr).to.equal("Validation failed. /paths/people/{name}/get is missing path parameter(s) for {name}\n"); }); + it("should fail validation against the Swagger 2.0 specification (JSON output)", () => { + let output = helper.run( + "--json", + "validate", + "test/files/invalid/spec/api.yaml" + ); + + expect(output.stdout).to.have.lengthOf(0); + expect(output.status).to.equal(1); + + const parsed = JSON.parse(output.stderr); + expect(parsed.valid).to.be.false; + expect(parsed.error.message).to.equal( + "Validation failed. /paths/people/{name}/get is missing path parameter(s) for {name}" + ); + expect(parsed.error.name).to.equal("SyntaxError"); + expect(parsed.error.inner).to.be.undefined; + }); + it("should skip validation against the Swagger 2.0 specification", () => { let output = helper.run("validate", "--no-spec", "test/files/invalid/spec/api.yaml");