Add printenv applet

This commit is contained in:
Nathan Fisher 2023-01-21 19:20:30 -05:00
parent 9df197a4b9
commit d92cb9f208
2 changed files with 60 additions and 1 deletions

View File

@ -31,6 +31,7 @@ mod mountpoint;
mod mv; mod mv;
mod nologin; mod nologin;
mod nproc; mod nproc;
mod printenv;
mod pwd; mod pwd;
mod rev; mod rev;
mod rm; mod rm;
@ -85,6 +86,7 @@ pub fn get(name: &str) -> Option<Box<dyn Cmd>> {
"mountpoint" => Some(Box::new(mountpoint::Mountpoint::default())), "mountpoint" => Some(Box::new(mountpoint::Mountpoint::default())),
"nologin" => Some(Box::new(nologin::Nologin::default())), "nologin" => Some(Box::new(nologin::Nologin::default())),
"nproc" => Some(Box::new(nproc::Nproc::default())), "nproc" => Some(Box::new(nproc::Nproc::default())),
"printenv" => Some(Box::new(printenv::Printenv::default())),
"pwd" => Some(Box::new(pwd::Pwd::default())), "pwd" => Some(Box::new(pwd::Pwd::default())),
"rev" => Some(Box::new(rev::Rev::default())), "rev" => Some(Box::new(rev::Rev::default())),
"rm" => Some(Box::new(rm::Rm::default())), "rm" => Some(Box::new(rm::Rm::default())),
@ -101,7 +103,7 @@ pub fn get(name: &str) -> Option<Box<dyn Cmd>> {
} }
} }
pub static COMMANDS: [&str; 35] = [ pub static COMMANDS: [&str; 36] = [
"base32", "base32",
"base64", "base64",
"basename", "basename",
@ -125,6 +127,7 @@ pub static COMMANDS: [&str; 35] = [
"mountpoint", "mountpoint",
"nologin", "nologin",
"nproc", "nproc",
"printenv",
"pwd", "pwd",
"rev", "rev",
"rm", "rm",

56
src/cmd/printenv/mod.rs Normal file
View File

@ -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<dyn std::error::Error>> {
let Some(matches) = matches else {
return Err(io::Error::new(io::ErrorKind::Other, "no input").into());
};
if let Some(vars) = matches.get_many::<String>("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<crate::Path> {
Some(crate::Path::UsrBin)
}
}