Skip to main content

remove_except/
model.rs

1use std::path::{Path, PathBuf};
2use std::time::SystemTime;
3
4use anyhow::Result;
5
6use crate::error::invalid;
7
8/// A half-open range of modification instants.
9///
10/// The lower bound is inclusive and the upper bound is exclusive. Bounds retain the
11/// precision and range of the supplied `SystemTime` values.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct ModifiedRange {
14    since: Option<SystemTime>,
15    before: Option<SystemTime>,
16}
17
18impl ModifiedRange {
19    /// Constructs a range with at least one bound.
20    ///
21    /// Returns a [`crate::ValidationError`] if both bounds are absent or the lower
22    /// bound is greater than or equal to the upper bound.
23    pub fn new(since: Option<SystemTime>, before: Option<SystemTime>) -> Result<Self> {
24        if since.is_none() && before.is_none() {
25            return Err(invalid("At least one modification-time bound is required"));
26        }
27        if let (Some(since), Some(before)) = (since, before)
28            && since >= before
29        {
30            return Err(invalid("Modification-time start must precede the end"));
31        }
32        Ok(Self { since, before })
33    }
34
35    /// Returns the inclusive lower bound, if specified.
36    pub fn since(&self) -> Option<SystemTime> {
37        self.since
38    }
39
40    /// Returns the exclusive upper bound, if specified.
41    pub fn before(&self) -> Option<SystemTime> {
42        self.before
43    }
44
45    pub(crate) fn contains(&self, time: SystemTime) -> bool {
46        self.since.is_none_or(|since| time >= since)
47            && self.before.is_none_or(|before| time < before)
48    }
49}
50
51/// Optional conditions used while generating a removal plan.
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub struct PlanOptions {
54    modified_range: Option<ModifiedRange>,
55}
56
57impl PlanOptions {
58    /// Constructs options with a modification-time range.
59    pub fn new(modified_range: ModifiedRange) -> Self {
60        Self {
61            modified_range: Some(modified_range),
62        }
63    }
64
65    /// Returns the modification-time range, if specified.
66    pub fn modified_range(&self) -> Option<&ModifiedRange> {
67        self.modified_range.as_ref()
68    }
69}
70
71/// The type of a filesystem item found during traversal.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum ItemType {
74    /// An item other than a directory or symbolic link, including special files.
75    File,
76    /// A directory.
77    Directory,
78    /// A symbolic link. Symbolic links are evaluated as leaf items and never traversed.
79    Symlink,
80}
81
82/// A filesystem item observed during the traversal that created a removal plan.
83///
84/// The traversal is not atomic. Instances are not automatically updated or revalidated if
85/// filesystem contents change during or after planning.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct PlannedItem {
88    /// Absolute path to the item, resolved under the normalized root.
89    /// On Windows, the canonicalized path may include the extended-path prefix `\\?\`.
90    pub(crate) path: PathBuf,
91    /// Path relative to the root, using `/` separators.
92    pub(crate) relative_path: String,
93    /// The type of this item.
94    pub(crate) item_type: ItemType,
95}
96
97impl PlannedItem {
98    /// Returns the absolute path to the item, resolved under the normalized root.
99    ///
100    /// On Windows, the canonicalized path may include the extended-length path prefix (`\\?\`).
101    pub fn path(&self) -> &Path {
102        &self.path
103    }
104
105    /// Returns the item's path relative to the processing root, always normalized with `/` separators.
106    pub fn relative_path(&self) -> &str {
107        &self.relative_path
108    }
109
110    /// Returns the [`ItemType`] classification of this item.
111    pub fn item_type(&self) -> ItemType {
112        self.item_type
113    }
114}
115
116/// An in-memory plan containing items to keep or delete beneath a root directory.
117///
118/// Created by [`crate::build_plan`] or [`crate::build_plan_with_options`]. Constructing or querying a `RemovalPlan` is strictly
119/// read-only and never modifies the filesystem.
120///
121/// # Item Collections
122///
123/// A `RemovalPlan` separates discovered filesystem items into three collections:
124///
125/// - [`keep_items`](RemovalPlan::keep_items): Contains all items directly matched by keep
126///   conditions, plus all ancestor directories required to preserve their paths from the root.
127/// - [`delete_items`](RemovalPlan::delete_items): Contains every individual item targeted for
128///   deletion. This comprehensive list is suitable for full previews, logging, or reporting.
129/// - [`delete_roots`](RemovalPlan::delete_roots): Contains only the top-level deletion targets.
130///   When an entire directory is targeted for deletion, its descendants appear in `delete_items`
131///   but are excluded from `delete_roots`. This minimal set is ideal for executing deletion via
132///   recursive removal routines without redundant operations.
133#[derive(Debug)]
134pub struct RemovalPlan {
135    /// The normalized traversal root. The root itself is not included in the plan.
136    pub(crate) root: PathBuf,
137    /// Number of items directly matching all keep conditions; ancestors alone are not counted.
138    pub(crate) direct_match_count: usize,
139    pub(crate) modified_range: Option<ModifiedRange>,
140    /// Items to keep and their ancestors, sorted by relative path.
141    pub(crate) keep_items: Vec<PlannedItem>,
142    /// All deletion targets, sorted by relative path.
143    pub(crate) delete_items: Vec<PlannedItem>,
144    /// Top-level items used for deletion. Descendants of deletion-target directories are excluded.
145    pub(crate) delete_roots: Vec<PlannedItem>,
146}
147
148impl RemovalPlan {
149    /// Returns the normalized root directory of the plan.
150    ///
151    /// The root directory itself is never included in any keep or delete list.
152    pub fn root(&self) -> &Path {
153        &self.root
154    }
155
156    /// Returns the number of items that directly matched all keep conditions.
157    ///
158    /// Directories kept solely because they are ancestors of matched items are not
159    /// included in this count.
160    pub fn direct_match_count(&self) -> usize {
161        self.direct_match_count
162    }
163
164    /// Returns the modification-time range used to create the plan, if specified.
165    pub fn modified_range(&self) -> Option<&ModifiedRange> {
166        self.modified_range.as_ref()
167    }
168
169    /// Returns all kept items and their required ancestor directories, sorted by relative path.
170    pub fn keep_items(&self) -> &[PlannedItem] {
171        &self.keep_items
172    }
173
174    /// Returns all items targeted for deletion, sorted by relative path.
175    ///
176    /// This is the complete, exhaustive list of all deletion targets, including items inside
177    /// directories that will be removed.
178    pub fn delete_items(&self) -> &[PlannedItem] {
179        &self.delete_items
180    }
181
182    /// Returns the minimal top-level items targeted for deletion, sorted by relative path.
183    ///
184    /// If a directory is targeted for deletion, the directory itself is included in this list,
185    /// but its child items are omitted. This provides the minimal set of targets needed to
186    /// execute recursive deletion safely and efficiently.
187    pub fn delete_roots(&self) -> &[PlannedItem] {
188        &self.delete_roots
189    }
190}