aboutsummaryrefslogtreecommitdiffstats
path: root/src/process.rs
blob: 81899d70a5fc3c4087fe79b9953586d2407f182d (plain) (blame)
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
use futures::future::Future as _;
use snafu::ResultExt as _;
use std::io::{Read as _, Write as _};
use tokio::io::AsyncRead as _;
use tokio_pty_process::CommandExt as _;

#[derive(Debug, snafu::Snafu)]
pub enum Error {
    #[snafu(display("failed to open a pty: {}", source))]
    OpenPty { source: std::io::Error },

    #[snafu(display("failed to spawn process for `{}`: {}", cmd, source))]
    SpawnProcess { cmd: String, source: std::io::Error },

    #[snafu(display("failed to write to pty: {}", source))]
    WriteToPty { source: std::io::Error },

    #[snafu(display("failed to read from terminal: {}", source))]
    ReadFromTerminal { source: std::io::Error },

    #[snafu(display(
        "failed to clear ready state on pty for reading: {}",
        source
    ))]
    PtyClearReadReady { source: std::io::Error },

    #[snafu(display("failed to poll for process exit: {}", source))]
    ProcessExitPoll { source: std::io::Error },

    #[snafu(display(
        "failed to put the terminal into raw mode: {}",
        source
    ))]
    IntoRawMode { source: std::io::Error },
}

pub type Result<T> = std::result::Result<T, Error>;

pub fn spawn(cmd: &str, args: &[String]) -> Result<RunningProcess> {
    RunningProcess::new(cmd, args)
}

pub struct RunningProcess {
    pty: tokio_pty_process::AsyncPtyMaster,
    process: tokio_pty_process::Child,
    // TODO: tokio::io::Stdin is broken
    // input: tokio::io::Stdin,
    input: tokio::reactor::PollEvented2<EventedStdin>,
    cmd: String,
    args: Vec<String>,
    buf: Vec<u8>,
    started: bool,
    output_done: bool,
    exit_done: bool,
    _screen: crossterm::RawScreen,
}

impl RunningProcess {
    fn new(cmd: &str, args: &[String]) -> Result<Self> {
        let pty =
            tokio_pty_process::AsyncPtyMaster::open().context(OpenPty)?;

        let process = std::process::Command::new(cmd)
            .args(args)
            .spawn_pty_async(&pty)
            .context(SpawnProcess { cmd })?;

        // TODO: tokio::io::stdin is broken (it's blocking)
        // let input = tokio::io::stdin();
        let input = tokio::reactor::PollEvented2::new(EventedStdin);

        Ok(Self {
            pty,
            process,
            input,
            cmd: cmd.to_string(),
            args: args.to_vec(),
            buf: Vec::with_capacity(4096),
            started: false,
            output_done: false,
            exit_done: false,
            _screen: crossterm::RawScreen::into_raw_mode()
                .context(IntoRawMode)?,
        })
    }
}

#[must_use = "streams do nothing unless polled"]
impl futures::stream::Stream for RunningProcess {
    type Item = crate::eval::CommandEvent;
    type Error = Error;

    fn poll(&mut self) -> futures::Poll<Option<Self::Item>, Self::Error> {
        if !self.started {
            self.started = true;
            return Ok(futures::Async::Ready(Some(
                crate::eval::CommandEvent::CommandStart(
                    self.cmd.clone(),
                    self.args.clone(),
                ),
            )));
        }

        let ready = mio::Ready::readable();
        let input_poll = self.input.poll_read_ready(ready);
        match input_poll {
            Ok(futures::Async::Ready(_)) => {
                let stdin = std::io::stdin();
                let mut stdin = stdin.lock();
                let mut buf = vec![0; 4096];
                // TODO: async
                let n = stdin.read(&mut buf).context(ReadFromTerminal)?;
                if n > 0 {
                    let bytes = buf[..n].to_vec();

                    // TODO: async
                    self.pty.write_all(&bytes).context(WriteToPty)?;
                }
            }
            _ => {}
        }
        // TODO: this could lose pending bytes if there is stuff to read in
        // the buffer but we don't read it all in the previous read call,
        // since i think we won't get another notification until new bytes
        // actually arrive even if there are bytes in the buffer
        self.input
            .clear_read_ready(ready)
            .context(PtyClearReadReady)?;

        if !self.output_done {
            self.buf.clear();
            let output_poll = self.pty.read_buf(&mut self.buf);
            match output_poll {
                Ok(futures::Async::Ready(n)) => {
                    let bytes = self.buf[..n].to_vec();
                    let bytes: Vec<_> = bytes
                        .iter()
                        // replace \n with \r\n
                        .fold(vec![], |mut acc, &c| {
                            if c == b'\n' {
                                acc.push(b'\r');
                                acc.push(b'\n');
                            } else {
                                acc.push(c);
                            }
                            acc
                        });
                    return Ok(futures::Async::Ready(Some(
                        crate::eval::CommandEvent::Output(bytes),
                    )));
                }
                Ok(futures::Async::NotReady) => {
                    return Ok(futures::Async::NotReady);
                }
                Err(_) => {
                    // explicitly ignoring errors (for now?) because we
                    // always read off the end of the pty after the process
                    // is done
                    self.output_done = true;
                }
            }
        }

        if !self.exit_done {
            let exit_poll = self.process.poll().context(ProcessExitPoll);
            match exit_poll {
                Ok(futures::Async::Ready(status)) => {
                    self.exit_done = true;
                    return Ok(futures::Async::Ready(Some(
                        crate::eval::CommandEvent::ProcessExit(status),
                    )));
                }
                Ok(futures::Async::NotReady) => {
                    return Ok(futures::Async::NotReady);
                }
                Err(e) => {
                    return Err(e);
                }
            }
        }

        Ok(futures::Async::Ready(None))
    }
}

struct EventedStdin;

impl mio::Evented for EventedStdin {
    fn register(
        &self,
        poll: &mio::Poll,
        token: mio::Token,
        interest: mio::Ready,
        opts: mio::PollOpt,
    ) -> std::io::Result<()> {
        let fd = 0 as std::os::unix::io::RawFd;
        let eventedfd = mio::unix::EventedFd(&fd);
        eventedfd.register(poll, token, interest, opts)
    }

    fn reregister(
        &self,
        poll: &mio::Poll,
        token: mio::Token,
        interest: mio::Ready,
        opts: mio::PollOpt,
    ) -> std::io::Result<()> {
        let fd = 0 as std::os::unix::io::RawFd;
        let eventedfd = mio::unix::EventedFd(&fd);
        eventedfd.reregister(poll, token, interest, opts)
    }

    fn deregister(&self, poll: &mio::Poll) -> std::io::Result<()> {
        let fd = 0 as std::os::unix::io::RawFd;
        let eventedfd = mio::unix::EventedFd(&fd);
        eventedfd.deregister(poll)
    }
}