Add printenv

This commit is contained in:
Apache 2024-10-17 14:00:58 -05:00
parent 32f2f66c7d
commit e7b84e6e13
Signed by: apache
GPG key ID: 78BA80EB40E43123
4 changed files with 76 additions and 1 deletions

View file

@ -7,6 +7,10 @@ edition = "2021"
name = "echo" name = "echo"
path = "src/echo.rs" path = "src/echo.rs"
[[bin]]
name = "printenv"
path = "src/printenv.rs"
[dependencies] [dependencies]
aho-corasick = "1.1.3" aho-corasick = "1.1.3"
clap = { version = "4.5.20", features = ["derive"] } clap = { version = "4.5.20", features = ["derive"] }

View file

@ -4,5 +4,5 @@ Implementation of some of the Unix command line utils
Currently implemented: Currently implemented:
``` ```
echo echo, printenv
``` ```

43
src/printenv.rs Normal file
View file

@ -0,0 +1,43 @@
#![feature(iter_intersperse)]
use std::io::Write;
use clap::Parser;
/// Utility command to output information
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
/// End each output line with NUL instead of newline
#[arg(short='0', long)]
null: bool,
}
fn main() {
let args = Args::parse();
let mut list: Vec<String> = vec![];
for (k, v) in std::env::vars() {
list.push(format!("{k}={v}"));
}
let mut data: String;
if args.null {
data = list.join("\0");
data.push('\0');
} else {
data = list.join("\n");
data.push('\n');
}
let mut out = std::io::stdout();
match out.write_all(data.as_bytes()) {
Err(e) => {
eprintln!("Failed to write to stdout: {e}");
std::process::exit(1);
},
Ok(()) => ()
};
}

28
tests/printenv.rs Normal file
View file

@ -0,0 +1,28 @@
use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::process::Command;
#[test]
fn env_capture() -> Result<(), Box<dyn std::error::Error>> {
std::env::set_var("TEST_ABC", "brrrr");
let mut cmd = Command::cargo_bin("printenv")?;
cmd.assert()
.success()
.stdout(predicate::str::contains("TEST_ABC=brrrr\n"));
Ok(())
}
#[test]
fn null_replace() -> Result<(), Box<dyn std::error::Error>> {
std::env::set_var("TEST_ABC", "brrrr");
let mut cmd = Command::cargo_bin("printenv")?;
cmd.arg("-0");
cmd.assert()
.success()
.stdout(predicate::str::contains("TEST_ABC=brrrr\0"));
Ok(())
}