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 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 a modification-time range without patterns. Multiple patterns use OR, while
30//! the time range is combined with the pattern condition using AND. When a time range
31//! is present, only matching regular files and their ancestors are kept. The following
32//! pattern retention rules describe behavior without a time 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};
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 filtering.
176///
177/// Patterns are combined with OR. When a modification range is present, only regular
178/// files satisfying both the pattern condition and range directly match; their ancestors
179/// are retained. An empty pattern list omits the pattern condition, but at least one
180/// pattern or a range is required. Without a range, behavior matches [`build_plan`].
181///
182/// This operation does not follow child symbolic links and does not provide a filesystem
183/// snapshot. A failure to obtain required file metadata aborts the entire plan.
184///
185/// # Errors
186///
187/// Invalid conditions, roots, and patterns carry [`ValidationError`]; traversal, metadata,
188/// and path-encoding failures are runtime errors. No partial plan is returned.
189pub fn build_plan_with_options(
190    root: &Path,
191    patterns: &[String],
192    options: &PlanOptions,
193) -> Result<RemovalPlan> {
194    build_plan_with_metadata(root, patterns, options, metadata::modified_time)
195}
196
197fn build_plan_with_metadata(
198    root: &Path,
199    patterns: &[String],
200    options: &PlanOptions,
201    mut modified_time: impl FnMut(&Path) -> Result<std::time::SystemTime>,
202) -> Result<RemovalPlan> {
203    if patterns.is_empty() && options.modified_range().is_none() {
204        return Err(invalid(
205            "At least one pattern or modification-time bound is required",
206        ));
207    }
208    if is_drive_relative_path(&root.to_string_lossy()) {
209        return Err(invalid(format!(
210            "Drive-relative root paths are not supported: {}",
211            root.display()
212        )));
213    }
214
215    let root = std::fs::canonicalize(root).map_err(|error| {
216        invalid_with_source(
217            error,
218            format!("Failed to resolve root directory: {}", root.display()),
219        )
220    })?;
221    if is_filesystem_root(&root) {
222        return Err(invalid(format!(
223            "Filesystem roots cannot be used as processing roots: {}",
224            root.display()
225        )));
226    }
227    if !root.is_dir() {
228        return Err(invalid(format!(
229            "Root path is not a directory: {}",
230            root.display()
231        )));
232    }
233
234    ensure_unicode_path(&root)?;
235    let compiled_patterns = if patterns.is_empty() {
236        None
237    } else {
238        Some(compile_patterns(&root, patterns)?)
239    };
240    let mut entries = Vec::new();
241    // WalkDir yields entries depth-first, so retain indices of the current item's ancestors.
242    let mut directory_stack = Vec::new();
243    let mut direct_match_count = 0;
244
245    for entry in WalkDir::new(&root).follow_links(false).min_depth(1) {
246        let entry = entry.with_context(|| "Failed to walk root directory")?;
247        let depth = entry.depth();
248        directory_stack.truncate(depth.saturating_sub(1));
249        // Parents are visited before children, so a parent's index is always smaller.
250        let parent_index = directory_stack.last().copied();
251        let file_type = entry.file_type();
252        let path = entry.path().to_path_buf();
253        ensure_unicode_path(&path)?;
254        let relative = path
255            .strip_prefix(&root)
256            .context("Walked path escaped the root directory")?;
257        let relative_path = display_path(relative);
258        let pattern_matched = compiled_patterns
259            .as_ref()
260            .is_none_or(|patterns| patterns.matches(&relative_path));
261        let matched = if let Some(range) = options.modified_range() {
262            if pattern_matched && file_type.is_file() {
263                range.contains(modified_time(&path)?)
264            } else {
265                false
266            }
267        } else {
268            pattern_matched
269        };
270
271        if matched {
272            direct_match_count += 1;
273        }
274
275        let item_type = if file_type.is_symlink() {
276            ItemType::Symlink
277        } else if file_type.is_dir() {
278            ItemType::Directory
279        } else {
280            ItemType::File
281        };
282        let item_index = entries.len();
283        entries.push(IndexedItem {
284            item: PlannedItem {
285                path,
286                relative_path,
287                item_type,
288            },
289            parent_index,
290            keep: matched,
291            is_delete_root: false,
292        });
293        if item_type == ItemType::Directory {
294            directory_stack.push(item_index);
295        }
296    }
297
298    Ok(finalize_plan(
299        root,
300        direct_match_count,
301        options.modified_range().cloned(),
302        entries,
303    ))
304}
305
306/// Derives kept ancestors and top-level deletion items from recorded parent indices.
307fn finalize_plan(
308    root: PathBuf,
309    direct_match_count: usize,
310    modified_range: Option<ModifiedRange>,
311    mut entries: Vec<IndexedItem>,
312) -> RemovalPlan {
313    // Children follow parents, so walk in reverse to propagate keep state to ancestors.
314    for index in (0..entries.len()).rev() {
315        if entries[index].keep
316            && let Some(parent_index) = entries[index].parent_index
317        {
318            entries[parent_index].keep = true;
319        }
320    }
321
322    // An unkept item is a deletion root when its parent is kept or is the processing root.
323    for index in 0..entries.len() {
324        let parent_is_kept = entries[index]
325            .parent_index
326            .is_none_or(|parent_index| entries[parent_index].keep);
327        entries[index].is_delete_root = !entries[index].keep && parent_is_kept;
328    }
329
330    entries.sort_unstable_by(|left, right| left.item.relative_path.cmp(&right.item.relative_path));
331    let mut keep_items = Vec::new();
332    let mut delete_items = Vec::new();
333    let mut delete_roots = Vec::new();
334    for entry in entries {
335        if entry.keep {
336            keep_items.push(entry.item);
337        } else {
338            if entry.is_delete_root {
339                delete_roots.push(entry.item.clone());
340            }
341            delete_items.push(entry.item);
342        }
343    }
344
345    RemovalPlan {
346        root,
347        direct_match_count,
348        modified_range,
349        keep_items,
350        delete_items,
351        delete_roots,
352    }
353}
354
355/// Data used to derive kept ancestors and top-level deletion items from traversal order.
356struct IndexedItem {
357    /// The item included in the public plan.
358    item: PlannedItem,
359    /// Index of the parent directory in traversal order, unless directly under the root.
360    parent_index: Option<usize>,
361    /// Initialized from direct matches and propagated to their ancestors.
362    keep: bool,
363    /// True when this is a top-level item passed to the deletion routine.
364    is_delete_root: bool,
365}
366
367#[cfg(test)]
368mod tests {
369    #[cfg(windows)]
370    use super::path::is_drive_relative_path;
371    #[cfg(windows)]
372    use super::pattern::normalize_pattern;
373    use super::{ItemType, build_plan, is_filesystem_root};
374    use assert_fs::prelude::*;
375    use std::path::Path;
376
377    #[test]
378    fn modification_time_is_requested_only_for_pattern_matching_regular_files() {
379        use super::{ModifiedRange, PlanOptions, build_plan_with_metadata};
380        use std::time::{Duration, SystemTime};
381
382        let temp = assert_fs::TempDir::new().unwrap();
383        temp.child("folder/selected.txt")
384            .write_str("selected")
385            .unwrap();
386        temp.child("folder/other.txt").write_str("other").unwrap();
387        let options =
388            PlanOptions::new(ModifiedRange::new(Some(SystemTime::UNIX_EPOCH), None).unwrap());
389        let mut observed = Vec::new();
390        let plan = build_plan_with_metadata(
391            temp.path(),
392            &["folder/selected.txt".to_owned()],
393            &options,
394            |path| {
395                observed.push(path.file_name().unwrap().to_owned());
396                Ok(SystemTime::UNIX_EPOCH + Duration::from_secs(1))
397            },
398        )
399        .unwrap();
400        assert_eq!(observed, [std::ffi::OsString::from("selected.txt")]);
401        assert_eq!(plan.direct_match_count(), 1);
402        let mut observed = Vec::new();
403        let plan = build_plan_with_metadata(temp.path(), &[".".to_owned()], &options, |path| {
404            observed.push(path.file_name().unwrap().to_owned());
405            Ok(SystemTime::UNIX_EPOCH + Duration::from_secs(1))
406        })
407        .unwrap();
408        observed.sort();
409        assert_eq!(
410            observed,
411            [
412                std::ffi::OsString::from("other.txt"),
413                std::ffi::OsString::from("selected.txt")
414            ]
415        );
416        assert_eq!(plan.direct_match_count(), 2);
417        let error = build_plan_with_metadata(
418            temp.path(),
419            &["folder/selected.txt".to_owned()],
420            &options,
421            |_| Err(anyhow::anyhow!("injected metadata failure")),
422        )
423        .unwrap_err();
424        assert!(error.to_string().contains("injected metadata failure"));
425        assert!(error.downcast_ref::<super::ValidationError>().is_none());
426        temp.child("folder/selected.txt").assert("selected");
427        temp.child("folder/other.txt").assert("other");
428        build_plan_with_metadata(
429            temp.path(),
430            &[".".to_owned()],
431            &PlanOptions::default(),
432            |_| panic!("mtime must not be read without a time condition"),
433        )
434        .unwrap();
435    }
436
437    #[test]
438    fn modification_time_is_not_requested_for_a_matching_symlink() {
439        use super::{ModifiedRange, PlanOptions, build_plan_with_metadata};
440        use std::time::SystemTime;
441
442        let temp = assert_fs::TempDir::new().unwrap();
443        let target = temp.child("target.txt");
444        target.write_str("target").unwrap();
445        let link = temp.path().join("link");
446        #[cfg(unix)]
447        let link_result = std::os::unix::fs::symlink(target.path(), &link);
448        #[cfg(windows)]
449        let link_result = std::os::windows::fs::symlink_file(target.path(), &link);
450        link_result.expect("creating the symbolic-link fixture is required for this test");
451        let options =
452            PlanOptions::new(ModifiedRange::new(Some(SystemTime::UNIX_EPOCH), None).unwrap());
453        let plan = build_plan_with_metadata(temp.path(), &["link".to_owned()], &options, |_| {
454            panic!("mtime must not be read for a symlink")
455        })
456        .unwrap();
457        assert_eq!(plan.direct_match_count(), 0);
458    }
459
460    #[test]
461    // Verify filesystem roots are identified correctly on Unix and Windows.
462    fn identifies_filesystem_root_paths() {
463        assert!(is_filesystem_root(Path::new("/")));
464
465        #[cfg(windows)]
466        {
467            assert!(is_filesystem_root(Path::new("C:\\")));
468            assert!(is_filesystem_root(Path::new("\\\\server\\share\\")));
469            assert!(!is_filesystem_root(Path::new("C:\\folder")));
470        }
471    }
472
473    #[cfg(windows)]
474    #[test]
475    // Verify Windows drive-relative paths are rejected as both roots and keep patterns.
476    fn rejects_drive_relative_roots_and_patterns() {
477        assert!(is_drive_relative_path("C:folder"));
478        assert!(!is_drive_relative_path("C:\\folder"));
479        assert!(!is_drive_relative_path("\\\\server\\share\\folder"));
480
481        let root_error = build_plan(Path::new("C:folder"), &["*".to_owned()]).unwrap_err();
482        assert!(root_error.to_string().contains("Drive-relative root"));
483
484        let pattern_error = normalize_pattern("C:/root", "C:folder").unwrap_err();
485        assert!(pattern_error.to_string().contains("Drive-relative pattern"));
486    }
487
488    #[test]
489    // Verify a filesystem root is rejected before scanning begins.
490    fn rejects_filesystem_root_before_walking_it() {
491        let error = build_plan(Path::new("/"), &["*".to_owned()]).unwrap_err();
492        assert!(error.to_string().contains("Filesystem roots"));
493    }
494
495    #[test]
496    // Verify missing patterns, empty patterns, and invalid globs are rejected.
497    fn rejects_empty_and_invalid_patterns() {
498        let temp = assert_fs::TempDir::new().unwrap();
499
500        let missing_error = build_plan(temp.path(), &[]).unwrap_err();
501        assert!(missing_error.to_string().contains("At least one pattern"));
502
503        let empty_error = build_plan(temp.path(), &[String::new()]).unwrap_err();
504        assert!(
505            empty_error
506                .to_string()
507                .contains("Pattern must not be empty")
508        );
509
510        let invalid_error = build_plan(temp.path(), &["[".to_owned()]).unwrap_err();
511        assert!(invalid_error.to_string().contains("Invalid glob pattern"));
512    }
513
514    #[test]
515    // Verify a non-directory path is rejected as the processing root.
516    fn rejects_non_directory_root() {
517        let temp = assert_fs::TempDir::new().unwrap();
518        let root_file = temp.child("root.txt");
519        root_file.write_str("not a directory").unwrap();
520
521        let error = build_plan(root_file.path(), &["*".to_owned()]).unwrap_err();
522
523        assert!(error.to_string().contains("Root path is not a directory"));
524    }
525
526    #[test]
527    // Verify matched items and ancestors are kept and all other items are planned for deletion.
528    fn keeps_matching_item_and_its_ancestors() {
529        let temp = assert_fs::TempDir::new().unwrap();
530        temp.child("keep/nested/file.txt")
531            .write_str("keep")
532            .unwrap();
533        temp.child("remove.txt").write_str("remove").unwrap();
534
535        let plan = build_plan(temp.path(), &["keep/nested/file.txt".to_owned()]).unwrap();
536
537        assert_eq!(plan.direct_match_count, 1);
538        assert_eq!(plan.keep_items.len(), 3);
539        assert!(
540            plan.keep_items
541                .iter()
542                .any(|item| item.relative_path == "keep/nested/file.txt")
543        );
544        assert_eq!(plan.delete_items.len(), 1);
545        assert_eq!(plan.delete_items[0].relative_path, "remove.txt");
546        assert_eq!(plan.delete_items[0].item_type, ItemType::File);
547        assert_eq!(plan.delete_roots.len(), 1);
548    }
549
550    #[test]
551    // Verify a literal directory pattern keeps the entire subtree.
552    fn directory_prefix_keeps_its_contents() {
553        let temp = assert_fs::TempDir::new().unwrap();
554        temp.child("keep/deep/file.txt").write_str("keep").unwrap();
555        temp.child("remove/file.txt").write_str("remove").unwrap();
556
557        let plan = build_plan(temp.path(), &["keep".to_owned()]).unwrap();
558
559        assert_eq!(plan.direct_match_count, 3);
560        assert_eq!(plan.keep_items.len(), 3);
561        assert!(
562            plan.keep_items
563                .iter()
564                .any(|item| item.relative_path == "keep/deep/file.txt")
565        );
566        assert_eq!(plan.delete_items.len(), 2);
567        assert_eq!(plan.delete_roots.len(), 1);
568        assert_eq!(plan.delete_roots[0].relative_path, "remove");
569    }
570
571    #[test]
572    // Verify `*` matches one level and `**` matches paths at multiple levels.
573    fn globstar_matches_nested_paths_while_star_matches_one_level() {
574        let temp = assert_fs::TempDir::new().unwrap();
575        temp.child("root.md").write_str("keep").unwrap();
576        temp.child("nested/child.md").write_str("keep").unwrap();
577        temp.child("nested/deep/annual.md")
578            .write_str("keep")
579            .unwrap();
580
581        let single_level = build_plan(temp.path(), &["*.md".to_owned()]).unwrap();
582        assert_eq!(single_level.direct_match_count, 1);
583        assert!(
584            single_level
585                .delete_items
586                .iter()
587                .any(|item| item.relative_path == "nested/child.md")
588        );
589
590        let all_levels = build_plan(temp.path(), &["**/*.md".to_owned()]).unwrap();
591        assert_eq!(all_levels.direct_match_count, 3);
592        assert!(all_levels.delete_items.is_empty());
593    }
594
595    #[test]
596    // Verify `?` and character classes each match one character.
597    fn question_mark_and_character_class_match_one_character() {
598        let temp = assert_fs::TempDir::new().unwrap();
599        temp.child("file1.c").write_str("keep").unwrap();
600        temp.child("file2.h").write_str("keep").unwrap();
601        temp.child("file12.c").write_str("remove").unwrap();
602        temp.child("file3.txt").write_str("remove").unwrap();
603
604        let plan = build_plan(temp.path(), &["file?.[ch]".to_owned()]).unwrap();
605
606        assert_eq!(plan.direct_match_count, 2);
607        assert_eq!(plan.delete_items.len(), 2);
608        assert!(
609            plan.delete_items
610                .iter()
611                .any(|item| item.relative_path == "file12.c")
612        );
613        assert!(
614            plan.delete_items
615                .iter()
616                .any(|item| item.relative_path == "file3.txt")
617        );
618    }
619
620    #[test]
621    // Verify brace alternation is glob syntax, so it does not keep matched directory contents.
622    fn brace_alternation_is_glob_syntax_and_does_not_keep_contents() {
623        let temp = assert_fs::TempDir::new().unwrap();
624        temp.child("reports/2024/a.txt").write_str("a").unwrap();
625        temp.child("reports/2025/b.txt").write_str("b").unwrap();
626        temp.child("reports/2026/c.txt").write_str("c").unwrap();
627        temp.child("x{1}.txt").write_str("brace").unwrap();
628        temp.child("x1.txt").write_str("plain").unwrap();
629
630        let dirs_only = build_plan(temp.path(), &["reports/{2024,2025}".to_owned()]).unwrap();
631        let kept = |plan: &super::RemovalPlan| {
632            plan.keep_items
633                .iter()
634                .map(|item| item.relative_path.clone())
635                .collect::<Vec<_>>()
636        };
637        assert_eq!(
638            kept(&dirs_only),
639            ["reports", "reports/2024", "reports/2025"]
640        );
641
642        let with_contents =
643            build_plan(temp.path(), &["reports/{2024,2025}/**".to_owned()]).unwrap();
644        assert_eq!(
645            kept(&with_contents),
646            [
647                "reports",
648                "reports/2024",
649                "reports/2024/a.txt",
650                "reports/2025",
651                "reports/2025/b.txt"
652            ]
653        );
654
655        // `{1}` is a one-choice alternation, so it matches `x1.txt`, not the literal name.
656        let literal_braces = build_plan(temp.path(), &["x{1}.txt".to_owned()]).unwrap();
657        assert_eq!(kept(&literal_braces), ["x1.txt"]);
658        let escaped_braces = build_plan(temp.path(), &["x[{]1[}].txt".to_owned()]).unwrap();
659        assert_eq!(kept(&escaped_braces), ["x{1}.txt"]);
660    }
661
662    #[test]
663    // Verify an escaped bracket directory name keeps only the directory unless `/**` follows.
664    fn escaped_bracket_directory_needs_globstar_to_keep_contents() {
665        let temp = assert_fs::TempDir::new().unwrap();
666        temp.child("backup[2025]/a.txt").write_str("a").unwrap();
667
668        let plan = build_plan(temp.path(), &["backup[[]2025]".to_owned()]).unwrap();
669        assert_eq!(plan.keep_items.len(), 1);
670        assert_eq!(plan.delete_items[0].relative_path, "backup[2025]/a.txt");
671
672        let plan = build_plan(temp.path(), &["backup[[]2025]/**".to_owned()]).unwrap();
673        assert!(plan.delete_items.is_empty());
674    }
675
676    #[cfg(not(windows))]
677    #[test]
678    // Verify a backslash is a glob escape on non-Windows platforms, not a literal prefix.
679    fn backslash_is_glob_escape_on_non_windows() {
680        let temp = assert_fs::TempDir::new().unwrap();
681        temp.child("subfile.txt").write_str("escaped").unwrap();
682        temp.child("sub\\file.txt/inner.txt")
683            .write_str("literal directory")
684            .unwrap();
685
686        let plan = build_plan(temp.path(), &["sub\\file.txt".to_owned()]).unwrap();
687        assert_eq!(plan.keep_items.len(), 1);
688        assert_eq!(plan.keep_items[0].relative_path, "subfile.txt");
689    }
690
691    #[test]
692    // Verify `dir/*` matches direct children but does not keep nested descendants.
693    fn single_level_glob_does_not_keep_nested_directory_contents() {
694        let temp = assert_fs::TempDir::new().unwrap();
695        temp.child("dir/top.txt").write_str("keep").unwrap();
696        temp.child("dir/sub/nested.txt")
697            .write_str("remove")
698            .unwrap();
699
700        let plan = build_plan(temp.path(), &["dir/*".to_owned()]).unwrap();
701
702        assert_eq!(plan.direct_match_count, 2);
703        assert_eq!(plan.delete_items.len(), 1);
704        assert_eq!(plan.delete_items[0].relative_path, "dir/sub/nested.txt");
705    }
706
707    #[test]
708    // Verify keep patterns that traverse to a parent directory are rejected.
709    fn rejects_parent_traversal() {
710        let temp = assert_fs::TempDir::new().unwrap();
711        let error = build_plan(temp.path(), &["../outside".to_owned()]).unwrap_err();
712        assert!(error.to_string().contains("Parent directory traversal"));
713    }
714
715    #[test]
716    // Verify absolute keep patterns outside the root are rejected.
717    fn absolute_pattern_must_stay_within_root_boundary() {
718        let temp = assert_fs::TempDir::new().unwrap();
719        temp.child("keep.txt").write_str("keep").unwrap();
720        let sibling = temp.path().with_file_name(format!(
721            "{}-sibling",
722            temp.path().file_name().unwrap().to_string_lossy()
723        ));
724        let outside_pattern = sibling.join("*").to_string_lossy().into_owned();
725
726        let error = build_plan(temp.path(), &[outside_pattern]).unwrap_err();
727
728        assert!(error.to_string().contains("outside the processing root"));
729    }
730
731    #[test]
732    // Verify an absolute keep pattern inside the root keeps the matching item.
733    fn absolute_keep_pattern_matches_inside_root() {
734        let temp = assert_fs::TempDir::new().unwrap();
735        temp.child("keep.txt").write_str("keep").unwrap();
736        temp.child("remove.txt").write_str("remove").unwrap();
737        let root = std::fs::canonicalize(temp.path()).unwrap();
738        let keep = root.join("keep.txt").to_string_lossy().into_owned();
739
740        let plan = build_plan(temp.path(), &[keep]).unwrap();
741
742        assert_eq!(plan.delete_items.len(), 1);
743        assert_eq!(plan.delete_items[0].relative_path, "remove.txt");
744    }
745
746    #[test]
747    // Verify glob case matching follows the platform-specific policy.
748    fn glob_case_sensitivity_matches_platform() {
749        let temp = assert_fs::TempDir::new().unwrap();
750        temp.child("Keep.txt").write_str("keep").unwrap();
751
752        let plan = build_plan(temp.path(), &["keep.txt".to_owned()]).unwrap();
753
754        assert_eq!(plan.delete_items.is_empty(), cfg!(windows));
755    }
756
757    #[cfg(windows)]
758    #[test]
759    // Verify Windows root-relative patterns outside the selected root are rejected.
760    fn rejects_windows_root_relative_pattern_outside_current_root() {
761        let temp = assert_fs::TempDir::new().unwrap();
762
763        let error = build_plan(temp.path(), &["/outside/*".to_owned()]).unwrap_err();
764
765        assert!(error.to_string().contains("outside the processing root"));
766    }
767}