Skip to main content

remove_except/
error.rs

1//! Error classification for invalid roots and keep conditions.
2
3use std::fmt;
4
5/// Marks an error caused by an invalid processing root or invalid keep conditions.
6///
7/// [`crate::build_plan`] returns [`anyhow::Error`] values. When the failure was caused by
8/// the caller's input rather than by filesystem traversal, the error carries a
9/// `ValidationError`, which can be detected with [`anyhow::Error::downcast_ref`]:
10///
11/// ```
12/// use remove_except::{ValidationError, build_plan};
13///
14/// let error = build_plan(std::path::Path::new("."), &[]).unwrap_err();
15/// assert!(error.downcast_ref::<ValidationError>().is_some());
16/// ```
17///
18/// Validation errors include missing conditions, empty patterns, invalid time ranges, invalid glob syntax, patterns that
19/// escape the processing root, Windows drive-relative paths, and roots that cannot be
20/// resolved, are not directories, or are filesystem roots. Errors while walking beneath a
21/// valid root are not validation errors. The message text is not a stable API contract.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ValidationError {
24    message: String,
25}
26
27impl ValidationError {
28    pub(crate) fn new(message: impl Into<String>) -> Self {
29        Self {
30            message: message.into(),
31        }
32    }
33}
34
35impl fmt::Display for ValidationError {
36    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37        formatter.write_str(&self.message)
38    }
39}
40
41impl std::error::Error for ValidationError {}
42
43/// Creates an `anyhow::Error` classified as a validation error.
44pub(crate) fn invalid(message: impl Into<String>) -> anyhow::Error {
45    ValidationError::new(message).into()
46}
47
48/// Wraps an underlying error with a validation-error context.
49pub(crate) fn invalid_with_source<E>(source: E, message: impl Into<String>) -> anyhow::Error
50where
51    E: std::error::Error + Send + Sync + 'static,
52{
53    anyhow::Error::new(source).context(ValidationError::new(message))
54}