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
use std::{
    process::{Command, Child, Stdio},
    sync::mpsc::{self, Sender, Receiver},
    thread,
    io::prelude::*,
    io::BufReader,
    str,
    path::PathBuf,
};

pub struct ChildProcess {
    pub child: Child,
    pub stdin_sender: Sender<ChildStdIn>,
    pub line_sender: Sender<ChildStdIO>,
    pub line_receiver: Receiver<ChildStdIO>,
}

pub enum ChildStdIO {
    StdOut(String),
    StdErr(String),
    Term,
    Kill
}

pub enum ChildStdIn {
    Send(String),
    Term,
}

impl ChildProcess {
    
    pub fn start(cmd: &str, args: &[String], current_dir: PathBuf, env: &[(&str, &str)]) -> Result<ChildProcess, std::io::Error> {
        
        let mut cmd_build = Command::new(cmd);
        
        cmd_build.args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .current_dir(current_dir);
        
        for (key, value) in env {
            cmd_build.env(key, value);
        }
        
        let mut child = cmd_build.spawn()?;
        
        let (line_sender, line_receiver) = mpsc::channel();
        let (stdin_sender, stdin_receiver) = mpsc::channel();

        let mut stdin = child.stdin.take().expect("stdin cannot be taken!");
        let stdout = child.stdout.take().expect("stdout cannot be taken!");
        let stderr = child.stderr.take().expect("stderr cannot be taken!");
        
        let _stdout_thread = {
            let line_sender = line_sender.clone();
            let stdin_sender = stdin_sender.clone();
            thread::spawn(move || {
                let mut reader = BufReader::new(stdout);
                loop{
                    let mut line = String::new();
                    if let Ok(len) = reader.read_line(&mut line){
                        if len == 0{
                            break
                        }
                        if line_sender.send(ChildStdIO::StdOut(line)).is_err(){
                            break;
                        }
                    }
                    else{
                        let _ = line_sender.send(ChildStdIO::Term);
                        let _ = stdin_sender.send(ChildStdIn::Term);
                        break;
                    }
                }
            })
        };
        
        let _stderr_thread = {
            let line_sender = line_sender.clone();
            thread::spawn(move || {
                let mut reader = BufReader::new(stderr);
                loop{
                    let mut line = String::new();
                    if let Ok(len) = reader.read_line(&mut line){
                        if len == 0{
                            break
                        }
                        if line_sender.send(ChildStdIO::StdErr(line)).is_err(){
                            break
                        };
                    }
                    else{
                        break;
                    }
                }
            });
        };

        let _stdin_thread = {
            thread::spawn(move || {
                while let Ok(line) = stdin_receiver.recv() {
                    match line {
                        ChildStdIn::Send(line) => {
                            if let Err(_) = stdin.write_all(line.as_bytes()){
                                //println!("Stdin send error {}", e);
                            }
                            let _ = stdin.flush();
                        }
                        ChildStdIn::Term=>{
                            break;
                        }
                    }
                }
            });
        };
        Ok(ChildProcess {
            stdin_sender,
            line_sender,
            child,
            line_receiver,
        })
    }
    
    pub fn wait(mut self) {
        let _ = self.child.wait();
    }
    
    pub fn kill(mut self) {
        let _ = self.stdin_sender.send(ChildStdIn::Term);
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}