tmux_lib/
error.rs

1use std::{io, process::Output};
2
3/// Describes all errors variants from this crate.
4#[derive(thiserror::Error, Debug)]
5pub enum Error {
6    /// A tmux invocation returned some output where none was expected (actions such as
7    /// some `tmux display-message` invocations).
8    #[error(
9        "unexpected process output: intent: `{intent}`, stdout: `{stdout}`, stderr: `{stderr}`"
10    )]
11    UnexpectedTmuxOutput {
12        intent: &'static str,
13        stdout: String,
14        stderr: String,
15    },
16
17    /// Indicates Tmux has a weird config, like missing the `"default-shell"`.
18    #[error("unexpected tmux config: `{0}`")]
19    TmuxConfig(&'static str),
20
21    /// Some parsing error.
22    #[error("failed parsing: `{intent}`")]
23    ParseError {
24        desc: &'static str,
25        intent: &'static str,
26        err: nom::Err<nom::error::Error<String>>,
27    },
28
29    /// Failed parsing the output of a process invocation as utf-8.
30    #[error("failed parsing utf-8 string: `{source}`")]
31    Utf8 {
32        #[from]
33        /// Source error.
34        source: std::string::FromUtf8Error,
35    },
36
37    /// Some IO error.
38    #[error("failed with io: `{source}`")]
39    Io {
40        #[from]
41        /// Source error.
42        source: io::Error,
43    },
44}
45
46/// Convert a nom error into an owned error and add the parsing intent.
47///
48/// # Errors
49///
50/// This maps to a `Error::ParseError`.
51#[must_use]
52pub fn map_add_intent(
53    desc: &'static str,
54    intent: &'static str,
55    nom_err: nom::Err<nom::error::Error<&str>>,
56) -> Error {
57    Error::ParseError {
58        desc,
59        intent,
60        err: nom_err.to_owned(),
61    }
62}
63
64/// Ensure that the output's stdout and stderr are empty, indicating
65/// the command had succeeded.
66///
67/// # Errors
68///
69/// Returns a `Error::UnexpectedTmuxOutput` in case .
70pub fn check_empty_process_output(
71    output: &Output,
72    intent: &'static str,
73) -> std::result::Result<(), Error> {
74    if !output.stdout.is_empty() || !output.stderr.is_empty() {
75        let stdout = String::from_utf8_lossy(&output.stdout[..]).to_string();
76        let stderr = String::from_utf8_lossy(&output.stderr[..]).to_string();
77        return Err(Error::UnexpectedTmuxOutput {
78            intent,
79            stdout,
80            stderr,
81        });
82    }
83    Ok(())
84}