aboutsummaryrefslogtreecommitdiffstats
path: root/src/run/mod.rs
blob: 47bf1750ad517254ec0594f01b47b1f703b9925f (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
232
233
234
235
236
237
use std::collections::HashMap;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::thread::Thread;

use crate::parse::Ast;
use crate::*;

mod builtin;

pub fn run(se: &mut Session, cmd: Vec<u8>) {
    let parsed = parse::do_parse(&cmd);

    let parsed = match parsed {
        Ok(p) => p,
        Err(err) => {
            println!("{cmd:?}");
            print!("{err:?}\r\n{PROMPT}");
            return;
        }
    };

    let Ast::Pipes(pipes) = parsed else {
        todo!("can only handle pipes");
    };

    let mut children = Vec::new();
    let mut threads = Vec::new();
    let mut prev_reader = None;
    let mut spawn_error = false;

    se.raw.disable();

    for (i, cmd) in pipes.cmds.iter().enumerate() {
        let last = i == pipes.cmds.len() - 1;

        let (reader, writer) = if !last {
            let (r, w) = io::pipe().unwrap();
            (Some(r), Some(w))
        } else {
            (None, None)
        };

        let Some(dc) = se.dispatch.get(&cmd.cmd[..]) else {
            println!(
                "unknown command {}",
                String::from_utf8_lossy(cmd.cmd.as_slice())
            );
            spawn_error = true;
            break;
        };

        match dc {
            CommandKind::Path(path) => {
                let mut command = Command::new(&path);
                for arg in cmd.args.iter() {
                    command.arg(OsStr::from_bytes(arg));
                }

                if let Some(r) = prev_reader.take() {
                    command.stdin(Stdio::from(r));
                }

                if let Some(w) = writer {
                    command.stdout(Stdio::from(w));
                }

                let Ok(child) = command.spawn() else {
                    println!("failed to spawn {path:?}");
                    spawn_error = true;
                    break;
                };

                children.push(child);
            }

            CommandKind::Builtin(builtin) => {
                builtin.mod_session(se, &cmd.args);

                let mut input: Box<dyn io::Read + Send> = match prev_reader.take() {
                    Some(r) => Box::new(r),
                    None => Box::new(io::stdin()),
                };

                let mut output: Box<dyn io::Write + Send> = match writer {
                    Some(w) => Box::new(w),
                    None => Box::new(io::stdout()),
                };

                // SAFETY: safe as long as we join all threads below again.
                // panics were not considered so probably needs to be fixed
                let args = &cmd.args;
                let args: &'static Vec<BString> = unsafe { std::mem::transmute(args) };

                let handle = std::thread::spawn(move || builtin.io(args, &mut input, &mut output));

                threads.push(handle);
            }
        }

        prev_reader = reader;
    }

    let status_string;

    if spawn_error {
        for child in children.iter_mut() {
            if let Err(e) = child.kill() {
                println!("failed to kill child - {e:?}");
            }
        }
        status_string = "ERR".into();
    } else {
        let mut code = 0;
        for jh in threads {
            // TODO do not ignore panics
            let _ = jh.join();
        }
        for mut child in children {
            match child.wait() {
                Ok(ec) => {
                    if let Some(c) = ec.code() {
                        code = c;
                    }
                }
                Err(e) => {
                    println!("failed to wait for child - {e:?}")
                }
            }
        }
        if code == 0 {
            status_string = String::new();
        } else {
            status_string = format!("{code}");
        }
    }

    se.raw.enable();

    print!("\r{status_string}{PROMPT}");
    let _ = std::io::stdout().lock().flush();
}

#[allow(unused_variables)]
pub trait Builtin: Send + Sync {
    fn name(&self) -> &str;

    /// quick synchronous call, `cd` for example
    fn mod_session(&self, session: &mut Session, args: &[BString]) {}

    /// potentially long, pipelineable thread, builtin `cat` for example
    fn io(
        &self,
        args: &[BString],
        stdin: &mut dyn Read,
        stdout: &mut dyn Write,
    ) -> std::io::Result<()> {
        Ok(())
    }
}

const BUILTINS: &[&'static dyn Builtin] = &[
    &builtin::cd,
    &builtin::clear,
    #[cfg(debug_assertions)]
    &builtin::re,
    &builtin::sink("to", false),
    &builtin::sink("into", false),
    &builtin::sink("append", true),
    &builtin::from,
];

pub struct CommandDispatch {
    map: HashMap<BString, CommandKind>,
}

impl CommandDispatch {
    pub fn new() -> Self {
        let mut map = HashMap::new();

        // all the commands from PATH
        let path = std::env::var_os("PATH").unwrap();
        for p in path.as_bytes().split(|x| *x == b':').rev() {
            let p = PathBuf::from(OsStr::from_bytes(p));
            let Ok(entries) = fs::read_dir(p) else {
                continue;
            };

            for entry in entries {
                let Ok(entry) = entry else { continue };
                let Ok(meta) = entry.metadata() else {
                    continue;
                };

                if !meta.is_file() {
                    continue;
                }

                let perms = meta.permissions();
                let mode = perms.mode();

                // Check if any execute bit is set (owner/group/other)
                if mode & 0o111 == 0 {
                    continue;
                }

                // insert into our command map, mind the .rev() on the iterator above s.t. correct precedence is had
                map.insert(
                    entry.file_name().as_bytes().to_vec(),
                    CommandKind::Path(entry.path()),
                );
            }
        }

        // builtins
        for &b in BUILTINS {
            map.insert(b.name().as_bytes().to_vec(), CommandKind::Builtin(b));
        }

        Self { map }
    }

    fn get(&self, cmd: &bstr) -> Option<CommandKind> {
        if cmd.starts_with(b"/") || cmd.starts_with(b"./") {
            Some(CommandKind::Path(PathBuf::from(OsStr::from_bytes(cmd))))
        } else {
            self.map.get(cmd).cloned()
        }
    }
}

#[derive(Clone)]
pub enum CommandKind {
    Builtin(&'static dyn Builtin),
    Path(PathBuf),
}