From d8bc6b620e636a958533c94bb656129ed889de92 Mon Sep 17 00:00:00 2001 From: teesh3rt Date: Wed, 26 Mar 2025 16:49:30 +0200 Subject: [PATCH] feat: add the tee command --- coreutils/src/commands/mod.rs | 1 + coreutils/src/commands/tee.rs | 50 +++++++++++++++++++++++++++++++++++ src/registry.rs | 1 + 3 files changed, 52 insertions(+) create mode 100644 coreutils/src/commands/tee.rs diff --git a/coreutils/src/commands/mod.rs b/coreutils/src/commands/mod.rs index 2ffe5b6..30ba6a7 100644 --- a/coreutils/src/commands/mod.rs +++ b/coreutils/src/commands/mod.rs @@ -19,3 +19,4 @@ command!(pwd::Pwd); command!(sleep::Sleep); command!(whoami::WhoAmI); command!(hostname::Hostname); +command!(tee::Tee); diff --git a/coreutils/src/commands/tee.rs b/coreutils/src/commands/tee.rs new file mode 100644 index 0000000..e149097 --- /dev/null +++ b/coreutils/src/commands/tee.rs @@ -0,0 +1,50 @@ +use boxutils::args::ArgParser; +use boxutils::commands::Command; +use std::fs::OpenOptions; +use std::io::Write; + +// TODO: Add the -i flag to ignore SIGINT. +// Not done yet because we want this to be +// Windows-compatible + +pub struct Tee; + +impl Command for Tee { + fn execute(&self) { + let args = ArgParser::builder() + .add_flag("--help") + .add_flag("-a") + .parse_args("tee"); + + if args.get_flag("--help") { + println!("Usage: tee -a [FILE]..."); + } + + let append = args.get_flag("-a"); + let files = args.get_normal_args(); + let mut writes: Vec> = vec![Box::new(std::io::stdout())]; + + for file in files { + let this_file = OpenOptions::new() + .create(true) + .write(true) + .append(append) + .open(&file); + + if let Ok(this_file) = this_file { + writes.push(Box::new(this_file)); + } else { + eprintln!("tee: unable to open file: {}", file); + } + } + + let mut buffer = String::new(); + while std::io::stdin().read_line(&mut buffer).unwrap_or(0) > 0 { + for output in &mut writes { + let _ = output.write_all(buffer.as_bytes()); + let _ = output.flush(); + } + buffer.clear(); + } + } +} diff --git a/src/registry.rs b/src/registry.rs index e27c9cf..a848fb8 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -29,6 +29,7 @@ pub fn get_registry() -> CommandRegistry { "sleep" => coreutils::commands::Sleep, "whoami" => coreutils::commands::WhoAmI, "hostname" => coreutils::commands::Hostname, + "tee" => coreutils::commands::Tee, "box" => Boxcmd });