Refactored stdin parsing.

This commit is contained in:
shy 2021-04-16 16:40:12 +02:00
parent d236c791a1
commit a79cd5d566
2 changed files with 12 additions and 17 deletions

View file

@ -1,5 +1,6 @@
use std::io::Write; use std::io::Write;
use std::process::{Command, Stdio, Child}; use std::process::{Command, Stdio, Child};
use std::io::BufRead;
use termion::{color, cursor, style}; use termion::{color, cursor, style};
use termion::raw::RawTerminal; use termion::raw::RawTerminal;
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
@ -350,24 +351,19 @@ impl AlarmRoster {
pub fn from_stdin(&mut self, stdin: std::io::Stdin) pub fn from_stdin(&mut self, stdin: std::io::Stdin)
-> Result<(), String> -> Result<(), String>
{ {
let mut buffer = String::new(); for line in stdin.lock().lines() {
loop { match line {
buffer.clear(); Ok(line)
match stdin.read_line(&mut buffer) { if !line.starts_with('#')
Ok(0) => break, // EOF. && !line.trim().is_empty()
Ok(1) => continue, // Empty (newline only). => {
Ok(_) if buffer.starts_with('#') => continue, if let Err(e) = self.add(&line) {
Ok(_) => (), return Err(format!("Value \"{}\": {}", line, e));
}
},
Ok(_) => (), // Discard comments and empty lines.
Err(e) => return Err(e.to_string()), Err(e) => return Err(e.to_string()),
} }
// Strip newline.
if buffer.ends_with('\n') { buffer.pop(); }
// Ignore lines containing only white spaces.
if buffer.contains(|c: char| !c.is_whitespace()) {
if let Err(e) = self.add(&buffer) {
return Err(format!("Value \"{}\": {}",buffer, e));
}
}
} }
Ok(()) Ok(())
} }

View file

@ -15,7 +15,6 @@ fn main() {
// Read alarm times from stdin if stdin is not a tty. // Read alarm times from stdin if stdin is not a tty.
let stdin = std::io::stdin(); let stdin = std::io::stdin();
if !termion::is_tty(&stdin) { if !termion::is_tty(&stdin) {
stdin.lock();
if let Err(e) = alarm_roster.from_stdin(stdin) { if let Err(e) = alarm_roster.from_stdin(stdin) {
eprintln!("Error while reading alarm times from stdin. ({})", e); eprintln!("Error while reading alarm times from stdin. ({})", e);
process::exit(1); process::exit(1);