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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! the simple invoke command for test
//!
//! This invokes external a command and manipulates standard in out.
//! You can use `std::process::Command` more easily.
//!
//! * minimum support rustc 1.43.0
//!
//! # Example:
//!
//! ```
//! use exec_target::exec_target_with_env_in;
//!
//! let command = "target/debug/exe-stab-grep";
//! let args = &["--color=always", "-e", "c"];
//! let envs = vec![("GREP_COLORS", "ms=01;32")];
//! let inp = b"abcdefg\n" as &[u8];
//!
//! let oup = exec_target_with_env_in(command, args, envs, inp);
//!
//! assert_eq!(oup.stderr, "");
//! assert_eq!(oup.stdout, "ab\u{1b}[01;32m\u{1b}[Kc\u{1b}[m\u{1b}[Kdefg\n");
//! assert_eq!(oup.status.success(), true);
//! ```
//!

use std::collections::HashMap;
use std::env;
use std::ffi::OsStr;
use std::process::{Command, ExitStatus, Output, Stdio};

// trats
use std::io::Write;
use std::iter::IntoIterator;

//
pub struct OutputString {
    pub status: ExitStatus,
    pub stdout: String,
    pub stderr: String,
}

fn setup_envs<I, K, V>(cmd: &mut Command, vars: I) -> &mut Command
where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<OsStr>,
    V: AsRef<OsStr>,
{
    let filtered_env: HashMap<String, String> = env::vars()
        .filter(|&(ref k, _)| k == "TERM" || k == "TZ" || k == "PATH")
        .collect();
    cmd.env_clear()
        .envs(filtered_env)
        .envs(vars)
        .env("LANG", "C")
}

pub fn exec_target<I, S>(target_exe: &str, args: I) -> OutputString
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let mut cmd: Command = Command::new(target_exe);
    setup_envs(&mut cmd, Vec::<(&str, &str)>::new())
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let child = cmd.spawn().expect("failed to execute child");
    let output: Output = child.wait_with_output().expect("failed to wait on child");
    //
    OutputString {
        status: output.status,
        stdout: String::from(String::from_utf8_lossy(&output.stdout)),
        stderr: String::from(String::from_utf8_lossy(&output.stderr)),
    }
}

pub fn exec_target_with_env<I, S, IKV, K, V>(target_exe: &str, args: I, env: IKV) -> OutputString
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
    IKV: IntoIterator<Item = (K, V)>,
    K: AsRef<OsStr>,
    V: AsRef<OsStr>,
{
    let mut cmd: Command = Command::new(target_exe);
    setup_envs(&mut cmd, env)
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let child = cmd.spawn().expect("failed to execute child");
    let output: Output = child.wait_with_output().expect("failed to wait on child");
    //
    OutputString {
        status: output.status,
        stdout: String::from(String::from_utf8_lossy(&output.stdout)),
        stderr: String::from(String::from_utf8_lossy(&output.stderr)),
    }
}

pub fn exec_target_with_in<I, S>(target_exe: &str, args: I, in_bytes: &[u8]) -> OutputString
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let mut cmd: Command = Command::new(target_exe);
    setup_envs(&mut cmd, Vec::<(&str, &str)>::new())
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().expect("failed to execute child");
    {
        let stdin = child.stdin.as_mut().expect("failed to get stdin");
        stdin.write_all(in_bytes).expect("failed to write to stdin");
    }
    let output: Output = child.wait_with_output().expect("failed to wait on child");
    //
    OutputString {
        status: output.status,
        stdout: String::from(String::from_utf8_lossy(&output.stdout)),
        stderr: String::from(String::from_utf8_lossy(&output.stderr)),
    }
}

///
/// This invokes external a command and manipulates standard in out.
/// You can use `std::process::Command` more easily.
///
/// # Example:
///
/// ```
/// use exec_target::exec_target_with_env_in;
///
/// let command = "target/debug/exe-stab-grep";
/// let args = &["--color=always", "-e", "c"];
/// let envs = vec![("GREP_COLORS", "ms=01;32")];
/// let inp = b"abcdefg\n" as &[u8];
///
/// let oup = exec_target_with_env_in(command, args, envs, inp);
///
/// assert_eq!(oup.stderr, "");
/// assert_eq!(oup.stdout, "ab\u{1b}[01;32m\u{1b}[Kc\u{1b}[m\u{1b}[Kdefg\n");
/// assert_eq!(oup.status.success(), true);
/// ```
///
pub fn exec_target_with_env_in<I, S, IKV, K, V>(
    target_exe: &str,
    args: I,
    env: IKV,
    in_bytes: &[u8],
) -> OutputString
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
    IKV: IntoIterator<Item = (K, V)>,
    K: AsRef<OsStr>,
    V: AsRef<OsStr>,
{
    let mut cmd: Command = Command::new(target_exe);
    setup_envs(&mut cmd, env)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().expect("failed to execute child");
    {
        let stdin = child.stdin.as_mut().expect("failed to get stdin");
        stdin.write_all(in_bytes).expect("failed to write to stdin");
    }
    let output: Output = child.wait_with_output().expect("failed to wait on child");
    //
    OutputString {
        status: output.status,
        stdout: String::from(String::from_utf8_lossy(&output.stdout)),
        stderr: String::from(String::from_utf8_lossy(&output.stderr)),
    }
}

///
/// parse a command line strings
///
/// This separates the string with blanks.
/// This considers special characters.
///
/// the special characters:
/// - "" : double quote
/// - '' : single quote
/// - \\ : back_slash
///
pub fn args_from(s: &str) -> Vec<String> {
    let mut v: Vec<String> = Vec::new();
    let mut ss = String::new();
    let mut enter_q: bool = false;
    let mut enter_qq: bool = false;
    let mut back_slash: bool = false;
    //
    for c in s.chars() {
        if back_slash {
            ss.push(c);
            back_slash = false;
            continue;
        }
        if c == '\\' {
            back_slash = true;
            continue;
        }
        if enter_q {
            if c == '\'' {
                v.push(ss.clone());
                ss.clear();
                enter_q = false;
            } else {
                ss.push(c);
            }
            continue;
        }
        if enter_qq {
            if c == '\"' {
                v.push(ss.clone());
                ss.clear();
                enter_qq = false;
            } else {
                ss.push(c);
            }
            continue;
        }
        match c {
            '\'' => {
                enter_q = true;
                continue;
            }
            '\"' => {
                enter_qq = true;
                continue;
            }
            ' ' => {
                if !ss.is_empty() {
                    v.push(ss.clone());
                    ss.clear();
                }
            }
            _ => {
                ss.push(c);
            }
        }
    }
    if !ss.is_empty() {
        v.push(ss.clone());
        ss.clear();
    }
    //
    v
}