From bf4e7b00d72341184a130685856db988f30e1463 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 13 May 2024 17:01:38 +0200 Subject: [PATCH] fix: only read from stdin if it's not a terminal #17 --- src/main.rs | 49 ++++++++++++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/main.rs b/src/main.rs index 0588508..ca7e5ab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,7 @@ //! This binary should just take any amount of numbers and print them out formatted to some other //! system. -use std::io::Read; +use std::io::{IsTerminal, Read}; use std::process::exit; use clap::{CommandFactory, Parser}; @@ -16,32 +16,35 @@ fn main() { // try to read from stdin first, appending the numbers we read to the FormatOptions let mut options = FormatOptions::parse(); let mut stdin_nums = Vec::new(); - match std::io::stdin().lock().read_to_end(&mut stdin_nums) { - Ok(_) => { - let whole: String = match String::from_utf8(stdin_nums) { - Ok(r) => r, - Err(e) => { - eprintln!("stdin for this program only accepts text: {e:#?}"); - exit(1); - } - }; - let split = whole.split_whitespace(); - for s in split { - let number = match numf_parser(s) { - Ok(n) => n, + let stdin = std::io::stdin(); + if !stdin.is_terminal() { + match stdin.lock().read_to_end(&mut stdin_nums) { + Ok(_) => { + let whole: String = match String::from_utf8(stdin_nums) { + Ok(r) => r, Err(e) => { - eprintln!("could not parse number from stdin: {e:#?}"); - exit(2); + eprintln!("stdin for this program only accepts text: {e:#?}"); + 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) => { - eprintln!("could not read from stdin: {e:#?}"); - exit(2); - } - }; + Err(e) => { + eprintln!("could not read from stdin: {e:#?}"); + exit(2); + } + }; + } if options.numbers().is_empty() { format!("{}", FormatOptions::command().render_usage());