term_transcript/term/
mod.rs

1use std::borrow::Cow;
2
3use crate::{utils::normalize_newlines, TermError};
4
5mod parser;
6#[cfg(test)]
7mod tests;
8
9pub(crate) use self::parser::TermOutputParser;
10
11/// Marker trait for supported types of terminal output.
12pub trait TermOutput: Clone + Send + Sync + 'static {}
13
14/// Output captured from the terminal.
15#[derive(Debug, Clone)]
16pub struct Captured(String);
17
18impl AsRef<str> for Captured {
19    fn as_ref(&self) -> &str {
20        &self.0
21    }
22}
23
24impl From<String> for Captured {
25    fn from(raw: String) -> Self {
26        // Normalize newlines to `\n`.
27        Self(match normalize_newlines(&raw) {
28            Cow::Owned(normalized) => normalized,
29            Cow::Borrowed(_) => raw,
30        })
31    }
32}
33
34impl Captured {
35    fn write_as_plaintext(&self, output: &mut String) -> Result<(), TermError> {
36        TermOutputParser::new(output).parse(self.0.as_bytes())
37    }
38
39    /// Converts this terminal output to plaintext.
40    ///
41    /// # Errors
42    ///
43    /// Returns an error if there was an issue processing output.
44    pub fn to_plaintext(&self) -> Result<String, TermError> {
45        let mut output = String::with_capacity(self.0.len());
46        self.write_as_plaintext(&mut output)?;
47        Ok(output)
48    }
49}
50
51impl TermOutput for Captured {}