logtimes/src/main.rs

66 lines
1.5 KiB
Rust
Raw Normal View History

2020-07-30 10:15:18 +02:00
use chrono::prelude::*;
use std::io::{stdin, stdout, ErrorKind, Read, StdoutLock, Write};
2020-07-30 10:15:18 +02:00
#[inline(always)]
fn print_time(output: &mut StdoutLock) -> Result<(), std::io::Error> {
2020-07-30 10:15:18 +02:00
let date_now = Local::now().format("%H:%M:%S%.9f");
let color_green = "\x1b\x5b\x30\x3b\x33\x32\x6d";
let color_off = "\x1b\x5b\x30\x6d";
write!(output, "{}[{}]{} ", color_green, &date_now, color_off)
2020-07-30 10:15:18 +02:00
}
#[inline(always)]
fn print_delete_line(output: &mut StdoutLock) -> Result<(), std::io::Error> {
// tput dl1 und tput hpa 0
let bytes = "\x1b\x5b\x4d\x1b\x5b\x31\x47";
write!(output, "{}", bytes)
}
2020-07-30 10:15:18 +02:00
fn run() -> Result<(), std::io::Error> {
2020-07-30 10:15:18 +02:00
let out = stdout();
let mut output = out.lock();
let inp = stdin();
let mut input = inp.lock();
let mut buf = [0; 1];
2020-07-30 10:15:18 +02:00
let mut linebuf = Vec::with_capacity(64 * 1024);
2020-07-30 10:15:18 +02:00
loop {
if let Err(e) = input.read_exact(&mut buf) {
if e.kind() == ErrorKind::UnexpectedEof {
return Err(e);
} else {
output.flush()?;
return Ok(());
2020-07-30 10:15:18 +02:00
}
}
2020-07-30 10:15:18 +02:00
linebuf.push(buf[0]);
2020-07-30 10:15:18 +02:00
if buf[0] == 0xa {
print_delete_line(&mut output)?;
print_time(&mut output)?;
output.write_all(&linebuf)?;
output.flush()?;
linebuf.clear();
2020-07-30 10:15:18 +02:00
continue;
}
output.write_all(&buf)?;
output.flush()?;
}
}
fn main() {
if let Err(e) = run() {
println!("{:?}", e);
std::process::exit(1);
2020-07-30 10:15:18 +02:00
}
}