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
use colored::*;
use std::fmt::Write as FmtWrite;
use std::io;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::PathBuf;
use std::process;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use std::thread;

use anyhow::{Context, Result};

pub use file::{set_exec_permision, File};
pub use var::{
    generate_array_env_var, generate_env_var, generate_env_vars, var_name, EnvValue, EnvVar,
    ENV_ENVIRONMENT_VAR, ENV_SETUP_VAR,
};

mod file;
pub mod kind;
mod var;

#[derive(Debug)]
pub struct Output {
    pub status: i32,
    pub stdout: String,
    pub stderr: String,
}

impl Output {
    pub fn new() -> Self {
        Self {
            status: 0,
            stdout: "".into(),
            stderr: "".into(),
        }
    }
}

impl From<process::Output> for Output {
    fn from(output: process::Output) -> Self {
        Self {
            status: output.status.code().map_or(0, |code| code),
            stderr: String::from_utf8_lossy(output.stderr.as_ref()).into_owned(),
            stdout: String::from_utf8_lossy(output.stdout.as_ref()).into_owned(),
        }
    }
}

pub fn run_as_stream(file: &PathBuf, vars: &Vec<EnvVar>, args: &Vec<String>) -> Result<Output> {
    let file = file.canonicalize()?;
    let mut command = Command::new(&file);

    for env_var in vars.iter() {
        command.env(env_var.var().to_env_var(), env_var.env_value().to_string());
    }

    if let Some(parent) = file.parent() {
        command.current_dir(parent);
    }

    let mut child = command
        .stdout(Stdio::piped())
        .stdin(Stdio::piped())
        .stderr(Stdio::piped())
        .args(args)
        .spawn()
        .context(format!("command {} fail", &file.to_string_lossy()))?;

    let mut command_stdin = child.stdin.take().expect("fail to get stdin");
    let read_stdin = thread::spawn(move || loop {
        // /!\ Manually tested
        let mut buff_writer = BufWriter::new(&mut command_stdin);
        let mut buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
        buff_writer.write_all(buffer.as_str().as_bytes()).unwrap();
    });

    let output = Arc::new(Mutex::new(Output::new()));

    let read_stdout = if let Some(stdout) = child.stdout.take() {
        let output = Arc::clone(&output);
        Some(thread::spawn(move || {
            let buf = BufReader::new(stdout);
            let mut buffer = String::new();
            for line in buf.lines() {
                let line = line.unwrap();
                writeln!(&mut buffer, "{}", line).unwrap();
                println!("{}", line.normal().clear());
            }
            let mut output = output.lock().unwrap();
            output.stdout = buffer;
        }))
    } else {
        None
    };
    let read_err = if let Some(stderr) = child.stderr.take() {
        let output = Arc::clone(&output);
        Some(thread::spawn(move || {
            let buf = BufReader::new(stderr);
            let mut buffer = String::new();
            for line in buf.lines() {
                let line = line.unwrap();
                writeln!(&mut buffer, "{}", line).unwrap();
                println!("{}", line.red());
            }
            let mut output = output.lock().unwrap();
            output.stderr = buffer;
        }))
    } else {
        None
    };

    if let Some(read_err) = read_err {
        read_err.join().expect("fail to wait read_err");
    }
    if let Some(read_stdout) = read_stdout {
        read_stdout.join().expect("fail to wait read_stdout");
    }
    drop(read_stdin);

    let exit_status = child.wait().unwrap();
    {
        let mut output = output.lock().unwrap();
        output.status = exit_status.code().unwrap_or_default();
    }

    let output = Arc::try_unwrap(output).unwrap();
    let output = output.into_inner().unwrap();
    Ok(output)
}

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

    use cli_integration_test::IntegrationTestEnvironment;

    use crate::run_file::run_as_stream;

    #[test]
    fn run_integration_test_stream() {
        let mut e = IntegrationTestEnvironment::new("run_integration_test");
        e.add_file(
            "run.sh",
            r#"#!/bin/bash
echo TEST
echo ERR >> /dev/stderr
"#,
        );
        e.setup();
        e.set_exec_permission("run.sh").unwrap();

        let output = run_as_stream(
            &e.path().unwrap().join(PathBuf::from("run.sh")),
            &vec![],
            &vec![],
        )
        .unwrap();
        assert_eq!(output.stdout, "TEST\n".to_string());
        assert_eq!(output.stderr, "ERR\n".to_string());
        assert_eq!(output.status, 0);
    }

    #[test]
    fn run_integration_test_stream_with_args() {
        let mut e = IntegrationTestEnvironment::new("run_integration_test");
        e.add_file(
            "run.sh",
            r#"#!/bin/bash
echo ARG = $1
"#,
        );
        e.setup();
        e.set_exec_permission("run.sh").unwrap();

        let output = run_as_stream(
            &e.path().unwrap().join(PathBuf::from("run.sh")),
            &vec![],
            &vec!["TEST_ARG".to_string()],
        )
        .unwrap();
        assert_eq!(output.stdout, "ARG = TEST_ARG\n".to_string());
        assert_eq!(output.status, 0);
    }
}