runite 0.1.0

An event-loop-per-thread async runtime built on io_uring (Linux), kqueue (macOS), and IOCP (Windows)
Documentation
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Builders and standard-stream configuration for subprocesses.
//!
//! [`Command`] accumulates a program, arguments, environment changes, working
//! directory, and standard-stream choices before spawning a [`Child`](super::Child).
//! [`Stdio`] describes how each child stream is connected.
//!
//! Spawning delegates to [`std::process::Command`] and is synchronous on the
//! calling runtime thread. The returned [`Child`](super::Child), if any, becomes
//! async when waiting for process exit or driving piped stdio handles through
//! runite's fd-readiness backend.
//!
//! # Examples
//!
//! ```no_run
//! # async fn example() -> std::io::Result<()> {
//! use runite::process::Command;
//!
//! let output = Command::new("echo")
//!     .arg("hello")
//!     .output()
//!     .await?;
//! assert_eq!(output.stdout, b"hello\n");
//! # Ok(())
//! # }
//! ```
//!
use std::ffi::{OsStr, OsString};
use std::io;
use std::path::{Path, PathBuf};

use super::{Child, ExitStatus};
use crate::io::AsyncReadExt;

/// The captured result of a process run by [`Command::output`].
///
/// Mirrors [`std::process::Output`]: the exit status plus the fully-buffered
/// standard output and standard error.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Output {
    /// The status (exit code) the process terminated with.
    pub status: ExitStatus,
    /// The bytes the process wrote to standard output.
    pub stdout: Vec<u8>,
    /// The bytes the process wrote to standard error.
    pub stderr: Vec<u8>,
}

/// Subprocess standard I/O configuration.
///
/// Use this with [`Command::stdin`], [`Command::stdout`], and
/// [`Command::stderr`] to decide whether a child inherits a standard stream,
/// connects it to the null device, or exposes it as an async pipe.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Stdio(pub(crate) StdioKind);

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum StdioKind {
    Inherit,
    Null,
    Piped,
}

impl Stdio {
    /// Inherits the parent process handle for this standard stream.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Stdio;
    ///
    /// let inherited = Stdio::inherit();
    /// ```
    pub fn inherit() -> Self {
        Self(StdioKind::Inherit)
    }

    /// Connects this standard stream to the platform null device.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Stdio;
    ///
    /// let discarded = Stdio::null();
    /// ```
    pub fn null() -> Self {
        Self(StdioKind::Null)
    }

    /// Creates an async pipe connected to the child handle.
    ///
    /// Use this when the parent task needs to asynchronously write child stdin
    /// or read child stdout/stderr.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Stdio;
    ///
    /// let piped = Stdio::piped();
    /// ```
    pub fn piped() -> Self {
        Self(StdioKind::Piped)
    }
}

#[derive(Clone, Debug)]
pub(crate) enum EnvChange {
    Set(OsString, OsString),
    Remove(OsString),
    Clear,
}

#[derive(Clone, Debug)]
pub(crate) struct CommandSpec {
    pub program: OsString,
    pub args: Vec<OsString>,
    pub env: Vec<EnvChange>,
    pub current_dir: Option<PathBuf>,
    pub stdin: StdioKind,
    pub stdout: StdioKind,
    pub stderr: StdioKind,
}

/// Builder for spawning an async subprocess.
///
/// `Command` mirrors the shape of [`std::process::Command`] while returning
/// runtime-aware child handles and async pipes. Configuration methods mutate the
/// builder and return `&mut Self` so they can be chained before [`spawn`](Self::spawn),
/// [`status`](Self::status), or [`output`](Self::output).
///
/// Calling [`spawn`](Self::spawn) itself is synchronous and delegates to
/// [`std::process::Command::spawn`]. Async runtime integration begins with
/// [`Child::wait`](super::Child::wait) and with piped standard streams.
#[derive(Clone, Debug)]
pub struct Command {
    spec: CommandSpec,
}

impl Command {
    /// Creates a command that runs `program`.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Command;
    ///
    /// let command = Command::new("echo");
    /// ```
    pub fn new(program: impl AsRef<OsStr>) -> Self {
        Self {
            spec: CommandSpec {
                program: program.as_ref().to_os_string(),
                args: Vec::new(),
                env: Vec::new(),
                current_dir: None,
                stdin: StdioKind::Inherit,
                stdout: StdioKind::Inherit,
                stderr: StdioKind::Inherit,
            },
        }
    }

    /// Adds one argument to the command line.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Command;
    ///
    /// let mut command = Command::new("echo");
    /// command.arg("hello");
    /// ```
    pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
        self.spec.args.push(arg.as_ref().to_os_string());
        self
    }

    /// Adds multiple arguments to the command line.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Command;
    ///
    /// let mut command = Command::new("echo");
    /// command.args(["hello", "world"]);
    /// ```
    pub fn args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.spec
            .args
            .extend(args.into_iter().map(|arg| arg.as_ref().to_os_string()));
        self
    }

    /// Sets or overrides an environment variable for the child.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Command;
    ///
    /// let mut command = Command::new("env");
    /// command.env("APP_MODE", "test");
    /// ```
    pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
        self.spec.env.push(EnvChange::Set(
            key.as_ref().to_os_string(),
            value.as_ref().to_os_string(),
        ));
        self
    }

    /// Sets or overrides multiple environment variables for the child.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Command;
    ///
    /// let mut command = Command::new("env");
    /// command.envs([("APP_MODE", "test"), ("APP_COLOR", "never")]);
    /// ```
    pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        for (key, value) in vars {
            self.env(key, value);
        }
        self
    }

    /// Removes an environment variable from the child environment.
    ///
    /// The removal is applied after inherited environment handling and before
    /// the child starts.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Command;
    ///
    /// let mut command = Command::new("env");
    /// command.env_remove("APP_MODE");
    /// ```
    pub fn env_remove(&mut self, key: impl AsRef<OsStr>) -> &mut Self {
        self.spec
            .env
            .push(EnvChange::Remove(key.as_ref().to_os_string()));
        self
    }

    /// Clears the child environment.
    ///
    /// Variables added later with [`env`](Self::env) or [`envs`](Self::envs)
    /// are still included.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Command;
    ///
    /// let mut command = Command::new("env");
    /// command.env_clear().env("PATH", "/usr/bin");
    /// ```
    pub fn env_clear(&mut self) -> &mut Self {
        self.spec.env.push(EnvChange::Clear);
        self
    }

    /// Sets the child working directory.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::Command;
    ///
    /// let mut command = Command::new("pwd");
    /// command.current_dir(".");
    /// ```
    pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
        self.spec.current_dir = Some(dir.as_ref().to_path_buf());
        self
    }

    /// Configures the child's standard input stream.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::{Command, Stdio};
    ///
    /// let mut command = Command::new("cat");
    /// command.stdin(Stdio::piped());
    /// ```
    pub fn stdin(&mut self, stdio: Stdio) -> &mut Self {
        self.spec.stdin = stdio.0;
        self
    }

    /// Configures the child's standard output stream.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::{Command, Stdio};
    ///
    /// let mut command = Command::new("echo");
    /// command.stdout(Stdio::piped());
    /// ```
    pub fn stdout(&mut self, stdio: Stdio) -> &mut Self {
        self.spec.stdout = stdio.0;
        self
    }

    /// Configures the child's standard error stream.
    ///
    /// # Examples
    ///
    /// ```
    /// use runite::process::{Command, Stdio};
    ///
    /// let mut command = Command::new("echo");
    /// command.stderr(Stdio::null());
    /// ```
    pub fn stderr(&mut self, stdio: Stdio) -> &mut Self {
        self.spec.stderr = stdio.0;
        self
    }

    /// Spawns the command and returns a handle to the running child.
    ///
    /// If any standard stream was configured with [`Stdio::piped`], the
    /// corresponding field on the returned [`Child`] contains an async pipe.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example() -> std::io::Result<()> {
    /// use runite::process::{Command, Stdio};
    ///
    /// let mut child = Command::new("echo")
    ///     .arg("hello")
    ///     .stdout(Stdio::piped())
    ///     .spawn()?;
    /// assert!(child.stdout.is_some());
    /// # Ok(())
    /// # }
    /// ```
    pub fn spawn(&mut self) -> io::Result<Child> {
        crate::sys::current::process::spawn(&self.spec).map(Child::from_inner)
    }

    /// Spawns the command and waits asynchronously for it to exit.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> std::io::Result<()> {
    /// use runite::process::Command;
    ///
    /// let status = Command::new("true").status().await?;
    /// assert!(status.success());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn status(&mut self) -> io::Result<ExitStatus> {
        self.spawn()?.wait().await
    }

    /// Spawns the command, captures its output, and waits for it to exit.
    ///
    /// Returns an [`Output`] with the exit status and the fully-buffered stdout
    /// and stderr. Like [`std::process::Command::output`], this forces stdout and
    /// stderr to [`Stdio::piped`] and redirects stdin to [`Stdio::null`] (so a
    /// child that reads stdin sees EOF immediately rather than blocking). A
    /// non-zero exit status is **not** an error — inspect
    /// [`output.status`](Output::status) yourself. stdout and stderr are read
    /// concurrently so a child cannot deadlock by filling one pipe's buffer.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> std::io::Result<()> {
    /// use runite::process::Command;
    ///
    /// let output = Command::new("echo").arg("hello").output().await?;
    /// assert!(output.status.success());
    /// assert_eq!(output.stdout, b"hello\n");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn output(&mut self) -> io::Result<Output> {
        self.stdin(Stdio::null());
        self.stdout(Stdio::piped());
        self.stderr(Stdio::piped());
        let mut child = self.spawn()?;

        // Drain stderr on a separate task while reading stdout here, so a child
        // that fills one pipe's buffer while we block on the other cannot
        // deadlock the runtime thread.
        let stderr_reader = child.stderr.take().map(|mut stderr| {
            crate::spawn(async move {
                let mut buf = Vec::new();
                stderr.read_to_end(&mut buf).await.map(|_| buf)
            })
        });

        let mut stdout = Vec::new();
        if let Some(out) = child.stdout.as_mut() {
            out.read_to_end(&mut stdout).await?;
        }

        let stderr = match stderr_reader {
            Some(handle) => handle
                .await
                .expect("stderr reader task should not be aborted")?,
            None => Vec::new(),
        };

        let status = child.wait().await?;
        Ok(Output {
            status,
            stdout,
            stderr,
        })
    }
}