Skip to main content

bare_script/
output.rs

1//! Command output types.
2
3use std::fmt;
4use std::process::ExitStatus;
5
6/// Represents the output of an executed command.
7#[derive(Debug, Clone)]
8pub struct Output {
9    stdout: Vec<u8>,
10    stderr: Vec<u8>,
11    status: ExitStatus,
12}
13
14impl Output {
15    /// Creates a new `Output` from raw components.
16    pub fn new(stdout: Vec<u8>, stderr: Vec<u8>, status: ExitStatus) -> Self {
17        Self {
18            stdout,
19            stderr,
20            status,
21        }
22    }
23
24    /// Returns the standard output as bytes.
25    #[inline]
26    pub fn stdout(&self) -> &[u8] {
27        &self.stdout
28    }
29
30    /// Returns the standard error as bytes.
31    #[inline]
32    pub fn stderr(&self) -> &[u8] {
33        &self.stderr
34    }
35
36    /// Returns the exit status of the command.
37    #[inline]
38    pub fn status(&self) -> ExitStatus {
39        self.status
40    }
41
42    /// Returns the stdout output as a string, lossily converting UTF-8 bytes.
43    #[inline]
44    pub fn stdout_str(&self) -> String {
45        String::from_utf8_lossy(&self.stdout).into_owned()
46    }
47
48    /// Returns the stderr output as a string, lossily converting UTF-8 bytes.
49    #[inline]
50    pub fn stderr_str(&self) -> String {
51        String::from_utf8_lossy(&self.stderr).into_owned()
52    }
53
54    /// Returns `true` if the command exited successfully (code 0).
55    #[inline]
56    pub fn success(&self) -> bool {
57        self.status.success()
58    }
59
60    /// Returns the exit code of the command, if available.
61    #[inline]
62    pub fn code(&self) -> Option<i32> {
63        self.status.code()
64    }
65}
66
67impl fmt::Display for Output {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        write!(f, "{}", self.stdout_str())
70    }
71}