From 9b73d54905349b8e7af348236d14b7ca430072c6 Mon Sep 17 00:00:00 2001 From: teesh3rt Date: Sun, 30 Mar 2025 23:05:49 +0300 Subject: [PATCH] feat: add the dirname command --- coreutils/src/commands/dirname.rs | 36 +++++++++++++++++++++++++++++++ coreutils/src/commands/mod.rs | 1 + src/registry.rs | 1 + 3 files changed, 38 insertions(+) create mode 100644 coreutils/src/commands/dirname.rs diff --git a/coreutils/src/commands/dirname.rs b/coreutils/src/commands/dirname.rs new file mode 100644 index 0000000..8fd18d3 --- /dev/null +++ b/coreutils/src/commands/dirname.rs @@ -0,0 +1,36 @@ +use std::path::Path; + +use boxutils::{args::ArgParser, commands::Command}; + +pub struct Dirname; + +impl Command for Dirname { + fn execute(&self) { + let args = ArgParser::builder() + .add_flag("--help") + .parse_args("dirname"); + + if args.get_normal_args().len() != 1 || args.get_flag("--help") { + println!("Usage: dirname FILENAME"); + return; + } + + // note(teesh): we have already checked for argnums, so we're fine :D + let normal_args = args.get_normal_args(); + let file = normal_args.get(0).unwrap(); + let path = Path::new(file); + + if let Some(parent) = path.parent() { + let mut to_print = format!("{}", parent.display()); + + // note(teesh): this is stupid, but thats how the box busies + if to_print == "" { + to_print = ".".into(); + } + + println!("{}", to_print); + } else { + println!("dirname: could not get parent") + } + } +} diff --git a/coreutils/src/commands/mod.rs b/coreutils/src/commands/mod.rs index ec0abcb..b8d13c2 100644 --- a/coreutils/src/commands/mod.rs +++ b/coreutils/src/commands/mod.rs @@ -25,3 +25,4 @@ command!(base32::Base32); command!(seq::Seq); command!(env::Env); command!(ln::Ln); +command!(dirname::Dirname); \ No newline at end of file diff --git a/src/registry.rs b/src/registry.rs index e7535a6..a504308 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -35,6 +35,7 @@ pub fn get_registry() -> CommandRegistry { "seq" => coreutils::commands::Seq, "env" => coreutils::commands::Env, "ln" => coreutils::commands::Ln, + "dirname" => coreutils::commands::Dirname, "box" => Boxcmd });