diff --git a/src/cmd/mod.rs b/src/cmd/mod.rs index bcca642..5811bf3 100644 --- a/src/cmd/mod.rs +++ b/src/cmd/mod.rs @@ -31,6 +31,7 @@ mod mountpoint; mod mv; mod nologin; mod nproc; +mod printenv; mod pwd; mod rev; mod rm; @@ -85,6 +86,7 @@ pub fn get(name: &str) -> Option> { "mountpoint" => Some(Box::new(mountpoint::Mountpoint::default())), "nologin" => Some(Box::new(nologin::Nologin::default())), "nproc" => Some(Box::new(nproc::Nproc::default())), + "printenv" => Some(Box::new(printenv::Printenv::default())), "pwd" => Some(Box::new(pwd::Pwd::default())), "rev" => Some(Box::new(rev::Rev::default())), "rm" => Some(Box::new(rm::Rm::default())), @@ -101,7 +103,7 @@ pub fn get(name: &str) -> Option> { } } -pub static COMMANDS: [&str; 35] = [ +pub static COMMANDS: [&str; 36] = [ "base32", "base64", "basename", @@ -125,6 +127,7 @@ pub static COMMANDS: [&str; 35] = [ "mountpoint", "nologin", "nproc", + "printenv", "pwd", "rev", "rm", diff --git a/src/cmd/printenv/mod.rs b/src/cmd/printenv/mod.rs new file mode 100644 index 0000000..9c34aa8 --- /dev/null +++ b/src/cmd/printenv/mod.rs @@ -0,0 +1,56 @@ +use std::{env, io}; + +use super::Cmd; +use clap::{Arg, ArgAction, Command}; + +#[derive(Debug, Default)] +pub struct Printenv; + +impl Cmd for Printenv { + fn cli(&self) -> clap::Command { + Command::new("printenv") + .about("print all or part of environment") + .author("Nathan Fisher") + .version(env!("CARGO_PKG_VERSION")) + .args([ + Arg::new("null") + .short('0') + .long("null") + .help("end each output line with NUL, not newline") + .action(ArgAction::SetTrue), + Arg::new("var") + .value_name("VARIABLE") + .num_args(1..) + .required(false), + ]) + } + + fn run(&self, matches: Option<&clap::ArgMatches>) -> Result<(), Box> { + let Some(matches) = matches else { + return Err(io::Error::new(io::ErrorKind::Other, "no input").into()); + }; + if let Some(vars) = matches.get_many::("var") { + for var in vars { + let val = env::var(var)?; + if matches.get_flag("null") { + print!("{var}={val}\0"); + } else { + println!("{var}={val}"); + } + } + } else { + env::vars().for_each(|(var, val)| { + if matches.get_flag("null") { + print!("{var}={val}\0"); + } else { + println!("{var}={val}"); + } + }); + } + Ok(()) + } + + fn path(&self) -> Option { + Some(crate::Path::UsrBin) + } +}