Skip to main content

remove_except/
lib.rs

1#![warn(missing_docs)]
2
3//! Safe removal plan generation for cleaning directories while keeping specified items.
4//!
5//! `remove-except` scans beneath a chosen processing root, compares discovered filesystem
6//! items against keep patterns and optional modification-time and file-size bounds, and creates an
7//! in-memory [`RemovalPlan`].
8//! The plan partitions items into kept entries (including required ancestor directories)
9//! and deletion targets.
10//!
11//! # Safety by Design
12//!
13//! - **Separation of Planning and Deletion**: [`build_plan`] is strictly read-only.
14//!   It records an in-memory plan from entries observed during traversal. The traversal is not
15//!   an atomic or protected filesystem snapshot and does not lock or prevent concurrent changes.
16//!   It does not create, modify, or delete any files or directories.
17//! - **Root Protection**: The processing root itself is never included in the plan,
18//!   and filesystem roots (such as `/` on Unix or `C:\` on Windows) are rejected to prevent
19//!   catastrophic deletion.
20//! - **No Symlink Traversal**: Symbolic links encountered beneath the root are never followed.
21//!   Each link is evaluated as an individual leaf item; if targeted for deletion, only the
22//!   symbolic link itself is deleted, never its target.
23//! - **Unambiguous Paths**: The normalized root and every scanned entry path must be
24//!   representable as Unicode. Otherwise, planning fails without returning a partial plan.
25//!
26//! # Pattern Matching Syntax and Semantics
27//!
28//! [`build_plan`] requires at least one keep pattern. [`build_plan_with_options`] also
29//! accepts modification-time and/or file-size ranges without patterns. Multiple patterns
30//! use OR, while each range is combined with the pattern condition and other ranges using AND.
31//! When either range is present, only matching regular files and their ancestors are kept.
32//! The following pattern retention rules describe behavior without a time or size range:
33//!
34//! - `*` matches any sequence of non-separator characters within a single directory component.
35//! - `?` matches one Unicode scalar value other than a separator. A character class also
36//!   matches one Unicode scalar value; combining sequences can therefore require multiple
37//!   wildcards.
38//! - `**` matches zero or more directory levels.
39//! - `[...]` matches any character in the character class, adhering to standard glob rules.
40//! - `{a,b}` matches any of the comma-separated alternatives.
41//! - `.` or `./` represents the processing root and keeps everything beneath it.
42//! - A directory path without glob syntax keeps that directory and all of its contents
43//!   recursively. Glob syntax is `*`, `?`, `[`, `{`, and `}`; on non-Windows platforms,
44//!   `\` is also glob syntax because it escapes the next character. On Windows, `\` is a
45//!   path separator.
46//! - A glob match keeps the matching item and all required ancestor directories up to the root,
47//!   but does *not* recursively keep unmatched descendants. For instance, `dir/*` matches
48//!   items directly beneath `dir/`, but does not recursively keep unmatched contents of
49//!   subdirectories beneath them. Likewise, `dir/**` does not match `dir` itself, and an
50//!   escaped name such as `backup[[]2025]` keeps only that directory; append `/**` to keep
51//!   its contents.
52//! - Relative patterns are resolved relative to the processing root. Patterns containing a
53//!   `..` component are rejected.
54//! - Leading and trailing whitespace in patterns is preserved.
55//!
56//! # Platform Differences
57//!
58//! - **Windows**: Path matching uses Unicode simple case folding (non-Turkic), ignoring
59//!   per-directory NTFS case-sensitivity settings.
60//! - **Ubuntu**: Path matching is strictly case-sensitive. Windows and Ubuntu are the
61//!   supported platforms.
62//!
63//! # Examples
64//!
65//! ```
66//! use remove_except::build_plan;
67//! use std::fs::{self, File};
68//!
69//! let temp_dir = assert_fs::TempDir::new().unwrap();
70//! let root = temp_dir.path();
71//! fs::create_dir_all(root.join("src")).unwrap();
72//! File::create(root.join("src/main.rs")).unwrap();
73//! File::create(root.join("notes.txt")).unwrap();
74//!
75//! // Build a removal plan keeping only files inside `src/`:
76//! let plan = build_plan(root, &["src/**".to_owned()])
77//!     .expect("valid root and keep patterns");
78//!
79//! // The plan identifies kept items and ancestors:
80//! assert!(plan.keep_items().iter().any(|item| item.relative_path() == "src/main.rs"));
81//! assert!(plan.keep_items().iter().any(|item| item.relative_path() == "src"));
82//!
83//! // Deletion roots identify top-level removal targets:
84//! assert!(plan.delete_roots().iter().any(|item| item.relative_path() == "notes.txt"));
85//! ```
86
87use std::path::{Path, PathBuf};
88
89use anyhow::{Context, Result};
90use walkdir::WalkDir;
91
92mod error;
93mod metadata;
94mod model;
95mod path;
96mod pattern;
97
98pub use error::ValidationError;
99use error::{invalid, invalid_with_source};
100pub use model::{ItemType, ModifiedRange, PlanOptions, PlannedItem, RemovalPlan, SizeRange};
101use path::{display_path, ensure_unicode_path, is_drive_relative_path, is_filesystem_root};
102use pattern::compile_patterns;
103
104/// Scans beneath the specified root directory and constructs a [`RemovalPlan`].
105///
106/// Discovered filesystem entries are evaluated against the provided `patterns`. An item is
107/// kept if it matches any pattern (logical OR). When an item is kept, all of its ancestor
108/// directories up to `root` are also kept to preserve directory hierarchy.
109///
110/// # Arguments
111///
112/// * `root` - Path to the directory to scan. Relative paths are resolved against the current
113///   working directory. Filesystem roots (e.g. `/` on Unix, `C:\` on Windows) and Windows
114///   drive-relative paths (e.g. `C:foo`) are rejected.
115/// * `patterns` - One or more keep patterns. Patterns may be literal relative paths or glob
116///   patterns (`*`, `?`, `**`, `[...]`, `{a,b}`; on non-Windows platforms `\` escapes the
117///   next character). `?` and a character class each match one Unicode scalar value.
118///   Literal directories without glob syntax match recursively; glob matches do not keep
119///   unmatched descendants. Relative patterns are resolved relative to `root`. Patterns
120///   containing a `..` component are rejected. Leading and trailing whitespace is preserved.
121///
122/// # Safety and Behavior
123///
124/// - **Read-Only**: This function only traverses and reads directory metadata. It does not
125///   modify, create, or delete any files.
126/// - **No Symlink Traversal**: Symbolic links beneath `root` are treated as individual leaf
127///   items and are never followed.
128/// - **Root Exclusion**: The `root` directory itself is never included in the plan.
129/// - **Unicode Paths**: The normalized root and every scanned entry path must be
130///   representable as Unicode, regardless of whether an entry would be kept or deleted.
131///   Link targets beneath `root` are not checked because those links are not followed.
132/// - **Observed Entries**: The plan contains entries observed during traversal. The traversal
133///   is not atomic and does not lock or prevent concurrent filesystem changes. The plan is not
134///   refreshed if the filesystem changes after construction.
135///
136/// # Errors
137///
138/// Returns an error in the following circumstances (exact error message strings are not part
139/// of the stable API contract):
140///
141/// - **Pattern errors**: `patterns` is empty, a pattern contains invalid glob syntax, or a
142///   pattern escapes `root` (e.g., starts with `../` or resolves to an ancestor).
143/// - **Root errors**: `root` cannot be resolved, is not a directory, is a filesystem root,
144///   or is a Windows drive-relative path.
145/// - **I/O errors**: Directory traversal fails due to filesystem permissions or I/O errors.
146/// - **Path encoding errors**: The normalized root or a scanned entry path cannot be
147///   represented as Unicode. No partial plan is returned, even if all entries would be kept.
148///
149/// Pattern and root validation errors carry a [`ValidationError`] that can be detected with
150/// [`anyhow::Error::downcast_ref`]. Traversal and path encoding errors do not.
151///
152/// # Examples
153///
154/// ```
155/// use remove_except::build_plan;
156/// use std::fs::{self, File};
157///
158/// let temp_dir = assert_fs::TempDir::new().unwrap();
159/// let root = temp_dir.path();
160/// fs::create_dir_all(root.join("docs")).unwrap();
161/// File::create(root.join("docs/guide.md")).unwrap();
162/// File::create(root.join("temp.log")).unwrap();
163///
164/// let plan = build_plan(root, &["docs/**".to_owned()])
165///     .expect("plan construction should succeed");
166///
167/// assert_eq!(plan.direct_match_count(), 1);
168/// assert!(plan.keep_items().iter().any(|item| item.relative_path() == "docs/guide.md"));
169/// assert!(plan.delete_roots().iter().any(|item| item.relative_path() == "temp.log"));
170/// ```
171pub fn build_plan(root: &Path, patterns: &[String]) -> Result<RemovalPlan> {
172    build_plan_with_options(root, patterns, &PlanOptions::default())
173}
174
175/// Builds a read-only removal plan with optional modification-time and file-size filtering.
176///
177/// Patterns are combined with OR. Each specified time or size range is combined with the
178/// pattern condition and other ranges using AND. When any range is present, only regular
179/// files satisfying every keep condition directly match; their ancestors are retained.
180/// An empty pattern list omits the pattern condition, but at least one pattern or range
181/// is required. Without ranges, behavior matches [`build_plan`].
182///
183/// This operation does not follow child symbolic links and does not provide a filesystem
184/// snapshot. Size bounds compare logical file lengths in bytes. A failure to obtain required
185/// metadata aborts the entire plan.
186///
187/// # Errors
188///
189/// Invalid conditions, roots, and patterns carry [`ValidationError`]; traversal, metadata,
190/// and path-encoding failures are runtime errors. No partial plan is returned.
191pub fn build_plan_with_options(
192    root: &Path,
193    patterns: &[String],
194    options: &PlanOptions,
195) -> Result<RemovalPlan> {
196    build_plan_with_metadata(root, patterns, options, metadata::file_metadata)
197}
198
199fn build_plan_with_metadata(
200    root: &Path,
201    patterns: &[String],
202    options: &PlanOptions,
203    mut read_metadata: impl FnMut(&Path, bool) -> Result<metadata::FileMetadata>,
204) -> Result<RemovalPlan> {
205    let has_filter = options.modified_range().is_some() || options.size_range().is_some();
206    if patterns.is_empty() && !has_filter {
207        return Err(invalid(
208            "At least one pattern, modification-time bound, or file-size bound is required",
209        ));
210    }
211    if is_drive_relative_path(&root.to_string_lossy()) {
212        return Err(invalid(format!(
213            "Drive-relative root paths are not supported: {}",
214            root.display()
215        )));
216    }
217
218    let root = std::fs::canonicalize(root).map_err(|error| {
219        invalid_with_source(
220            error,
221            format!("Failed to resolve root directory: {}", root.display()),
222        )
223    })?;
224    if is_filesystem_root(&root) {
225        return Err(invalid(format!(
226            "Filesystem roots cannot be used as processing roots: {}",
227            root.display()
228        )));
229    }
230    if !root.is_dir() {
231        return Err(invalid(format!(
232            "Root path is not a directory: {}",
233            root.display()
234        )));
235    }
236
237    ensure_unicode_path(&root)?;
238    let compiled_patterns = if patterns.is_empty() {
239        None
240    } else {
241        Some(compile_patterns(&root, patterns)?)
242    };
243    let mut entries = Vec::new();
244    // WalkDir yields entries depth-first, so retain indices of the current item's ancestors.
245    let mut directory_stack = Vec::new();
246    let mut direct_match_count = 0;
247
248    for entry in WalkDir::new(&root).follow_links(false).min_depth(1) {
249        let entry = entry.with_context(|| "Failed to walk root directory")?;
250        let depth = entry.depth();
251        directory_stack.truncate(depth.saturating_sub(1));
252        // Parents are visited before children, so a parent's index is always smaller.
253        let parent_index = directory_stack.last().copied();
254        let file_type = entry.file_type();
255        let path = entry.path().to_path_buf();
256        ensure_unicode_path(&path)?;
257        let relative = path
258            .strip_prefix(&root)
259            .context("Walked path escaped the root directory")?;
260        let relative_path = display_path(relative);
261        let pattern_matched = compiled_patterns
262            .as_ref()
263            .is_none_or(|patterns| patterns.matches(&relative_path));
264        let matched = if has_filter {
265            if pattern_matched && file_type.is_file() {
266                let metadata = read_metadata(&path, options.modified_range().is_some())?;
267                let modified_matches = if let Some(range) = options.modified_range() {
268                    range.contains(metadata.modified.context(
269                        "Required modification time was not returned by the metadata reader",
270                    )?)
271                } else {
272                    true
273                };
274                let size_matches = options
275                    .size_range()
276                    .is_none_or(|range| range.contains(metadata.size));
277                modified_matches && size_matches
278            } else {
279                false
280            }
281        } else {
282            pattern_matched
283        };
284
285        if matched {
286            direct_match_count += 1;
287        }
288
289        let item_type = if file_type.is_symlink() {
290            ItemType::Symlink
291        } else if file_type.is_dir() {
292            ItemType::Directory
293        } else {
294            ItemType::File
295        };
296        let item_index = entries.len();
297        entries.push(IndexedItem {
298            item: PlannedItem {
299                path,
300                relative_path,
301                item_type,
302            },
303            parent_index,
304            keep: matched,
305            is_delete_root: false,
306        });
307        if item_type == ItemType::Directory {
308            directory_stack.push(item_index);
309        }
310    }
311
312    Ok(finalize_plan(
313        root,
314        direct_match_count,
315        options.modified_range().cloned(),
316        options.size_range().cloned(),
317        entries,
318    ))
319}
320
321/// Derives kept ancestors and top-level deletion items from recorded parent indices.
322fn finalize_plan(
323    root: PathBuf,
324    direct_match_count: usize,
325    modified_range: Option<ModifiedRange>,
326    size_range: Option<SizeRange>,
327    mut entries: Vec<IndexedItem>,
328) -> RemovalPlan {
329    // Children follow parents, so walk in reverse to propagate keep state to ancestors.
330    for index in (0..entries.len()).rev() {
331        if entries[index].keep
332            && let Some(parent_index) = entries[index].parent_index
333        {
334            entries[parent_index].keep = true;
335        }
336    }
337
338    // An unkept item is a deletion root when its parent is kept or is the processing root.
339    for index in 0..entries.len() {
340        let parent_is_kept = entries[index]
341            .parent_index
342            .is_none_or(|parent_index| entries[parent_index].keep);
343        entries[index].is_delete_root = !entries[index].keep && parent_is_kept;
344    }
345
346    entries.sort_unstable_by(|left, right| left.item.relative_path.cmp(&right.item.relative_path));
347    let mut keep_items = Vec::new();
348    let mut delete_items = Vec::new();
349    let mut delete_roots = Vec::new();
350    for entry in entries {
351        if entry.keep {
352            keep_items.push(entry.item);
353        } else {
354            if entry.is_delete_root {
355                delete_roots.push(entry.item.clone());
356            }
357            delete_items.push(entry.item);
358        }
359    }
360
361    RemovalPlan {
362        root,
363        direct_match_count,
364        modified_range,
365        size_range,
366        keep_items,
367        delete_items,
368        delete_roots,
369    }
370}
371
372/// Data used to derive kept ancestors and top-level deletion items from traversal order.
373struct IndexedItem {
374    /// The item included in the public plan.
375    item: PlannedItem,
376    /// Index of the parent directory in traversal order, unless directly under the root.
377    parent_index: Option<usize>,
378    /// Initialized from direct matches and propagated to their ancestors.
379    keep: bool,
380    /// True when this is a top-level item passed to the deletion routine.
381    is_delete_root: bool,
382}
383
384#[cfg(test)]
385mod tests {
386    #[cfg(windows)]
387    use super::path::is_drive_relative_path;
388    #[cfg(windows)]
389    use super::pattern::normalize_pattern;
390    use super::{ItemType, build_plan, is_filesystem_root};
391    use assert_fs::prelude::*;
392    use std::path::Path;
393
394    fn file_metadata(
395        size: u64,
396        modified: Option<std::time::SystemTime>,
397    ) -> super::metadata::FileMetadata {
398        super::metadata::FileMetadata { size, modified }
399    }
400
401    #[test]
402    fn modification_time_is_requested_only_for_pattern_matching_regular_files() {
403        use super::{ModifiedRange, PlanOptions, build_plan_with_metadata};
404        use std::time::{Duration, SystemTime};
405
406        let temp = assert_fs::TempDir::new().unwrap();
407        temp.child("folder/selected.txt")
408            .write_str("selected")
409            .unwrap();
410        temp.child("folder/other.txt").write_str("other").unwrap();
411        let options =
412            PlanOptions::new(ModifiedRange::new(Some(SystemTime::UNIX_EPOCH), None).unwrap());
413        let mut observed = Vec::new();
414        let plan = build_plan_with_metadata(
415            temp.path(),
416            &["folder/selected.txt".to_owned()],
417            &options,
418            |path, read_modified| {
419                assert!(read_modified);
420                observed.push(path.file_name().unwrap().to_owned());
421                Ok(file_metadata(
422                    8,
423                    Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
424                ))
425            },
426        )
427        .unwrap();
428        assert_eq!(observed, [std::ffi::OsString::from("selected.txt")]);
429        assert_eq!(plan.direct_match_count(), 1);
430        let mut observed = Vec::new();
431        let plan = build_plan_with_metadata(
432            temp.path(),
433            &[".".to_owned()],
434            &options,
435            |path, read_modified| {
436                assert!(read_modified);
437                observed.push(path.file_name().unwrap().to_owned());
438                Ok(file_metadata(
439                    8,
440                    Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
441                ))
442            },
443        )
444        .unwrap();
445        observed.sort();
446        assert_eq!(
447            observed,
448            [
449                std::ffi::OsString::from("other.txt"),
450                std::ffi::OsString::from("selected.txt")
451            ]
452        );
453        assert_eq!(plan.direct_match_count(), 2);
454        let error = build_plan_with_metadata(
455            temp.path(),
456            &["folder/selected.txt".to_owned()],
457            &options,
458            |_, _| Err(anyhow::anyhow!("injected metadata failure")),
459        )
460        .unwrap_err();
461        assert!(error.to_string().contains("injected metadata failure"));
462        assert!(error.downcast_ref::<super::ValidationError>().is_none());
463        temp.child("folder/selected.txt").assert("selected");
464        temp.child("folder/other.txt").assert("other");
465        build_plan_with_metadata(
466            temp.path(),
467            &[".".to_owned()],
468            &PlanOptions::default(),
469            |_, _| panic!("metadata must not be read without a time or size condition"),
470        )
471        .unwrap();
472    }
473
474    #[test]
475    fn size_only_reads_metadata_for_matching_regular_files_without_mtime() {
476        use super::{PlanOptions, SizeRange, build_plan_with_metadata};
477
478        let temp = assert_fs::TempDir::new().unwrap();
479        temp.child("selected.txt").write_str("selected").unwrap();
480        temp.child("other.txt").write_str("other").unwrap();
481        let options =
482            PlanOptions::default().with_size_range(SizeRange::new(Some(8), None).unwrap());
483        let mut observed = Vec::new();
484        let plan = build_plan_with_metadata(
485            temp.path(),
486            &["selected.txt".to_owned()],
487            &options,
488            |path, read_modified| {
489                assert!(!read_modified);
490                observed.push(path.file_name().unwrap().to_owned());
491                Ok(file_metadata(8, None))
492            },
493        )
494        .unwrap();
495        assert_eq!(observed, [std::ffi::OsString::from("selected.txt")]);
496        assert_eq!(plan.direct_match_count(), 1);
497        assert_eq!(plan.size_range(), options.size_range());
498    }
499
500    #[test]
501    fn size_filter_does_not_match_directories_or_follow_symlinks() {
502        use super::{PlanOptions, SizeRange, build_plan_with_metadata};
503
504        let temp = assert_fs::TempDir::new().unwrap();
505        let outside = assert_fs::TempDir::new().unwrap();
506        let target = outside.child("target.txt");
507        target.write_str("target").unwrap();
508        temp.child("empty").create_dir_all().unwrap();
509        let link = temp.path().join("link");
510        #[cfg(unix)]
511        let link_result = std::os::unix::fs::symlink(target.path(), &link);
512        #[cfg(windows)]
513        let link_result = std::os::windows::fs::symlink_file(target.path(), &link);
514        link_result.expect("creating the symbolic-link fixture is required for this test");
515
516        let options =
517            PlanOptions::default().with_size_range(SizeRange::new(Some(0), None).unwrap());
518        let plan = build_plan_with_metadata(temp.path(), &[".".to_owned()], &options, |_, _| {
519            panic!("metadata must not be read for directories or symlinks")
520        })
521        .unwrap();
522        assert_eq!(plan.direct_match_count(), 0);
523        assert_eq!(
524            plan.delete_items()
525                .iter()
526                .map(|item| (item.relative_path(), item.item_type()))
527                .collect::<Vec<_>>(),
528            [("empty", ItemType::Directory), ("link", ItemType::Symlink)]
529        );
530        target.assert("target");
531    }
532
533    #[test]
534    fn combined_ranges_read_metadata_once_per_matching_regular_file() {
535        use super::{ModifiedRange, PlanOptions, SizeRange, build_plan_with_metadata};
536        use std::time::SystemTime;
537
538        let temp = assert_fs::TempDir::new().unwrap();
539        temp.child("file.txt").write_str("data").unwrap();
540        let options =
541            PlanOptions::new(ModifiedRange::new(Some(SystemTime::UNIX_EPOCH), None).unwrap())
542                .with_size_range(SizeRange::new(Some(4), None).unwrap());
543        let mut calls = 0;
544        let plan = build_plan_with_metadata(temp.path(), &[], &options, |_, read_modified| {
545            calls += 1;
546            assert!(read_modified);
547            Ok(file_metadata(4, Some(SystemTime::UNIX_EPOCH)))
548        })
549        .unwrap();
550        assert_eq!(calls, 1);
551        assert_eq!(plan.direct_match_count(), 1);
552    }
553
554    #[test]
555    fn modification_time_is_not_requested_for_a_matching_symlink() {
556        use super::{ModifiedRange, PlanOptions, build_plan_with_metadata};
557        use std::time::SystemTime;
558
559        let temp = assert_fs::TempDir::new().unwrap();
560        let target = temp.child("target.txt");
561        target.write_str("target").unwrap();
562        let link = temp.path().join("link");
563        #[cfg(unix)]
564        let link_result = std::os::unix::fs::symlink(target.path(), &link);
565        #[cfg(windows)]
566        let link_result = std::os::windows::fs::symlink_file(target.path(), &link);
567        link_result.expect("creating the symbolic-link fixture is required for this test");
568        let options =
569            PlanOptions::new(ModifiedRange::new(Some(SystemTime::UNIX_EPOCH), None).unwrap());
570        let plan = build_plan_with_metadata(temp.path(), &["link".to_owned()], &options, |_, _| {
571            panic!("metadata must not be read for a symlink")
572        })
573        .unwrap();
574        assert_eq!(plan.direct_match_count(), 0);
575    }
576
577    #[test]
578    // Verify filesystem roots are identified correctly on Unix and Windows.
579    fn identifies_filesystem_root_paths() {
580        assert!(is_filesystem_root(Path::new("/")));
581
582        #[cfg(windows)]
583        {
584            assert!(is_filesystem_root(Path::new("C:\\")));
585            assert!(is_filesystem_root(Path::new("\\\\server\\share\\")));
586            assert!(!is_filesystem_root(Path::new("C:\\folder")));
587        }
588    }
589
590    #[cfg(windows)]
591    #[test]
592    // Verify Windows drive-relative paths are rejected as both roots and keep patterns.
593    fn rejects_drive_relative_roots_and_patterns() {
594        assert!(is_drive_relative_path("C:folder"));
595        assert!(!is_drive_relative_path("C:\\folder"));
596        assert!(!is_drive_relative_path("\\\\server\\share\\folder"));
597
598        let root_error = build_plan(Path::new("C:folder"), &["*".to_owned()]).unwrap_err();
599        assert!(root_error.to_string().contains("Drive-relative root"));
600
601        let pattern_error = normalize_pattern("C:/root", "C:folder").unwrap_err();
602        assert!(pattern_error.to_string().contains("Drive-relative pattern"));
603    }
604
605    #[test]
606    // Verify a filesystem root is rejected before scanning begins.
607    fn rejects_filesystem_root_before_walking_it() {
608        let error = build_plan(Path::new("/"), &["*".to_owned()]).unwrap_err();
609        assert!(error.to_string().contains("Filesystem roots"));
610    }
611
612    #[test]
613    // Verify missing patterns, empty patterns, and invalid globs are rejected.
614    fn rejects_empty_and_invalid_patterns() {
615        let temp = assert_fs::TempDir::new().unwrap();
616
617        let missing_error = build_plan(temp.path(), &[]).unwrap_err();
618        assert!(missing_error.to_string().contains("At least one pattern"));
619
620        let empty_error = build_plan(temp.path(), &[String::new()]).unwrap_err();
621        assert!(
622            empty_error
623                .to_string()
624                .contains("Pattern must not be empty")
625        );
626
627        let invalid_error = build_plan(temp.path(), &["[".to_owned()]).unwrap_err();
628        assert!(invalid_error.to_string().contains("Invalid glob pattern"));
629    }
630
631    #[test]
632    // Verify a non-directory path is rejected as the processing root.
633    fn rejects_non_directory_root() {
634        let temp = assert_fs::TempDir::new().unwrap();
635        let root_file = temp.child("root.txt");
636        root_file.write_str("not a directory").unwrap();
637
638        let error = build_plan(root_file.path(), &["*".to_owned()]).unwrap_err();
639
640        assert!(error.to_string().contains("Root path is not a directory"));
641    }
642
643    #[test]
644    // Verify matched items and ancestors are kept and all other items are planned for deletion.
645    fn keeps_matching_item_and_its_ancestors() {
646        let temp = assert_fs::TempDir::new().unwrap();
647        temp.child("keep/nested/file.txt")
648            .write_str("keep")
649            .unwrap();
650        temp.child("remove.txt").write_str("remove").unwrap();
651
652        let plan = build_plan(temp.path(), &["keep/nested/file.txt".to_owned()]).unwrap();
653
654        assert_eq!(plan.direct_match_count, 1);
655        assert_eq!(plan.keep_items.len(), 3);
656        assert!(
657            plan.keep_items
658                .iter()
659                .any(|item| item.relative_path == "keep/nested/file.txt")
660        );
661        assert_eq!(plan.delete_items.len(), 1);
662        assert_eq!(plan.delete_items[0].relative_path, "remove.txt");
663        assert_eq!(plan.delete_items[0].item_type, ItemType::File);
664        assert_eq!(plan.delete_roots.len(), 1);
665    }
666
667    #[test]
668    // Verify a literal directory pattern keeps the entire subtree.
669    fn directory_prefix_keeps_its_contents() {
670        let temp = assert_fs::TempDir::new().unwrap();
671        temp.child("keep/deep/file.txt").write_str("keep").unwrap();
672        temp.child("remove/file.txt").write_str("remove").unwrap();
673
674        let plan = build_plan(temp.path(), &["keep".to_owned()]).unwrap();
675
676        assert_eq!(plan.direct_match_count, 3);
677        assert_eq!(plan.keep_items.len(), 3);
678        assert!(
679            plan.keep_items
680                .iter()
681                .any(|item| item.relative_path == "keep/deep/file.txt")
682        );
683        assert_eq!(plan.delete_items.len(), 2);
684        assert_eq!(plan.delete_roots.len(), 1);
685        assert_eq!(plan.delete_roots[0].relative_path, "remove");
686    }
687
688    #[test]
689    // Verify `*` matches one level and `**` matches paths at multiple levels.
690    fn globstar_matches_nested_paths_while_star_matches_one_level() {
691        let temp = assert_fs::TempDir::new().unwrap();
692        temp.child("root.md").write_str("keep").unwrap();
693        temp.child("nested/child.md").write_str("keep").unwrap();
694        temp.child("nested/deep/annual.md")
695            .write_str("keep")
696            .unwrap();
697
698        let single_level = build_plan(temp.path(), &["*.md".to_owned()]).unwrap();
699        assert_eq!(single_level.direct_match_count, 1);
700        assert!(
701            single_level
702                .delete_items
703                .iter()
704                .any(|item| item.relative_path == "nested/child.md")
705        );
706
707        let all_levels = build_plan(temp.path(), &["**/*.md".to_owned()]).unwrap();
708        assert_eq!(all_levels.direct_match_count, 3);
709        assert!(all_levels.delete_items.is_empty());
710    }
711
712    #[test]
713    // Verify `?` and character classes each match one character.
714    fn question_mark_and_character_class_match_one_character() {
715        let temp = assert_fs::TempDir::new().unwrap();
716        temp.child("file1.c").write_str("keep").unwrap();
717        temp.child("file2.h").write_str("keep").unwrap();
718        temp.child("file12.c").write_str("remove").unwrap();
719        temp.child("file3.txt").write_str("remove").unwrap();
720
721        let plan = build_plan(temp.path(), &["file?.[ch]".to_owned()]).unwrap();
722
723        assert_eq!(plan.direct_match_count, 2);
724        assert_eq!(plan.delete_items.len(), 2);
725        assert!(
726            plan.delete_items
727                .iter()
728                .any(|item| item.relative_path == "file12.c")
729        );
730        assert!(
731            plan.delete_items
732                .iter()
733                .any(|item| item.relative_path == "file3.txt")
734        );
735    }
736
737    #[test]
738    // Verify brace alternation is glob syntax, so it does not keep matched directory contents.
739    fn brace_alternation_is_glob_syntax_and_does_not_keep_contents() {
740        let temp = assert_fs::TempDir::new().unwrap();
741        temp.child("reports/2024/a.txt").write_str("a").unwrap();
742        temp.child("reports/2025/b.txt").write_str("b").unwrap();
743        temp.child("reports/2026/c.txt").write_str("c").unwrap();
744        temp.child("x{1}.txt").write_str("brace").unwrap();
745        temp.child("x1.txt").write_str("plain").unwrap();
746
747        let dirs_only = build_plan(temp.path(), &["reports/{2024,2025}".to_owned()]).unwrap();
748        let kept = |plan: &super::RemovalPlan| {
749            plan.keep_items
750                .iter()
751                .map(|item| item.relative_path.clone())
752                .collect::<Vec<_>>()
753        };
754        assert_eq!(
755            kept(&dirs_only),
756            ["reports", "reports/2024", "reports/2025"]
757        );
758
759        let with_contents =
760            build_plan(temp.path(), &["reports/{2024,2025}/**".to_owned()]).unwrap();
761        assert_eq!(
762            kept(&with_contents),
763            [
764                "reports",
765                "reports/2024",
766                "reports/2024/a.txt",
767                "reports/2025",
768                "reports/2025/b.txt"
769            ]
770        );
771
772        // `{1}` is a one-choice alternation, so it matches `x1.txt`, not the literal name.
773        let literal_braces = build_plan(temp.path(), &["x{1}.txt".to_owned()]).unwrap();
774        assert_eq!(kept(&literal_braces), ["x1.txt"]);
775        let escaped_braces = build_plan(temp.path(), &["x[{]1[}].txt".to_owned()]).unwrap();
776        assert_eq!(kept(&escaped_braces), ["x{1}.txt"]);
777    }
778
779    #[test]
780    // Verify an escaped bracket directory name keeps only the directory unless `/**` follows.
781    fn escaped_bracket_directory_needs_globstar_to_keep_contents() {
782        let temp = assert_fs::TempDir::new().unwrap();
783        temp.child("backup[2025]/a.txt").write_str("a").unwrap();
784
785        let plan = build_plan(temp.path(), &["backup[[]2025]".to_owned()]).unwrap();
786        assert_eq!(plan.keep_items.len(), 1);
787        assert_eq!(plan.delete_items[0].relative_path, "backup[2025]/a.txt");
788
789        let plan = build_plan(temp.path(), &["backup[[]2025]/**".to_owned()]).unwrap();
790        assert!(plan.delete_items.is_empty());
791    }
792
793    #[cfg(not(windows))]
794    #[test]
795    // Verify a backslash is a glob escape on non-Windows platforms, not a literal prefix.
796    fn backslash_is_glob_escape_on_non_windows() {
797        let temp = assert_fs::TempDir::new().unwrap();
798        temp.child("subfile.txt").write_str("escaped").unwrap();
799        temp.child("sub\\file.txt/inner.txt")
800            .write_str("literal directory")
801            .unwrap();
802
803        let plan = build_plan(temp.path(), &["sub\\file.txt".to_owned()]).unwrap();
804        assert_eq!(plan.keep_items.len(), 1);
805        assert_eq!(plan.keep_items[0].relative_path, "subfile.txt");
806    }
807
808    #[test]
809    // Verify `dir/*` matches direct children but does not keep nested descendants.
810    fn single_level_glob_does_not_keep_nested_directory_contents() {
811        let temp = assert_fs::TempDir::new().unwrap();
812        temp.child("dir/top.txt").write_str("keep").unwrap();
813        temp.child("dir/sub/nested.txt")
814            .write_str("remove")
815            .unwrap();
816
817        let plan = build_plan(temp.path(), &["dir/*".to_owned()]).unwrap();
818
819        assert_eq!(plan.direct_match_count, 2);
820        assert_eq!(plan.delete_items.len(), 1);
821        assert_eq!(plan.delete_items[0].relative_path, "dir/sub/nested.txt");
822    }
823
824    #[test]
825    // Verify keep patterns that traverse to a parent directory are rejected.
826    fn rejects_parent_traversal() {
827        let temp = assert_fs::TempDir::new().unwrap();
828        let error = build_plan(temp.path(), &["../outside".to_owned()]).unwrap_err();
829        assert!(error.to_string().contains("Parent directory traversal"));
830    }
831
832    #[test]
833    // Verify absolute keep patterns outside the root are rejected.
834    fn absolute_pattern_must_stay_within_root_boundary() {
835        let temp = assert_fs::TempDir::new().unwrap();
836        temp.child("keep.txt").write_str("keep").unwrap();
837        let sibling = temp.path().with_file_name(format!(
838            "{}-sibling",
839            temp.path().file_name().unwrap().to_string_lossy()
840        ));
841        let outside_pattern = sibling.join("*").to_string_lossy().into_owned();
842
843        let error = build_plan(temp.path(), &[outside_pattern]).unwrap_err();
844
845        assert!(error.to_string().contains("outside the processing root"));
846    }
847
848    #[test]
849    // Verify an absolute keep pattern inside the root keeps the matching item.
850    fn absolute_keep_pattern_matches_inside_root() {
851        let temp = assert_fs::TempDir::new().unwrap();
852        temp.child("keep.txt").write_str("keep").unwrap();
853        temp.child("remove.txt").write_str("remove").unwrap();
854        let root = std::fs::canonicalize(temp.path()).unwrap();
855        let keep = root.join("keep.txt").to_string_lossy().into_owned();
856
857        let plan = build_plan(temp.path(), &[keep]).unwrap();
858
859        assert_eq!(plan.delete_items.len(), 1);
860        assert_eq!(plan.delete_items[0].relative_path, "remove.txt");
861    }
862
863    #[test]
864    // Verify glob case matching follows the platform-specific policy.
865    fn glob_case_sensitivity_matches_platform() {
866        let temp = assert_fs::TempDir::new().unwrap();
867        temp.child("Keep.txt").write_str("keep").unwrap();
868
869        let plan = build_plan(temp.path(), &["keep.txt".to_owned()]).unwrap();
870
871        assert_eq!(plan.delete_items.is_empty(), cfg!(windows));
872    }
873
874    #[cfg(windows)]
875    #[test]
876    // Verify Windows root-relative patterns outside the selected root are rejected.
877    fn rejects_windows_root_relative_pattern_outside_current_root() {
878        let temp = assert_fs::TempDir::new().unwrap();
879
880        let error = build_plan(temp.path(), &["/outside/*".to_owned()]).unwrap_err();
881
882        assert!(error.to_string().contains("outside the processing root"));
883    }
884}