Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support for stdin and piping #270

Merged
merged 3 commits into from
Mar 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions lib/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const path = require('path');
const rules = require('./rules.js');
const resolver = require('oas-resolver');
const yaml = require('js-yaml');
const readline = require('readline');

class ExtendableError extends Error {
constructor(message) {
Expand All @@ -27,6 +28,21 @@ function readFileAsync(filename, encoding) {
});
}

function readFileStdinAsync() {
return new Promise((resolve, reject) => {
const rl = readline.createInterface({
input: process.stdin
});
let lines = [];
rl.on('line', (line) => {
lines.push(line);
});
rl.on('close', () => {
resolve(lines.join('\n'));
});
});
}

const fetchUrl = async (url) => {
let response;
try {
Expand All @@ -45,18 +61,24 @@ const fetchUrl = async (url) => {
};


// file can be null, meaning stdin
function readSpecFile(file, options) {
if (options.verbose > 1) {
console.log('GET ' + file);
file ? console.error('GET ' + file) : console.error('GET <stdin>');
}
if (file && file.startsWith('http')) {
if (!file) {
// standard input
return readFileStdinAsync();
} else if (file && file.startsWith('http')) {
// remote file
return fetch(file).then(res => {
if (res.status !== 200) {
throw new Error(`Received status code ${res.status}`);
}
return res.text();
})
} else {
// local file
// TODO error handlers?
return readFileAsync(file, 'utf8');
}
Expand All @@ -83,16 +105,16 @@ const recursivelyLoadRulesets = async (ruleset, loadedRulesets, options) => {
let text;
// If the ruleset looks like a HTTP URL
if (ruleset && ruleset.startsWith('http')) {
if (verbose > 1) console.log('GET ' + ruleset);
if (verbose > 1) console.error('GET ' + ruleset);
text = await fetchUrl(ruleset);
}
else if (fs.existsSync(ruleset)) {
if (verbose > 1) console.log('READ ' + ruleset);
if (verbose > 1) console.error('READ ' + ruleset);
text = fs.readFileSync(ruleset, 'utf8');
}
else {
const rulesetFile = path.join(__dirname, '../rules/' + ruleset + '.yaml');
if (verbose > 1) console.log('READ ' + rulesetFile);
if (verbose > 1) console.error('READ ' + rulesetFile);
text = fs.readFileSync(rulesetFile, 'utf8');
}

Expand Down
6 changes: 6 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"babel-preset-es2015": "^6.24.1",
"coveralls": "^3.0.0",
"jest": "^24.1.0",
"mock-stdin": "^0.3.1",
"nock": "^10.0.0"
}
}
21 changes: 11 additions & 10 deletions resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,20 @@ const command = async (file, cmd) => {
return new Promise((resolve, reject) => {
if (output) {
fs.writeFile(output, content, 'utf8', err => {
if (err && verbose) {
console.error('Failed to write file: ' + err.message);
return reject();
if (err) {
if (verbose) console.error('Failed to write file: ' + err.message);
reject();
} else {
if (verbose) console.error('Resolved to ' + output);
resolve();
}

if (verbose) console.log('Resolved to ' + output);
});

return resolve();
} else {
process.stdout.write(content, () => {
// Do not exit until the output is flushed (e.g. pipes)
resolve();
});
}

console.log(content);
return resolve();
});
};

Expand Down
4 changes: 2 additions & 2 deletions speccy.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ program
.option('-c, --config [configFile]', 'config file (containing JSON/YAML). See README for potential values.');

program
.command('lint <file-or-url>')
.description('ensure specs are not just valid OpenAPI, but lint against specified rules')
.command('lint [file-or-url]')
.description('ensure specs are not just valid OpenAPI, but lint against specified rules. If no argument is passed, then standard input will be used (please note that in this case the provided spec must be fully resolved)')
.option('-q, --quiet', 'reduce verbosity')
.option('-r, --rules [ruleFile]', 'provide multiple rules files', collect, [])
.option('-s, --skip [ruleName]', 'provide multiple rules to skip', collect, [])
Expand Down
74 changes: 73 additions & 1 deletion test/integration/lint.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const fs = require('fs');
const mockStdin = require('mock-stdin');
const lint = require('../../lint.js');

const commandConfig = {
Expand All @@ -9,7 +11,7 @@ const commandConfig = {
};

beforeEach(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
});

describe('Lint command', () => {
Expand Down Expand Up @@ -73,4 +75,74 @@ describe('Lint command', () => {
});
});
});

describe('properly support stdin and pipes', () => {
let stdin = null;

beforeEach(() => {
stdin = mockStdin.stdin();
});

afterEach(() => {
stdin.restore();
});

test('expect errors on lint of empty input', () => {
process.nextTick(function mockResponse() {
stdin.end();
});

expect.assertions(4);
const logSpy = jest.spyOn(console, 'log');
const warnSpy = jest.spyOn(console, 'warn');
const errorSpy = jest.spyOn(console, 'error');

// pass null as spec, it will be read from stdin
return lint.command(null, commandConfig).catch(() => {
expect(logSpy).toBeCalledTimes(0);
expect(warnSpy).toBeCalledTimes(0);
expect(errorSpy).toBeCalledTimes(2);
expect(errorSpy).toHaveBeenCalledWith('\x1b[31mSpecification schema is invalid.\x1b[0m');
});
});

test('expect errors on lint of invalid input', () => {
const spec = fs.readFileSync('./test/fixtures/integration/invalid-key.yaml', 'utf8');
process.nextTick(function mockResponse() {
stdin.send(spec, 'utf8').end();
});

expect.assertions(4);
const logSpy = jest.spyOn(console, 'log');
const warnSpy = jest.spyOn(console, 'warn');
const errorSpy = jest.spyOn(console, 'error');

return lint.command('./test/fixtures/integration/invalid-key.yaml', commandConfig).catch(() => {
expect(logSpy).toBeCalledTimes(0);
expect(warnSpy).toBeCalledTimes(0);
expect(errorSpy).toBeCalledTimes(2);
expect(errorSpy).toHaveBeenCalledWith('\x1b[31mSpecification schema is invalid.\x1b[0m');
});
});

test('expect no errors on lint of valid input', () => {
const spec = fs.readFileSync('./test/fixtures/loader/openapi.yaml', 'utf8');
process.nextTick(function mockResponse() {
stdin.send(spec, 'utf8').end();
});

expect.assertions(4);
const logSpy = jest.spyOn(console, 'log');
const warnSpy = jest.spyOn(console, 'warn');
const errorSpy = jest.spyOn(console, 'error');

// pass null as spec, it will be read from stdin
return lint.command(null, commandConfig).then(() => {
expect(logSpy).toBeCalledTimes(1);
expect(logSpy.mock.calls[0][0]).toEqual('\x1b[32mSpecification is valid, with 0 lint errors\x1b[0m');
expect(warnSpy).toBeCalledTimes(0);
expect(errorSpy).toBeCalledTimes(0);
});
});
});
});