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

fix EAGAIN error for stdin #621

Merged
merged 2 commits into from
Jul 23, 2023
Merged
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
58 changes: 41 additions & 17 deletions bin/sql-formatter-cli.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,36 @@ const fs = require('fs');
const tty = require('tty');
const { version } = require('../package.json');
const { ArgumentParser } = require('argparse');
const { promisify } = require('util');

class PrettierSQLArgs {
constructor() {
this.parser = this.getParser();
this.args = this.parser.parse_args();
this.cfg = this.readConfig();

this.query = this.getInput();
const formattedQuery = format(this.query, this.cfg).trim() + '\n';
this.writeOutput(this.getOutputFile(this.args), formattedQuery);
this.readFile = promisify(fs.readFile);
this.getInput().then(input => {
this.query = input;
const formattedQuery = format(this.query, this.cfg).trim() + '\n';
this.writeOutput(this.getOutputFile(this.args), formattedQuery);
});
}

async getStdin() {
if (process.stdin.isTTY) {
return Buffer.alloc(0);
}

const result = [];
let length = 0;

for await (const chunk of process.stdin) {
result.push(chunk);
length += chunk.length;
}

return Buffer.concat(result, length).toString();
}

getParser() {
Expand Down Expand Up @@ -91,22 +111,26 @@ class PrettierSQLArgs {
};
}

getInput() {
async getInput() {
const infile = this.args.file || process.stdin.fd;
try {
return fs.readFileSync(infile, 'utf-8');
} catch (e) {
if (e.code === 'EAGAIN') {
console.error('Error: no file specified and no data in stdin');
process.exit(1);
}
if (e.code === 'ENOENT') {
console.error(`Error: could not open file ${infile}`);
process.exit(1);
if (this.args.file) {
try {
return await this.readFile(infile, { encoding: 'utf-8' });
} catch (e) {
if (e.code === 'EAGAIN') {
console.error('Error: no file specified and no data in stdin');
process.exit(1);
}
if (e.code === 'ENOENT') {
console.error(`Error: could not open file ${infile}`);
process.exit(1);
}
console.error('An unknown error has occurred, please file a bug report at:');
console.log('https://github.com/sql-formatter-org/sql-formatter/issues\n');
throw e;
}
console.error('An unknown error has occurred, please file a bug report at:');
console.log('https://github.com/sql-formatter-org/sql-formatter/issues\n');
throw e;
} else {
return await this.getStdin();
}
}

Expand Down
Loading