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/// A half-open range of file sizes in bytes.
52///
53/// The lower bound is inclusive and the upper bound is exclusive. File sizes are
54/// logical lengths reported by filesystem metadata.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct SizeRange {
57 at_least: Option<u64>,
58 below: Option<u64>,
59}
60
61impl SizeRange {
62 /// Constructs a size range with at least one bound.
63 ///
64 /// Returns a [`crate::ValidationError`] if both bounds are absent, the exclusive
65 /// upper bound is zero, or the lower bound is greater than or equal to the upper bound.
66 pub fn new(at_least: Option<u64>, below: Option<u64>) -> Result<Self> {
67 if at_least.is_none() && below.is_none() {
68 return Err(invalid("At least one file-size bound is required"));
69 }
70 if below == Some(0) {
71 return Err(invalid("File-size upper bound must be greater than zero"));
72 }
73 if let (Some(at_least), Some(below)) = (at_least, below)
74 && at_least >= below
75 {
76 return Err(invalid(
77 "File-size lower bound must be less than the upper bound",
78 ));
79 }
80 Ok(Self { at_least, below })
81 }
82
83 /// Returns the inclusive lower bound in bytes, if specified.
84 pub fn at_least(&self) -> Option<u64> {
85 self.at_least
86 }
87
88 /// Returns the exclusive upper bound in bytes, if specified.
89 pub fn below(&self) -> Option<u64> {
90 self.below
91 }
92
93 pub(crate) fn contains(&self, size: u64) -> bool {
94 self.at_least.is_none_or(|at_least| size >= at_least)
95 && self.below.is_none_or(|below| size < below)
96 }
97}
98
99/// Optional conditions used while generating a removal plan.
100#[derive(Debug, Clone, Default, PartialEq, Eq)]
101pub struct PlanOptions {
102 modified_range: Option<ModifiedRange>,
103 size_range: Option<SizeRange>,
104}
105
106impl PlanOptions {
107 /// Constructs options with a modification-time range.
108 pub fn new(modified_range: ModifiedRange) -> Self {
109 Self {
110 modified_range: Some(modified_range),
111 size_range: None,
112 }
113 }
114
115 /// Adds a file-size range to these options.
116 ///
117 /// This can be used with [`PlanOptions::default`] for size-only selection or chained
118 /// after [`PlanOptions::new`] to combine size and modification-time conditions.
119 pub fn with_size_range(mut self, size_range: SizeRange) -> Self {
120 self.size_range = Some(size_range);
121 self
122 }
123
124 /// Returns the modification-time range, if specified.
125 pub fn modified_range(&self) -> Option<&ModifiedRange> {
126 self.modified_range.as_ref()
127 }
128
129 /// Returns the file-size range, if specified.
130 pub fn size_range(&self) -> Option<&SizeRange> {
131 self.size_range.as_ref()
132 }
133}
134
135/// The type of a filesystem item found during traversal.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum ItemType {
138 /// An item other than a directory or symbolic link, including special files.
139 File,
140 /// A directory.
141 Directory,
142 /// A symbolic link. Symbolic links are evaluated as leaf items and never traversed.
143 Symlink,
144}
145
146/// A filesystem item observed during the traversal that created a removal plan.
147///
148/// The traversal is not atomic. Instances are not automatically updated or revalidated if
149/// filesystem contents change during or after planning.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct PlannedItem {
152 /// Absolute path to the item, resolved under the normalized root.
153 /// On Windows, the canonicalized path may include the extended-path prefix `\\?\`.
154 pub(crate) path: PathBuf,
155 /// Path relative to the root, using `/` separators.
156 pub(crate) relative_path: String,
157 /// The type of this item.
158 pub(crate) item_type: ItemType,
159}
160
161impl PlannedItem {
162 /// Returns the absolute path to the item, resolved under the normalized root.
163 ///
164 /// On Windows, the canonicalized path may include the extended-length path prefix (`\\?\`).
165 pub fn path(&self) -> &Path {
166 &self.path
167 }
168
169 /// Returns the item's path relative to the processing root, always normalized with `/` separators.
170 pub fn relative_path(&self) -> &str {
171 &self.relative_path
172 }
173
174 /// Returns the [`ItemType`] classification of this item.
175 pub fn item_type(&self) -> ItemType {
176 self.item_type
177 }
178}
179
180/// An in-memory plan containing items to keep or delete beneath a root directory.
181///
182/// Created by [`crate::build_plan`] or [`crate::build_plan_with_options`]. Constructing or querying a `RemovalPlan` is strictly
183/// read-only and never modifies the filesystem.
184///
185/// # Item Collections
186///
187/// A `RemovalPlan` separates discovered filesystem items into three collections:
188///
189/// - [`keep_items`](RemovalPlan::keep_items): Contains all items directly matched by keep
190/// conditions, plus all ancestor directories required to preserve their paths from the root.
191/// - [`delete_items`](RemovalPlan::delete_items): Contains every individual item targeted for
192/// deletion. This comprehensive list is suitable for full previews, logging, or reporting.
193/// - [`delete_roots`](RemovalPlan::delete_roots): Contains only the top-level deletion targets.
194/// When an entire directory is targeted for deletion, its descendants appear in `delete_items`
195/// but are excluded from `delete_roots`. This minimal set is ideal for executing deletion via
196/// recursive removal routines without redundant operations.
197#[derive(Debug)]
198pub struct RemovalPlan {
199 /// The normalized traversal root. The root itself is not included in the plan.
200 pub(crate) root: PathBuf,
201 /// Number of items directly matching all keep conditions; ancestors alone are not counted.
202 pub(crate) direct_match_count: usize,
203 pub(crate) modified_range: Option<ModifiedRange>,
204 pub(crate) size_range: Option<SizeRange>,
205 /// Items to keep and their ancestors, sorted by relative path.
206 pub(crate) keep_items: Vec<PlannedItem>,
207 /// All deletion targets, sorted by relative path.
208 pub(crate) delete_items: Vec<PlannedItem>,
209 /// Top-level items used for deletion. Descendants of deletion-target directories are excluded.
210 pub(crate) delete_roots: Vec<PlannedItem>,
211}
212
213impl RemovalPlan {
214 /// Returns the normalized root directory of the plan.
215 ///
216 /// The root directory itself is never included in any keep or delete list.
217 pub fn root(&self) -> &Path {
218 &self.root
219 }
220
221 /// Returns the number of items that directly matched all keep conditions.
222 ///
223 /// Directories kept solely because they are ancestors of matched items are not
224 /// included in this count.
225 pub fn direct_match_count(&self) -> usize {
226 self.direct_match_count
227 }
228
229 /// Returns the modification-time range used to create the plan, if specified.
230 pub fn modified_range(&self) -> Option<&ModifiedRange> {
231 self.modified_range.as_ref()
232 }
233
234 /// Returns the file-size range used to create the plan, if specified.
235 pub fn size_range(&self) -> Option<&SizeRange> {
236 self.size_range.as_ref()
237 }
238
239 /// Returns all kept items and their required ancestor directories, sorted by relative path.
240 pub fn keep_items(&self) -> &[PlannedItem] {
241 &self.keep_items
242 }
243
244 /// Returns all items targeted for deletion, sorted by relative path.
245 ///
246 /// This is the complete, exhaustive list of all deletion targets, including items inside
247 /// directories that will be removed.
248 pub fn delete_items(&self) -> &[PlannedItem] {
249 &self.delete_items
250 }
251
252 /// Returns the minimal top-level items targeted for deletion, sorted by relative path.
253 ///
254 /// If a directory is targeted for deletion, the directory itself is included in this list,
255 /// but its child items are omitted. This provides the minimal set of targets needed to
256 /// execute recursive deletion safely and efficiently.
257 pub fn delete_roots(&self) -> &[PlannedItem] {
258 &self.delete_roots
259 }
260}