Skip to content

Commit

Permalink
fix EAGAIN error for stdin
Browse files Browse the repository at this point in the history
  • Loading branch information
Sebastian Lyng Johansen committed Jul 10, 2023
1 parent d6c830c commit 12c2d20
Showing 1 changed file with 50 additions and 10 deletions.
60 changes: 50 additions & 10 deletions bin/sql-formatter-cli.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -91,22 +91,62 @@ class PrettierSQLArgs {
};
}

getInput() {
const infile = this.args.file || process.stdin.fd;
readError(e) {
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;
}

stdinReadSync() {
const b = Buffer.alloc(1024);
let data = '';

while (true) {
let n = 0;

// Read while EAGAIN
while (true) {
try {
n = fs.readSync(process.stdin.fd, b, 0, b.length);
break;
} catch (e) {
if (e.code === 'EAGAIN') {
// Sleep 100ms
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
continue;
}
this.readError(e);
}
}

if (!n) break;
data += b.toString('utf8', 0, n);
}

return data;
}

fileReadSync() {
try {
return fs.readFileSync(infile, 'utf-8');
return fs.readFileSync(this.args.file, '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;
this.readError(e);
}
}

getInput() {
if (this.args.file) {
return this.fileReadSync();
} else {
return this.stdinReadSync();
}
}

Expand Down

0 comments on commit 12c2d20

Please sign in to comment.