summaryrefslogtreecommitdiffstats
path: root/src/runner/command.rs
blob: 5d4c11e8439779d21ea4c413fda86d9b9208efa1 (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
use crate::runner::prelude::*;

pub struct Command {
    inner: Inner,
    exe: std::path::PathBuf,
    redirects: Vec<crate::parse::Redirect>,
    pre_exec: Option<
        Box<dyn FnMut() -> std::io::Result<()> + Send + Sync + 'static>,
    >,
}
impl Command {
    pub fn new(exe: crate::parse::Exe, io: super::builtins::Io) -> Self {
        let exe_path = exe.exe().to_path_buf();
        let redirects = exe.redirects().to_vec();
        Self {
            inner: super::builtins::Command::new(exe, io).map_or_else(
                |exe| Self::new_binary(exe).inner,
                Inner::Builtin,
            ),
            exe: exe_path,
            redirects,
            pre_exec: None,
        }
    }

    #[allow(clippy::needless_pass_by_value)]
    pub fn new_binary(exe: crate::parse::Exe) -> Self {
        let exe_path = exe.exe().to_path_buf();
        let redirects = exe.redirects().to_vec();
        let mut cmd = async_std::process::Command::new(exe.exe());
        cmd.args(exe.args());
        Self {
            inner: Inner::Binary(cmd),
            exe: exe_path,
            redirects,
            pre_exec: None,
        }
    }

    pub fn new_builtin(
        exe: crate::parse::Exe,
        io: super::builtins::Io,
    ) -> Self {
        let exe_path = exe.exe().to_path_buf();
        let redirects = exe.redirects().to_vec();
        Self {
            inner: super::builtins::Command::new(exe, io)
                .map_or_else(|_| todo!(), Inner::Builtin),
            exe: exe_path,
            redirects,
            pre_exec: None,
        }
    }

    pub fn stdin(&mut self, fh: std::fs::File) {
        match &mut self.inner {
            Inner::Binary(cmd) => {
                cmd.stdin(fh);
            }
            Inner::Builtin(cmd) => {
                cmd.stdin(fh);
            }
        }
    }

    pub fn stdout(&mut self, fh: std::fs::File) {
        match &mut self.inner {
            Inner::Binary(cmd) => {
                cmd.stdout(fh);
            }
            Inner::Builtin(cmd) => {
                cmd.stdout(fh);
            }
        }
    }

    pub fn stderr(&mut self, fh: std::fs::File) {
        match &mut self.inner {
            Inner::Binary(cmd) => {
                cmd.stderr(fh);
            }
            Inner::Builtin(cmd) => {
                cmd.stderr(fh);
            }
        }
    }

    // Safety: see pre_exec in async_std::os::unix::process::CommandExt (this
    // is just a wrapper)
    pub unsafe fn pre_exec<F>(&mut self, f: F)
    where
        F: 'static + FnMut() -> std::io::Result<()> + Send + Sync,
    {
        self.pre_exec = Some(Box::new(f));
    }

    pub fn spawn(self, env: &Env) -> anyhow::Result<Child> {
        let Self {
            inner,
            exe,
            redirects,
            pre_exec,
        } = self;

        #[allow(clippy::as_conversions)]
        let pre_exec = pre_exec.map_or_else(
            || {
                let redirects = redirects.clone();
                Box::new(move || {
                    apply_redirects(&redirects)?;
                    Ok(())
                })
                    as Box<dyn FnMut() -> std::io::Result<()> + Send + Sync>
            },
            |mut pre_exec| {
                let redirects = redirects.clone();
                Box::new(move || {
                    apply_redirects(&redirects)?;
                    pre_exec()?;
                    Ok(())
                })
            },
        );
        match inner {
            Inner::Binary(mut cmd) => {
                // Safety: open, dup2, and close are async-signal-safe
                // functions
                unsafe { cmd.pre_exec(pre_exec) };
                Ok(Child::Binary(cmd.spawn().map_err(|e| {
                    anyhow::anyhow!(
                        "{}: {}",
                        crate::format::io_error(&e),
                        exe.display()
                    )
                })?))
            }
            Inner::Builtin(mut cmd) => {
                // Safety: open, dup2, and close are async-signal-safe
                // functions
                unsafe { cmd.pre_exec(pre_exec) };
                cmd.apply_redirects(&redirects);
                Ok(Child::Builtin(cmd.spawn(env)?))
            }
        }
    }
}

pub enum Inner {
    Binary(async_std::process::Command),
    Builtin(super::builtins::Command),
}

pub enum Child<'a> {
    Binary(async_std::process::Child),
    Builtin(super::builtins::Child<'a>),
}

impl<'a> Child<'a> {
    pub fn id(&self) -> Option<u32> {
        match self {
            Self::Binary(child) => Some(child.id()),
            Self::Builtin(child) => child.id(),
        }
    }

    pub fn status(
        self,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<
                    Output = anyhow::Result<std::process::ExitStatus>,
                > + Send
                + Sync
                + 'a,
        >,
    > {
        Box::pin(async move {
            match self {
                Self::Binary(child) => Ok(child.status_no_drop().await?),
                Self::Builtin(child) => Ok(child.status().await?),
            }
        })
    }
}

fn apply_redirects(
    redirects: &[crate::parse::Redirect],
) -> std::io::Result<()> {
    for redirect in redirects {
        match &redirect.to {
            crate::parse::RedirectTarget::Fd(fd) => {
                nix::unistd::dup2(*fd, redirect.from)?;
            }
            crate::parse::RedirectTarget::File(path) => {
                let fd = redirect.dir.open(path)?;
                if fd != redirect.from {
                    nix::unistd::dup2(fd, redirect.from)?;
                    nix::unistd::close(fd)?;
                }
            }
        }
    }
    Ok(())
}