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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
use std::{collections::HashMap, path::Path, process::Output};

// use crate::{Error, Result};
// use teller_providers::errors::{Error, Result};
use crate::{Error, Result};
pub struct Opts<'a> {
    pub pwd: &'a Path,
    pub capture: bool,
    pub sh: bool,
    pub reset_env: bool,
}

const ENV_OK: &[&str] = &[
    "USER",
    "HOME",
    "PATH",
    "TMPDIR",
    "SHELL",
    "SSH_AUTH_SOCK",
    "LANG",
    "LC_ALL",
    "TEMPDIR",
    "TERM",
    "COLORTERM",
    "LOGNAME",
];

/// Run a command
///
/// # Errors
///
/// This function will return an error if running command fails
pub fn cmd(cmdstr: &str, env_kvs: &[(String, String)], opts: &Opts<'_>) -> Result<Output> {
    let words = if opts.sh {
        shell_command_argv(cmdstr.into())
    } else {
        shell_words::split(cmdstr)?.iter().map(Into::into).collect()
    };
    cmd_slice(
        words
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>()
            .as_slice(),
        env_kvs,
        opts,
    )
}

fn cmd_slice(words: &[&str], env_kvs: &[(String, String)], opts: &Opts<'_>) -> Result<Output> {
    // env handling
    let mut env_map: HashMap<_, _> = if opts.reset_env {
        std::env::vars()
            .filter(|(k, _)| ENV_OK.contains(&k.as_str()))
            .collect()
    } else {
        std::env::vars().collect()
    };

    for (k, v) in env_kvs {
        env_map.insert(k.clone(), v.clone());
    }

    // no shell
    let (first, rest) = words
        .split_first()
        .ok_or_else(|| Error::Message("command has not enough arguments".to_string()))?;

    let mut expr = duct::cmd(Path::new(first), rest)
        .dir(opts.pwd)
        .full_env(&env_map);

    if opts.capture {
        expr = expr.stdout_capture();
    }

    Ok(expr.run()?)
}

#[cfg(unix)]
fn shell_command_argv(command: String) -> Vec<String> {
    use std::env;

    let shell = env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into());
    vec![shell, "-c".into(), command]
}

#[cfg(windows)]
fn shell_command_argv(command: String) -> Vec<String> {
    let comspec = std::env::var_os("COMSPEC")
        .and_then(|s| s.into_string().ok())
        .unwrap_or_else(|| "cmd.exe".into());
    vec![comspec, "/C".into(), command]
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use insta::assert_debug_snapshot;
    use teller_providers::config::ProviderInfo;
    use teller_providers::config::KV;
    use teller_providers::providers::ProviderKind;

    use super::cmd;
    use super::Opts;

    #[test]
    #[cfg(not(windows))]
    fn run_echo() {
        let out = cmd(
            "echo $MY_VAR",
            &std::iter::once(&KV::from_literal(
                "/foo/bar",
                "MY_VAR",
                "shazam",
                ProviderInfo {
                    kind: ProviderKind::Inmem,
                    name: "test".to_string(),
                },
            ))
            .map(|kv| (kv.key.clone(), kv.value.clone()))
            .collect::<Vec<_>>(),
            &Opts {
                pwd: Path::new("."),
                capture: true,
                reset_env: true,
                sh: true,
            },
        )
        .unwrap();
        let s = String::from_utf8_lossy(&out.stdout[..]);
        assert_debug_snapshot!(s);
    }

    #[ignore]
    #[test]
    fn env_reset() {
        let out = cmd(
            "/usr/bin/env",
            &std::iter::once(&KV::from_literal(
                "/foo/bar",
                "MY_VAR",
                "shazam",
                ProviderInfo {
                    kind: ProviderKind::Inmem,
                    name: "test".to_string(),
                },
            ))
            .map(|kv| (kv.key.clone(), kv.value.clone()))
            .collect::<Vec<_>>(),
            &Opts {
                pwd: Path::new("."),
                capture: true,
                reset_env: false, // <-- notice this!
                sh: false,
            },
        )
        .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout[..]).to_string();

        // dirty secret here
        assert!(stdout.contains("GITHUB_TOKEN="));

        let out = cmd(
            "/usr/bin/env",
            &std::iter::once(&KV::from_literal(
                "/foo/bar",
                "MY_VAR",
                "shazam",
                ProviderInfo {
                    kind: ProviderKind::Inmem,
                    name: "test".to_string(),
                },
            ))
            .map(|kv| (kv.key.clone(), kv.value.clone()))
            .collect::<Vec<_>>(),
            &Opts {
                pwd: Path::new("."),
                capture: true,
                reset_env: true, // <-- reset env
                sh: false,
            },
        )
        .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout[..]).to_string();

        assert!(stdout.contains("USER="));
        assert!(stdout.contains("PATH="));
        // no secret here!
        assert!(!stdout.contains("GITHUB_TOKEN="));
    }
}