1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use clap::Parser;
use rustutils_runnable::Runnable;
use std::env;
use std::error::Error;
use std::ffi::{OsStr, OsString};
use std::io::Write;
use std::os::unix::ffi::OsStrExt;

/// Print the values of the specified environment variables.
#[derive(Parser, Clone, Debug)]
#[clap(author, version, about, long_about = None)]
pub struct Printenv {
    /// When printing the current environment, separate the variables with a NUL character.
    #[clap(short = '0', long)]
    null: bool,
    /// When printing the current environment, output it as JSON.
    #[clap(short, long, conflicts_with = "null")]
    json: bool,
    /// Environment variables to print.
    variables: Vec<OsString>,
}

impl Printenv {
    pub fn run(&self) -> Result<(), Box<dyn Error>> {
        let separator = match self.null {
            true => OsStr::new("\0"),
            false => OsStr::new("\n"),
        };
        self.print_variables(separator)
    }

    pub fn print_variables(&self, separator: &OsStr) -> Result<(), Box<dyn Error>> {
        let mut stdout = std::io::stdout();
        for name in &self.variables {
            let value =
                env::var_os(name).ok_or_else(|| format!("Missing env variable {name:?}"))?;
            stdout.write_all(value.as_bytes())?;
            stdout.write_all(separator.as_bytes())?;
        }
        Ok(())
    }
}

impl Runnable for Printenv {
    fn run(&self) -> Result<(), Box<dyn Error>> {
        self.run()?;
        Ok(())
    }
}