command_error/output_conversion_error.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
use std::fmt::Debug;
use std::fmt::Display;
#[cfg(doc)]
use std::process::Command;
#[cfg(doc)]
use std::process::Output;
use crate::CommandDisplay;
#[cfg(doc)]
use crate::CommandExt;
#[cfg(feature = "miette")]
use miette::Diagnostic;
#[cfg(doc)]
use utf8_command::Utf8Output;
/// An error produced when attempting to convert [`Command`] [`Output`] to a custom format (such as
/// [`Utf8Output`]).
///
/// Produced by methods like [`CommandExt::output_checked_with`] and
/// [`CommandExt::output_checked_utf8`].
///
/// ```
/// # use pretty_assertions::assert_eq;
/// # use indoc::indoc;
/// # use std::process::Command;
/// # use std::process::Output;
/// # use std::process::ExitStatus;
/// # use command_error::Utf8ProgramAndArgs;
/// # use command_error::CommandDisplay;
/// # use command_error::OutputConversionError;
/// let mut command = Command::new("sh");
/// command.args(["-c", "echo puppy doggy"]);
/// let displayed: Utf8ProgramAndArgs = (&command).into();
/// let mut output = command.output().unwrap();
/// output.stdout[5] = 0xc0; // Invalid UTF-8 byte.
/// let inner: Result<utf8_command::Utf8Output, _> = output.try_into();
/// let error = OutputConversionError::new(
/// Box::new(displayed),
/// Box::new(inner.unwrap_err())
/// );
/// assert_eq!(
/// error.to_string(),
/// "Failed to convert `sh` output: \
/// Stdout contained invalid utf-8 sequence of 1 bytes from index 5: \
/// \"puppy�doggy\\n\""
/// );
/// ```
pub struct OutputConversionError {
pub(crate) command: Box<dyn CommandDisplay + Send + Sync>,
pub(crate) inner: Box<dyn Display + Send + Sync>,
}
impl OutputConversionError {
/// Construct a new [`OutputConversionError`].
pub fn new(
command: Box<dyn CommandDisplay + Send + Sync>,
inner: Box<dyn Display + Send + Sync>,
) -> Self {
Self { command, inner }
}
}
impl Debug for OutputConversionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OutputConversionError")
.field("program", &self.command.program())
.field("inner", &self.inner.to_string())
.finish()
}
}
impl Display for OutputConversionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Failed to convert `{}` output: {}",
self.command.program_quoted(),
self.inner
)
}
}
impl std::error::Error for OutputConversionError {}
#[cfg(feature = "miette")]
impl Diagnostic for OutputConversionError {}
#[cfg(test)]
mod tests {
use super::*;
use static_assertions::assert_impl_all;
assert_impl_all!(OutputConversionError: Send, Sync);
}