pty_process/blocking/
command.rs

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
use std::os::unix::process::CommandExt as _;

/// Wrapper around [`std::process::Command`]
pub struct Command {
    inner: std::process::Command,
    stdin: bool,
    stdout: bool,
    stderr: bool,
    pre_exec_set: bool,
    pre_exec: Option<
        Box<dyn FnMut() -> std::io::Result<()> + Send + Sync + 'static>,
    >,
}

impl Command {
    /// See [`std::process::Command::new`]
    pub fn new<S: AsRef<std::ffi::OsStr>>(program: S) -> Self {
        Self {
            inner: std::process::Command::new(program),
            stdin: false,
            stdout: false,
            stderr: false,
            pre_exec_set: false,
            pre_exec: None,
        }
    }

    /// See [`std::process::Command::arg`]
    #[must_use]
    pub fn arg<S: AsRef<std::ffi::OsStr>>(mut self, arg: S) -> Self {
        self.inner.arg(arg);
        self
    }

    /// See [`std::process::Command::args`]
    #[must_use]
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<std::ffi::OsStr>,
    {
        self.inner.args(args);
        self
    }

    /// See [`std::process::Command::env`]
    #[must_use]
    pub fn env<K, V>(mut self, key: K, val: V) -> Self
    where
        K: AsRef<std::ffi::OsStr>,
        V: AsRef<std::ffi::OsStr>,
    {
        self.inner.env(key, val);
        self
    }

    /// See [`std::process::Command::envs`]
    #[must_use]
    pub fn envs<I, K, V>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<std::ffi::OsStr>,
        V: AsRef<std::ffi::OsStr>,
    {
        self.inner.envs(vars);
        self
    }

    /// See [`std::process::Command::env_remove`]
    #[must_use]
    pub fn env_remove<K: AsRef<std::ffi::OsStr>>(mut self, key: K) -> Self {
        self.inner.env_remove(key);
        self
    }

    /// See [`std::process::Command::env_clear`]
    #[must_use]
    pub fn env_clear(mut self) -> Self {
        self.inner.env_clear();
        self
    }

    /// See [`std::process::Command::current_dir`]
    #[must_use]
    pub fn current_dir<P: AsRef<std::path::Path>>(mut self, dir: P) -> Self {
        self.inner.current_dir(dir);
        self
    }

    /// See [`std::process::Command::stdin`]
    #[must_use]
    pub fn stdin<T: Into<std::process::Stdio>>(mut self, cfg: T) -> Self {
        self.stdin = true;
        self.inner.stdin(cfg);
        self
    }

    /// See [`std::process::Command::stdout`]
    #[must_use]
    pub fn stdout<T: Into<std::process::Stdio>>(mut self, cfg: T) -> Self {
        self.stdout = true;
        self.inner.stdout(cfg);
        self
    }

    /// See [`std::process::Command::stderr`]
    #[must_use]
    pub fn stderr<T: Into<std::process::Stdio>>(mut self, cfg: T) -> Self {
        self.stderr = true;
        self.inner.stderr(cfg);
        self
    }

    /// Executes the command as a child process via
    /// [`std::process::Command::spawn`] on the given pty. The pty will be
    /// attached to all of `stdin`, `stdout`, and `stderr` of the child,
    /// unless those file descriptors were previously overridden through calls
    /// to [`stdin`](Self::stdin), [`stdout`](Self::stdout), or
    /// [`stderr`](Self::stderr). The newly created child process will also be
    /// made the session leader of a new session, and will have the given
    /// pty set as its controlling terminal.
    ///
    /// # Errors
    /// Returns an error if we fail to allocate new file descriptors for
    /// attaching the pty to the child process, or if we fail to spawn the
    /// child process (see the documentation for
    /// [`std::process::Command::spawn`]), or if we fail to make the child a
    /// session leader or set its controlling terminal.
    #[allow(clippy::needless_pass_by_value)]
    pub fn spawn(
        mut self,
        pts: crate::blocking::Pts,
    ) -> crate::Result<std::process::Child> {
        self.spawn_impl(&pts)
    }

    /// Executes the command as a child process via
    /// [`std::process::Command::spawn`] on the given pty. The pty will be
    /// attached to all of `stdin`, `stdout`, and `stderr` of the child,
    /// unless those file descriptors were previously overridden through calls
    /// to [`stdin`](Self::stdin), [`stdout`](Self::stdout), or
    /// [`stderr`](Self::stderr). The newly created child process will also be
    /// made the session leader of a new session, and will have the given
    /// pty set as its controlling terminal.
    ///
    /// Differs from `spawn` in that it borrows the pty rather than consuming
    /// it, allowing for multiple commands to be spawned onto the same pty in
    /// sequence, but this functionality is not available on macos.
    ///
    /// # Errors
    /// Returns an error if we fail to allocate new file descriptors for
    /// attaching the pty to the child process, or if we fail to spawn the
    /// child process (see the documentation for
    /// [`std::process::Command::spawn`]), or if we fail to make the child a
    /// session leader or set its controlling terminal.
    #[cfg(not(target_os = "macos"))]
    pub fn spawn_borrowed(
        &mut self,
        pts: &crate::blocking::Pts,
    ) -> crate::Result<std::process::Child> {
        self.spawn_impl(pts)
    }

    fn spawn_impl(
        &mut self,
        pts: &crate::blocking::Pts,
    ) -> crate::Result<std::process::Child> {
        let (stdin, stdout, stderr) = pts.0.setup_subprocess()?;

        if !self.stdin {
            self.inner.stdin(stdin);
        }
        if !self.stdout {
            self.inner.stdout(stdout);
        }
        if !self.stderr {
            self.inner.stderr(stderr);
        }

        let mut session_leader = pts.0.session_leader();
        // Safety: setsid() is an async-signal-safe function and ioctl() is a
        // raw syscall (which is inherently async-signal-safe).
        if let Some(mut custom) = self.pre_exec.take() {
            unsafe {
                self.inner.pre_exec(move || {
                    session_leader()?;
                    custom()?;
                    Ok(())
                })
            };
        } else if !self.pre_exec_set {
            unsafe { self.inner.pre_exec(session_leader) };
        }
        self.pre_exec_set = true;

        Ok(self.inner.spawn()?)
    }

    /// See [`std::os::unix::process::CommandExt::uid`]
    #[must_use]
    pub fn uid(mut self, id: u32) -> Self {
        self.inner.uid(id);
        self
    }

    /// See [`std::os::unix::process::CommandExt::gid`]
    #[must_use]
    pub fn gid(mut self, id: u32) -> Self {
        self.inner.gid(id);
        self
    }

    /// See [`std::os::unix::process::CommandExt::pre_exec`]
    #[allow(clippy::missing_safety_doc)]
    #[must_use]
    pub unsafe fn pre_exec<F>(mut self, f: F) -> Self
    where
        F: FnMut() -> std::io::Result<()> + Send + Sync + 'static,
    {
        self.pre_exec = Some(Box::new(f));
        self
    }

    /// See [`std::os::unix::process::CommandExt::arg0`]
    #[must_use]
    pub fn arg0<S>(mut self, arg: S) -> Self
    where
        S: AsRef<std::ffi::OsStr>,
    {
        self.inner.arg0(arg);
        self
    }
}