summaryrefslogtreecommitdiffstats
path: root/src/pipeline/builtins/mod.rs
blob: 003892d9c07bbfc025c080eb6e82ec32d614531a (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 crate::pipeline::prelude::*;

pub mod command;
pub use command::{Child, Command};

type Builtin = &'static (dyn for<'a> Fn(
    crate::parse::Exe,
    &'a Env,
    command::Io,
) -> anyhow::Result<command::Child<'a>>
              + Sync
              + Send);

#[allow(clippy::as_conversions)]
static BUILTINS: once_cell::sync::Lazy<
    std::collections::HashMap<&'static str, Builtin>,
> = once_cell::sync::Lazy::new(|| {
    let mut builtins = std::collections::HashMap::new();
    builtins.insert("cd", &cd as Builtin);
    builtins.insert("echo", &echo);
    builtins.insert("and", &and);
    builtins.insert("or", &or);
    builtins.insert("command", &command);
    builtins.insert("builtin", &builtin);
    builtins
});

// clippy can't tell that the type is necessary
#[allow(clippy::unnecessary_wraps)]
fn cd(
    exe: crate::parse::Exe,
    env: &Env,
    io: command::Io,
) -> anyhow::Result<command::Child> {
    async fn async_cd(
        exe: crate::parse::Exe,
        _env: &Env,
        io: command::Io,
    ) -> std::process::ExitStatus {
        macro_rules! bail {
            ($msg:literal $(,)?) => {
                io.write_stderr(format!("cd: {}\n", $msg).as_bytes())
                    .await
                    .unwrap();
                return std::process::ExitStatus::from_raw(1 << 8);
            };
            ($msg:expr $(,)?) => {
                io.write_stderr(format!("cd: {}\n", $msg).as_bytes())
                    .await
                    .unwrap();
                return std::process::ExitStatus::from_raw(1 << 8);
            };
            ($msg:expr, $($arg:tt)*) => {
                io.write_stderr(b"cd: ").await.unwrap();
                io.write_stderr(format!($msg, $($arg)*).as_bytes())
                    .await
                    .unwrap();
                io.write_stderr(b"\n").await.unwrap();
                return std::process::ExitStatus::from_raw(1 << 8);
            };
        }

        let dir = exe
            .args()
            .into_iter()
            .map(std::convert::AsRef::as_ref)
            .next()
            .unwrap_or("");

        let dir = if dir.is_empty() {
            if let Some(dir) = home(None) {
                dir
            } else {
                bail!("couldn't find current user");
            }
        } else if dir.starts_with('~') {
            let path: std::path::PathBuf = dir.into();
            if let std::path::Component::Normal(prefix) =
                path.components().next().unwrap()
            {
                let prefix_bytes = prefix.as_bytes();
                let name = if prefix_bytes == b"~" {
                    None
                } else {
                    Some(std::ffi::OsStr::from_bytes(&prefix_bytes[1..]))
                };
                if let Some(home) = home(name) {
                    home.join(path.strip_prefix(prefix).unwrap())
                } else {
                    bail!(
                        "no such user: {}",
                        name.map(std::ffi::OsStr::to_string_lossy)
                            .as_ref()
                            .unwrap_or(&std::borrow::Cow::Borrowed(
                                "(deleted)"
                            ))
                    );
                }
            } else {
                unreachable!()
            }
        } else {
            dir.into()
        };
        if let Err(e) = std::env::set_current_dir(&dir) {
            bail!("{}: {}", crate::format::io_error(&e), dir.display());
        }
        async_std::process::ExitStatus::from_raw(0)
    }

    Ok(command::Child::new_fut(async move {
        async_cd(exe, env, io).await
    }))
}

// clippy can't tell that the type is necessary
#[allow(clippy::unnecessary_wraps)]
// mostly just for testing and ensuring that builtins work, i'll likely remove
// this later, since the binary seems totally fine
fn echo(
    exe: crate::parse::Exe,
    env: &Env,
    io: command::Io,
) -> anyhow::Result<command::Child> {
    async fn async_echo(
        exe: crate::parse::Exe,
        _env: &Env,
        io: command::Io,
    ) -> std::process::ExitStatus {
        macro_rules! write_stdout {
            ($bytes:expr) => {
                if let Err(e) = io.write_stdout($bytes).await {
                    io.write_stderr(format!("echo: {}", e).as_bytes())
                        .await
                        .unwrap();
                    return async_std::process::ExitStatus::from_raw(1 << 8);
                }
            };
        }
        let count = exe.args().count();
        for (i, arg) in exe.args().enumerate() {
            write_stdout!(arg.as_bytes());
            if i == count - 1 {
                write_stdout!(b"\n");
            } else {
                write_stdout!(b" ");
            }
        }

        async_std::process::ExitStatus::from_raw(0)
    }

    Ok(command::Child::new_fut(async move {
        async_echo(exe, env, io).await
    }))
}

fn and(
    mut exe: crate::parse::Exe,
    env: &Env,
    io: command::Io,
) -> anyhow::Result<command::Child> {
    exe.shift();
    if env.latest_status().success() {
        let mut cmd = crate::pipeline::Command::new(exe);
        io.setup_command(&mut cmd);
        Ok(command::Child::new_wrapped(cmd.spawn(env)?))
    } else {
        let status = *env.latest_status();
        Ok(command::Child::new_fut(async move { status }))
    }
}

fn or(
    mut exe: crate::parse::Exe,
    env: &Env,
    io: command::Io,
) -> anyhow::Result<command::Child> {
    exe.shift();
    if env.latest_status().success() {
        let status = *env.latest_status();
        Ok(command::Child::new_fut(async move { status }))
    } else {
        let mut cmd = crate::pipeline::Command::new(exe);
        io.setup_command(&mut cmd);
        Ok(command::Child::new_wrapped(cmd.spawn(env)?))
    }
}

fn command(
    mut exe: crate::parse::Exe,
    env: &Env,
    io: command::Io,
) -> anyhow::Result<command::Child> {
    exe.shift();
    let mut cmd = crate::pipeline::Command::new_binary(exe);
    io.setup_command(&mut cmd);
    Ok(command::Child::new_wrapped(cmd.spawn(env)?))
}

fn builtin(
    mut exe: crate::parse::Exe,
    env: &Env,
    io: command::Io,
) -> anyhow::Result<command::Child> {
    exe.shift();
    let mut cmd = crate::pipeline::Command::new_builtin(exe);
    io.setup_command(&mut cmd);
    Ok(command::Child::new_wrapped(cmd.spawn(env)?))
}

fn home(user: Option<&std::ffi::OsStr>) -> Option<std::path::PathBuf> {
    let user = user.map_or_else(
        || users::get_user_by_uid(users::get_current_uid()),
        users::get_user_by_name,
    );
    user.map(|user| user.home_dir().to_path_buf())
}