use std::fmt;
use std::io;
use std::path::PathBuf;
use crate::closed_enum::closed_enum;
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum RestoreKind {
NotNeeded => "not_needed",
Restored => "restored",
Failed => "failed",
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum Restore {
NotNeeded,
Restored,
Failed {
backup: PathBuf,
error: io::Error,
},
}
impl Restore {
#[must_use]
pub const fn original_is_intact(&self) -> bool {
matches!(self, Self::NotNeeded | Self::Restored)
}
#[must_use]
pub const fn kind(&self) -> RestoreKind {
match self {
Self::NotNeeded => RestoreKind::NotNeeded,
Self::Restored => RestoreKind::Restored,
Self::Failed { .. } => RestoreKind::Failed,
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct StagingLeftover {
pub path: PathBuf,
}
impl StagingLeftover {
#[must_use]
pub const fn new(path: PathBuf) -> Self {
Self { path }
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ReplaceFailure {
pub error: io::Error,
pub restore: Restore,
pub leftover: Option<StagingLeftover>,
}
impl ReplaceFailure {
#[must_use]
pub const fn new(
error: io::Error,
restore: Restore,
leftover: Option<StagingLeftover>,
) -> Self {
Self {
error,
restore,
leftover,
}
}
}
impl ReplaceFailure {
pub(crate) fn redacted_description(&self) -> String {
use super::redaction::sanitize_io_error_for_error;
use super::redaction::sanitize_path_for_error;
let head = format!(
"failed to replace the destination: {}",
sanitize_io_error_for_error(&self.error)
);
let restore = match &self.restore {
Restore::NotNeeded => format!("{head}; the original destination is unchanged"),
Restore::Restored => format!("{head}; the original destination was restored"),
Restore::Failed { backup, error } => format!(
"{head}; restoring the original destination failed ({}), it remains at {}",
sanitize_io_error_for_error(error),
sanitize_path_for_error(backup)
),
};
match &self.leftover {
Some(leftover) => format!(
"{restore}; a staging directory remains at {}",
sanitize_path_for_error(&leftover.path)
),
None => restore,
}
}
}
impl fmt::Display for ReplaceFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "failed to replace the destination: {}", self.error)?;
match &self.restore {
Restore::NotNeeded => f.write_str("; the original destination is unchanged")?,
Restore::Restored => f.write_str("; the original destination was restored")?,
Restore::Failed { backup, error } => write!(
f,
"; restoring the original destination failed ({error}), it remains at {}",
backup.display()
)?,
}
self.leftover.as_ref().map_or(Ok(()), |leftover| {
write!(
f,
"; a staging directory remains at {}",
leftover.path.display()
)
})
}
}
impl std::error::Error for ReplaceFailure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}