generated from PlexSheep/rs-base
fix: only read from stdin if it's not a terminal #17
cargo devel CI / cargo CI (push) Successful in 1m14s
Details
cargo devel CI / cargo CI (push) Successful in 1m14s
Details
This commit is contained in:
parent
f93e5f6c4c
commit
bf4e7b00d7
49
src/main.rs
49
src/main.rs
|
@ -3,7 +3,7 @@
|
||||||
//! This binary should just take any amount of numbers and print them out formatted to some other
|
//! This binary should just take any amount of numbers and print them out formatted to some other
|
||||||
//! system.
|
//! system.
|
||||||
|
|
||||||
use std::io::Read;
|
use std::io::{IsTerminal, Read};
|
||||||
use std::process::exit;
|
use std::process::exit;
|
||||||
|
|
||||||
use clap::{CommandFactory, Parser};
|
use clap::{CommandFactory, Parser};
|
||||||
|
@ -16,32 +16,35 @@ fn main() {
|
||||||
// try to read from stdin first, appending the numbers we read to the FormatOptions
|
// try to read from stdin first, appending the numbers we read to the FormatOptions
|
||||||
let mut options = FormatOptions::parse();
|
let mut options = FormatOptions::parse();
|
||||||
let mut stdin_nums = Vec::new();
|
let mut stdin_nums = Vec::new();
|
||||||
match std::io::stdin().lock().read_to_end(&mut stdin_nums) {
|
let stdin = std::io::stdin();
|
||||||
Ok(_) => {
|
if !stdin.is_terminal() {
|
||||||
let whole: String = match String::from_utf8(stdin_nums) {
|
match stdin.lock().read_to_end(&mut stdin_nums) {
|
||||||
Ok(r) => r,
|
Ok(_) => {
|
||||||
Err(e) => {
|
let whole: String = match String::from_utf8(stdin_nums) {
|
||||||
eprintln!("stdin for this program only accepts text: {e:#?}");
|
Ok(r) => r,
|
||||||
exit(1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let split = whole.split_whitespace();
|
|
||||||
for s in split {
|
|
||||||
let number = match numf_parser(s) {
|
|
||||||
Ok(n) => n,
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("could not parse number from stdin: {e:#?}");
|
eprintln!("stdin for this program only accepts text: {e:#?}");
|
||||||
exit(2);
|
exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
options.push_number(number)
|
let split = whole.split_whitespace();
|
||||||
|
for s in split {
|
||||||
|
let number = match numf_parser(s) {
|
||||||
|
Ok(n) => n,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("could not parse number from stdin: {e:#?}");
|
||||||
|
exit(2);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
options.push_number(number)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
Err(e) => {
|
||||||
Err(e) => {
|
eprintln!("could not read from stdin: {e:#?}");
|
||||||
eprintln!("could not read from stdin: {e:#?}");
|
exit(2);
|
||||||
exit(2);
|
}
|
||||||
}
|
};
|
||||||
};
|
}
|
||||||
|
|
||||||
if options.numbers().is_empty() {
|
if options.numbers().is_empty() {
|
||||||
format!("{}", FormatOptions::command().render_usage());
|
format!("{}", FormatOptions::command().render_usage());
|
||||||
|
|
Reference in New Issue