aboutsummaryrefslogtreecommitdiffstats
path: root/src/state.rs
blob: 197ff0e9b04eb813f7bf2d2d76054ff165b8a274 (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
219
220
221
222
223
224
225
226
227
228
229
230
231
use futures::future::Future as _;
use futures::stream::Stream as _;
use snafu::{OptionExt as _, ResultExt as _};
use std::io::Write as _;

#[derive(Debug, snafu::Snafu)]
pub enum Error {
    #[snafu(display("invalid command index: {}", idx))]
    InvalidCommandIndex { idx: usize },

    #[snafu(display("error during read: {}", source))]
    Read { source: crate::readline::Error },

    #[snafu(display("error during eval: {}", source))]
    Eval { source: crate::eval::Error },

    #[snafu(display("error during print: {}", source))]
    Print { source: std::io::Error },

    #[snafu(display("eof"))]
    EOF,
}

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

pub struct State {
    idx: usize,
    readline: Option<crate::readline::Readline>,
    commands: std::collections::HashMap<usize, Command>,
}

impl State {
    pub fn new() -> Result<Self> {
        Ok(Self {
            idx: 0,
            readline: Some(Self::read()?),
            commands: std::collections::HashMap::new(),
        })
    }

    fn read() -> Result<crate::readline::Readline> {
        crate::readline::readline("$ ", true).context(Read)
    }

    fn eval(
        &mut self,
        idx: usize,
        line: &str,
    ) -> std::result::Result<(), Error> {
        if self.commands.contains_key(&idx) {
            return Err(Error::InvalidCommandIndex { idx });
        }
        let eval = crate::eval::eval(line).context(Eval);
        match eval {
            Ok(eval) => {
                self.commands.insert(idx, Command::new(eval));
            }
            Err(e) => return Err(e),
        }
        Ok(())
    }

    fn command_start(
        &mut self,
        idx: usize,
        cmd: &str,
        args: &[String],
    ) -> Result<()> {
        let command = self
            .commands
            .get_mut(&idx)
            .context(InvalidCommandIndex { idx })?;
        let cmd = cmd.to_string();
        let args = args.to_vec();
        eprint!("running '{} {:?}'\r\n", cmd, args);
        command.cmd = Some(cmd);
        command.args = Some(args);
        Ok(())
    }

    fn command_output(&mut self, idx: usize, output: &[u8]) -> Result<()> {
        let command = self
            .commands
            .get_mut(&idx)
            .context(InvalidCommandIndex { idx })?;
        command.output.append(&mut output.to_vec());

        let stdout = std::io::stdout();
        let mut stdout = stdout.lock();
        stdout.write(output).context(Print)?;
        stdout.flush().context(Print)?;

        Ok(())
    }

    fn command_exit(
        &mut self,
        idx: usize,
        status: std::process::ExitStatus,
    ) -> Result<()> {
        let command = self
            .commands
            .get_mut(&idx)
            .context(InvalidCommandIndex { idx })?;
        command.status = Some(status);
        eprint!("command exited: {}\r\n", status);
        Ok(())
    }

    fn poll_with_errors(&mut self) -> futures::Poll<(), Error> {
        loop {
            let mut did_work = false;

            if self.readline.is_none() && self.commands.is_empty() {
                self.idx += 1;
                self.readline = Some(Self::read()?)
            }

            if let Some(mut r) = self.readline.take() {
                match r.poll() {
                    Ok(futures::Async::Ready(line)) => {
                        // overlapping RawScreen lifespans don't work properly
                        // - if readline creates a RawScreen, then eval
                        // creates a separate one, then readline drops it, the
                        // screen will go back to cooked even though a
                        // RawScreen instance is still live.
                        drop(r);

                        match self.eval(self.idx, &line) {
                            Ok(())
                            | Err(Error::Eval {
                                source:
                                    crate::eval::Error::Parser {
                                        source:
                                            crate::parser::Error::CommandRequired,
                                        ..
                                    },
                            }) => {}
                            Err(e) => return Err(e),
                        }
                        did_work = true;
                    }
                    Ok(futures::Async::NotReady) => {
                        self.readline.replace(r);
                    }
                    Err(crate::readline::Error::EOF) => {
                        return Err(Error::EOF)
                    }
                    Err(e) => return Err(e).context(Read),
                }
            }

            for idx in self.commands.keys().cloned().collect::<Vec<usize>>() {
                match self
                    .commands
                    .get_mut(&idx)
                    .unwrap()
                    .future
                    .poll()
                    .context(Eval)?
                {
                    futures::Async::Ready(Some(event)) => match event {
                        crate::eval::CommandEvent::CommandStart(
                            cmd,
                            args,
                        ) => {
                            self.command_start(idx, &cmd, &args)?;
                            did_work = true;
                        }
                        crate::eval::CommandEvent::Output(out) => {
                            self.command_output(idx, &out)?;
                            did_work = true;
                        }
                        crate::eval::CommandEvent::CommandExit(status) => {
                            self.command_exit(idx, status)?;
                            did_work = true;
                        }
                    },
                    futures::Async::Ready(None) => {
                        self.commands
                            .remove(&idx)
                            .context(InvalidCommandIndex { idx })?;
                        did_work = true;
                    }
                    futures::Async::NotReady => {}
                }
            }

            if !did_work {
                return Ok(futures::Async::NotReady);
            }
        }
    }
}

impl futures::future::Future for State {
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> futures::Poll<Self::Item, Self::Error> {
        loop {
            match self.poll_with_errors() {
                Ok(a) => return Ok(a),
                Err(Error::EOF) => return Ok(futures::Async::Ready(())),
                Err(e) => {
                    eprint!("error polling state: {}\r\n", e);
                }
            }
        }
    }
}

struct Command {
    future: crate::eval::Eval,
    cmd: Option<String>,
    args: Option<Vec<String>>,
    output: Vec<u8>,
    status: Option<std::process::ExitStatus>,
}

impl Command {
    fn new(future: crate::eval::Eval) -> Self {
        Self {
            future,
            cmd: None,
            args: None,
            output: vec![],
            status: None,
        }
    }
}