Allow example CLI to read from stdin (#1536)

This commit is contained in:
Michael Victor Zink 2024-11-22 11:06:42 -08:00 committed by GitHub
parent fad2ddd641
commit a1150223af
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -17,9 +17,11 @@
#![warn(clippy::all)]
/// A small command-line app to run the parser.
/// Run with `cargo run --example cli`
//! A small command-line app to run the parser.
//! Run with `cargo run --example cli`
use std::fs;
use std::io::{stdin, Read};
use simple_logger::SimpleLogger;
use sqlparser::dialect::*;
@ -38,6 +40,9 @@ $ cargo run --example cli FILENAME.sql [--dialectname]
To print the parse results as JSON:
$ cargo run --feature json_example --example cli FILENAME.sql [--dialectname]
To read from stdin instead of a file:
$ cargo run --example cli - [--dialectname]
"#,
);
@ -57,9 +62,18 @@ $ cargo run --feature json_example --example cli FILENAME.sql [--dialectname]
s => panic!("Unexpected parameter: {s}"),
};
println!("Parsing from file '{}' using {:?}", &filename, dialect);
let contents = fs::read_to_string(&filename)
.unwrap_or_else(|_| panic!("Unable to read the file {}", &filename));
let contents = if filename == "-" {
println!("Parsing from stdin using {:?}", dialect);
let mut buf = Vec::new();
stdin()
.read_to_end(&mut buf)
.expect("failed to read from stdin");
String::from_utf8(buf).expect("stdin content wasn't valid utf8")
} else {
println!("Parsing from file '{}' using {:?}", &filename, dialect);
fs::read_to_string(&filename)
.unwrap_or_else(|_| panic!("Unable to read the file {}", &filename))
};
let without_bom = if contents.chars().next().unwrap() as u64 != 0xfeff {
contents.as_str()
} else {