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 one or more keep patterns, and creates an in-memory [`RemovalPlan`].
7//! The plan partitions items into kept entries (including required ancestor directories)
8//! and deletion targets.
9//!
10//! # Safety by Design
11//!
12//! - **Separation of Planning and Deletion**: [`build_plan`] is strictly read-only.
13//!   It records an in-memory plan from entries observed during traversal. The traversal is not
14//!   an atomic or protected filesystem snapshot and does not lock or prevent concurrent changes.
15//!   It does not create, modify, or delete any files or directories.
16//! - **Root Protection**: The processing root itself is never included in the plan,
17//!   and filesystem roots (such as `/` on Unix or `C:\` on Windows) are rejected to prevent
18//!   catastrophic deletion.
19//! - **No Symlink Traversal**: Symbolic links encountered beneath the root are never followed.
20//!   Each link is evaluated as an individual leaf item; if targeted for deletion, only the
21//!   symbolic link itself is deleted, never its target.
22//! - **Unambiguous Paths**: The normalized root and every scanned entry path must be
23//!   representable as Unicode. Otherwise, planning fails without returning a partial plan.
24//!
25//! # Pattern Matching Syntax and Semantics
26//!
27//! At least one keep pattern must be provided. When multiple patterns are given, an item
28//! is kept if it matches **any** pattern (logical OR):
29//!
30//! - `*` matches any sequence of non-separator characters within a single directory component.
31//! - `?` matches one Unicode scalar value other than a separator. A character class also
32//!   matches one Unicode scalar value; combining sequences can therefore require multiple
33//!   wildcards.
34//! - `**` matches zero or more directory levels.
35//! - `[...]` matches any character in the character class, adhering to standard glob rules.
36//! - `{a,b}` matches any of the comma-separated alternatives.
37//! - `.` or `./` represents the processing root and keeps everything beneath it.
38//! - A directory path without glob syntax keeps that directory and all of its contents
39//!   recursively. Glob syntax is `*`, `?`, `[`, `{`, and `}`; on non-Windows platforms,
40//!   `\` is also glob syntax because it escapes the next character. On Windows, `\` is a
41//!   path separator.
42//! - A glob match keeps the matching item and all required ancestor directories up to the root,
43//!   but does *not* recursively keep unmatched descendants. For instance, `dir/*` matches
44//!   items directly beneath `dir/`, but does not recursively keep unmatched contents of
45//!   subdirectories beneath them. Likewise, `dir/**` does not match `dir` itself, and an
46//!   escaped name such as `backup[[]2025]` keeps only that directory; append `/**` to keep
47//!   its contents.
48//! - Relative patterns are resolved relative to the processing root. Patterns containing a
49//!   `..` component are rejected.
50//! - Leading and trailing whitespace in patterns is preserved.
51//!
52//! # Platform Differences
53//!
54//! - **Windows**: Path matching uses Unicode simple case folding (non-Turkic), ignoring
55//!   per-directory NTFS case-sensitivity settings.
56//! - **Ubuntu**: Path matching is strictly case-sensitive. Windows and Ubuntu are the
57//!   supported platforms.
58//!
59//! # Examples
60//!
61//! ```
62//! use remove_except::build_plan;
63//! use std::fs::{self, File};
64//!
65//! let temp_dir = assert_fs::TempDir::new().unwrap();
66//! let root = temp_dir.path();
67//! fs::create_dir_all(root.join("src")).unwrap();
68//! File::create(root.join("src/main.rs")).unwrap();
69//! File::create(root.join("notes.txt")).unwrap();
70//!
71//! // Build a removal plan keeping only files inside `src/`:
72//! let plan = build_plan(root, &["src/**".to_owned()])
73//!     .expect("valid root and keep patterns");
74//!
75//! // The plan identifies kept items and ancestors:
76//! assert!(plan.keep_items().iter().any(|item| item.relative_path() == "src/main.rs"));
77//! assert!(plan.keep_items().iter().any(|item| item.relative_path() == "src"));
78//!
79//! // Deletion roots identify top-level removal targets:
80//! assert!(plan.delete_roots().iter().any(|item| item.relative_path() == "notes.txt"));
81//! ```
82
83use std::path::{Path, PathBuf};
84
85use anyhow::{Context, Result};
86use walkdir::WalkDir;
87
88mod error;
89mod model;
90mod path;
91mod pattern;
92
93pub use error::ValidationError;
94use error::{invalid, invalid_with_source};
95pub use model::{ItemType, PlannedItem, RemovalPlan};
96use path::{display_path, ensure_unicode_path, is_drive_relative_path, is_filesystem_root};
97use pattern::compile_patterns;
98
99/// Scans beneath the specified root directory and constructs a [`RemovalPlan`].
100///
101/// Discovered filesystem entries are evaluated against the provided `patterns`. An item is
102/// kept if it matches any pattern (logical OR). When an item is kept, all of its ancestor
103/// directories up to `root` are also kept to preserve directory hierarchy.
104///
105/// # Arguments
106///
107/// * `root` - Path to the directory to scan. Relative paths are resolved against the current
108///   working directory. Filesystem roots (e.g. `/` on Unix, `C:\` on Windows) and Windows
109///   drive-relative paths (e.g. `C:foo`) are rejected.
110/// * `patterns` - One or more keep patterns. Patterns may be literal relative paths or glob
111///   patterns (`*`, `?`, `**`, `[...]`, `{a,b}`; on non-Windows platforms `\` escapes the
112///   next character). `?` and a character class each match one Unicode scalar value.
113///   Literal directories without glob syntax match recursively; glob matches do not keep
114///   unmatched descendants. Relative patterns are resolved relative to `root`. Patterns
115///   containing a `..` component are rejected. Leading and trailing whitespace is preserved.
116///
117/// # Safety and Behavior
118///
119/// - **Read-Only**: This function only traverses and reads directory metadata. It does not
120///   modify, create, or delete any files.
121/// - **No Symlink Traversal**: Symbolic links beneath `root` are treated as individual leaf
122///   items and are never followed.
123/// - **Root Exclusion**: The `root` directory itself is never included in the plan.
124/// - **Unicode Paths**: The normalized root and every scanned entry path must be
125///   representable as Unicode, regardless of whether an entry would be kept or deleted.
126///   Link targets beneath `root` are not checked because those links are not followed.
127/// - **Observed Entries**: The plan contains entries observed during traversal. The traversal
128///   is not atomic and does not lock or prevent concurrent filesystem changes. The plan is not
129///   refreshed if the filesystem changes after construction.
130///
131/// # Errors
132///
133/// Returns an error in the following circumstances (exact error message strings are not part
134/// of the stable API contract):
135///
136/// - **Pattern errors**: `patterns` is empty, a pattern contains invalid glob syntax, or a
137///   pattern escapes `root` (e.g., starts with `../` or resolves to an ancestor).
138/// - **Root errors**: `root` cannot be resolved, is not a directory, is a filesystem root,
139///   or is a Windows drive-relative path.
140/// - **I/O errors**: Directory traversal fails due to filesystem permissions or I/O errors.
141/// - **Path encoding errors**: The normalized root or a scanned entry path cannot be
142///   represented as Unicode. No partial plan is returned, even if all entries would be kept.
143///
144/// Pattern and root validation errors carry a [`ValidationError`] that can be detected with
145/// [`anyhow::Error::downcast_ref`]. Traversal and path encoding errors do not.
146///
147/// # Examples
148///
149/// ```
150/// use remove_except::build_plan;
151/// use std::fs::{self, File};
152///
153/// let temp_dir = assert_fs::TempDir::new().unwrap();
154/// let root = temp_dir.path();
155/// fs::create_dir_all(root.join("docs")).unwrap();
156/// File::create(root.join("docs/guide.md")).unwrap();
157/// File::create(root.join("temp.log")).unwrap();
158///
159/// let plan = build_plan(root, &["docs/**".to_owned()])
160///     .expect("plan construction should succeed");
161///
162/// assert_eq!(plan.direct_match_count(), 1);
163/// assert!(plan.keep_items().iter().any(|item| item.relative_path() == "docs/guide.md"));
164/// assert!(plan.delete_roots().iter().any(|item| item.relative_path() == "temp.log"));
165/// ```
166pub fn build_plan(root: &Path, patterns: &[String]) -> Result<RemovalPlan> {
167    if patterns.is_empty() {
168        return Err(invalid("At least one pattern is required"));
169    }
170    if is_drive_relative_path(&root.to_string_lossy()) {
171        return Err(invalid(format!(
172            "Drive-relative root paths are not supported: {}",
173            root.display()
174        )));
175    }
176
177    let root = std::fs::canonicalize(root).map_err(|error| {
178        invalid_with_source(
179            error,
180            format!("Failed to resolve root directory: {}", root.display()),
181        )
182    })?;
183    if is_filesystem_root(&root) {
184        return Err(invalid(format!(
185            "Filesystem roots cannot be used as processing roots: {}",
186            root.display()
187        )));
188    }
189    if !root.is_dir() {
190        return Err(invalid(format!(
191            "Root path is not a directory: {}",
192            root.display()
193        )));
194    }
195
196    ensure_unicode_path(&root)?;
197    let compiled_patterns = compile_patterns(&root, patterns)?;
198    let mut entries = Vec::new();
199    // WalkDir yields entries depth-first, so retain indices of the current item's ancestors.
200    let mut directory_stack = Vec::new();
201    let mut direct_match_count = 0;
202
203    for entry in WalkDir::new(&root).follow_links(false).min_depth(1) {
204        let entry = entry.with_context(|| "Failed to walk root directory")?;
205        let depth = entry.depth();
206        directory_stack.truncate(depth.saturating_sub(1));
207        // Parents are visited before children, so a parent's index is always smaller.
208        let parent_index = directory_stack.last().copied();
209        let file_type = entry.file_type();
210        let path = entry.path().to_path_buf();
211        ensure_unicode_path(&path)?;
212        let relative = path
213            .strip_prefix(&root)
214            .context("Walked path escaped the root directory")?;
215        let relative_path = display_path(relative);
216        let matched = compiled_patterns.matches(&relative_path);
217
218        if matched {
219            direct_match_count += 1;
220        }
221
222        let item_type = if file_type.is_symlink() {
223            ItemType::Symlink
224        } else if file_type.is_dir() {
225            ItemType::Directory
226        } else {
227            ItemType::File
228        };
229        let item_index = entries.len();
230        entries.push(IndexedItem {
231            item: PlannedItem {
232                path,
233                relative_path,
234                item_type,
235            },
236            parent_index,
237            keep: matched,
238            is_delete_root: false,
239        });
240        if item_type == ItemType::Directory {
241            directory_stack.push(item_index);
242        }
243    }
244
245    Ok(finalize_plan(root, direct_match_count, entries))
246}
247
248/// Derives kept ancestors and top-level deletion items from recorded parent indices.
249fn finalize_plan(
250    root: PathBuf,
251    direct_match_count: usize,
252    mut entries: Vec<IndexedItem>,
253) -> RemovalPlan {
254    // Children follow parents, so walk in reverse to propagate keep state to ancestors.
255    for index in (0..entries.len()).rev() {
256        if entries[index].keep
257            && let Some(parent_index) = entries[index].parent_index
258        {
259            entries[parent_index].keep = true;
260        }
261    }
262
263    // An unkept item is a deletion root when its parent is kept or is the processing root.
264    for index in 0..entries.len() {
265        let parent_is_kept = entries[index]
266            .parent_index
267            .is_none_or(|parent_index| entries[parent_index].keep);
268        entries[index].is_delete_root = !entries[index].keep && parent_is_kept;
269    }
270
271    entries.sort_unstable_by(|left, right| left.item.relative_path.cmp(&right.item.relative_path));
272    let mut keep_items = Vec::new();
273    let mut delete_items = Vec::new();
274    let mut delete_roots = Vec::new();
275    for entry in entries {
276        if entry.keep {
277            keep_items.push(entry.item);
278        } else {
279            if entry.is_delete_root {
280                delete_roots.push(entry.item.clone());
281            }
282            delete_items.push(entry.item);
283        }
284    }
285
286    RemovalPlan {
287        root,
288        direct_match_count,
289        keep_items,
290        delete_items,
291        delete_roots,
292    }
293}
294
295/// Data used to derive kept ancestors and top-level deletion items from traversal order.
296struct IndexedItem {
297    /// The item included in the public plan.
298    item: PlannedItem,
299    /// Index of the parent directory in traversal order, unless directly under the root.
300    parent_index: Option<usize>,
301    /// Initialized from direct matches and propagated to their ancestors.
302    keep: bool,
303    /// True when this is a top-level item passed to the deletion routine.
304    is_delete_root: bool,
305}
306
307#[cfg(test)]
308mod tests {
309    #[cfg(windows)]
310    use super::path::is_drive_relative_path;
311    #[cfg(windows)]
312    use super::pattern::normalize_pattern;
313    use super::{ItemType, build_plan, is_filesystem_root};
314    use assert_fs::prelude::*;
315    use std::path::Path;
316
317    #[test]
318    // Verify filesystem roots are identified correctly on Unix and Windows.
319    fn identifies_filesystem_root_paths() {
320        assert!(is_filesystem_root(Path::new("/")));
321
322        #[cfg(windows)]
323        {
324            assert!(is_filesystem_root(Path::new("C:\\")));
325            assert!(is_filesystem_root(Path::new("\\\\server\\share\\")));
326            assert!(!is_filesystem_root(Path::new("C:\\folder")));
327        }
328    }
329
330    #[cfg(windows)]
331    #[test]
332    // Verify Windows drive-relative paths are rejected as both roots and keep patterns.
333    fn rejects_drive_relative_roots_and_patterns() {
334        assert!(is_drive_relative_path("C:folder"));
335        assert!(!is_drive_relative_path("C:\\folder"));
336        assert!(!is_drive_relative_path("\\\\server\\share\\folder"));
337
338        let root_error = build_plan(Path::new("C:folder"), &["*".to_owned()]).unwrap_err();
339        assert!(root_error.to_string().contains("Drive-relative root"));
340
341        let pattern_error = normalize_pattern("C:/root", "C:folder").unwrap_err();
342        assert!(pattern_error.to_string().contains("Drive-relative pattern"));
343    }
344
345    #[test]
346    // Verify a filesystem root is rejected before scanning begins.
347    fn rejects_filesystem_root_before_walking_it() {
348        let error = build_plan(Path::new("/"), &["*".to_owned()]).unwrap_err();
349        assert!(error.to_string().contains("Filesystem roots"));
350    }
351
352    #[test]
353    // Verify missing patterns, empty patterns, and invalid globs are rejected.
354    fn rejects_empty_and_invalid_patterns() {
355        let temp = assert_fs::TempDir::new().unwrap();
356
357        let missing_error = build_plan(temp.path(), &[]).unwrap_err();
358        assert!(missing_error.to_string().contains("At least one pattern"));
359
360        let empty_error = build_plan(temp.path(), &[String::new()]).unwrap_err();
361        assert!(
362            empty_error
363                .to_string()
364                .contains("Pattern must not be empty")
365        );
366
367        let invalid_error = build_plan(temp.path(), &["[".to_owned()]).unwrap_err();
368        assert!(invalid_error.to_string().contains("Invalid glob pattern"));
369    }
370
371    #[test]
372    // Verify a non-directory path is rejected as the processing root.
373    fn rejects_non_directory_root() {
374        let temp = assert_fs::TempDir::new().unwrap();
375        let root_file = temp.child("root.txt");
376        root_file.write_str("not a directory").unwrap();
377
378        let error = build_plan(root_file.path(), &["*".to_owned()]).unwrap_err();
379
380        assert!(error.to_string().contains("Root path is not a directory"));
381    }
382
383    #[test]
384    // Verify matched items and ancestors are kept and all other items are planned for deletion.
385    fn keeps_matching_item_and_its_ancestors() {
386        let temp = assert_fs::TempDir::new().unwrap();
387        temp.child("keep/nested/file.txt")
388            .write_str("keep")
389            .unwrap();
390        temp.child("remove.txt").write_str("remove").unwrap();
391
392        let plan = build_plan(temp.path(), &["keep/nested/file.txt".to_owned()]).unwrap();
393
394        assert_eq!(plan.direct_match_count, 1);
395        assert_eq!(plan.keep_items.len(), 3);
396        assert!(
397            plan.keep_items
398                .iter()
399                .any(|item| item.relative_path == "keep/nested/file.txt")
400        );
401        assert_eq!(plan.delete_items.len(), 1);
402        assert_eq!(plan.delete_items[0].relative_path, "remove.txt");
403        assert_eq!(plan.delete_items[0].item_type, ItemType::File);
404        assert_eq!(plan.delete_roots.len(), 1);
405    }
406
407    #[test]
408    // Verify a literal directory pattern keeps the entire subtree.
409    fn directory_prefix_keeps_its_contents() {
410        let temp = assert_fs::TempDir::new().unwrap();
411        temp.child("keep/deep/file.txt").write_str("keep").unwrap();
412        temp.child("remove/file.txt").write_str("remove").unwrap();
413
414        let plan = build_plan(temp.path(), &["keep".to_owned()]).unwrap();
415
416        assert_eq!(plan.direct_match_count, 3);
417        assert_eq!(plan.keep_items.len(), 3);
418        assert!(
419            plan.keep_items
420                .iter()
421                .any(|item| item.relative_path == "keep/deep/file.txt")
422        );
423        assert_eq!(plan.delete_items.len(), 2);
424        assert_eq!(plan.delete_roots.len(), 1);
425        assert_eq!(plan.delete_roots[0].relative_path, "remove");
426    }
427
428    #[test]
429    // Verify `*` matches one level and `**` matches paths at multiple levels.
430    fn globstar_matches_nested_paths_while_star_matches_one_level() {
431        let temp = assert_fs::TempDir::new().unwrap();
432        temp.child("root.md").write_str("keep").unwrap();
433        temp.child("nested/child.md").write_str("keep").unwrap();
434        temp.child("nested/deep/annual.md")
435            .write_str("keep")
436            .unwrap();
437
438        let single_level = build_plan(temp.path(), &["*.md".to_owned()]).unwrap();
439        assert_eq!(single_level.direct_match_count, 1);
440        assert!(
441            single_level
442                .delete_items
443                .iter()
444                .any(|item| item.relative_path == "nested/child.md")
445        );
446
447        let all_levels = build_plan(temp.path(), &["**/*.md".to_owned()]).unwrap();
448        assert_eq!(all_levels.direct_match_count, 3);
449        assert!(all_levels.delete_items.is_empty());
450    }
451
452    #[test]
453    // Verify `?` and character classes each match one character.
454    fn question_mark_and_character_class_match_one_character() {
455        let temp = assert_fs::TempDir::new().unwrap();
456        temp.child("file1.c").write_str("keep").unwrap();
457        temp.child("file2.h").write_str("keep").unwrap();
458        temp.child("file12.c").write_str("remove").unwrap();
459        temp.child("file3.txt").write_str("remove").unwrap();
460
461        let plan = build_plan(temp.path(), &["file?.[ch]".to_owned()]).unwrap();
462
463        assert_eq!(plan.direct_match_count, 2);
464        assert_eq!(plan.delete_items.len(), 2);
465        assert!(
466            plan.delete_items
467                .iter()
468                .any(|item| item.relative_path == "file12.c")
469        );
470        assert!(
471            plan.delete_items
472                .iter()
473                .any(|item| item.relative_path == "file3.txt")
474        );
475    }
476
477    #[test]
478    // Verify brace alternation is glob syntax, so it does not keep matched directory contents.
479    fn brace_alternation_is_glob_syntax_and_does_not_keep_contents() {
480        let temp = assert_fs::TempDir::new().unwrap();
481        temp.child("reports/2024/a.txt").write_str("a").unwrap();
482        temp.child("reports/2025/b.txt").write_str("b").unwrap();
483        temp.child("reports/2026/c.txt").write_str("c").unwrap();
484        temp.child("x{1}.txt").write_str("brace").unwrap();
485        temp.child("x1.txt").write_str("plain").unwrap();
486
487        let dirs_only = build_plan(temp.path(), &["reports/{2024,2025}".to_owned()]).unwrap();
488        let kept = |plan: &super::RemovalPlan| {
489            plan.keep_items
490                .iter()
491                .map(|item| item.relative_path.clone())
492                .collect::<Vec<_>>()
493        };
494        assert_eq!(
495            kept(&dirs_only),
496            ["reports", "reports/2024", "reports/2025"]
497        );
498
499        let with_contents =
500            build_plan(temp.path(), &["reports/{2024,2025}/**".to_owned()]).unwrap();
501        assert_eq!(
502            kept(&with_contents),
503            [
504                "reports",
505                "reports/2024",
506                "reports/2024/a.txt",
507                "reports/2025",
508                "reports/2025/b.txt"
509            ]
510        );
511
512        // `{1}` is a one-choice alternation, so it matches `x1.txt`, not the literal name.
513        let literal_braces = build_plan(temp.path(), &["x{1}.txt".to_owned()]).unwrap();
514        assert_eq!(kept(&literal_braces), ["x1.txt"]);
515        let escaped_braces = build_plan(temp.path(), &["x[{]1[}].txt".to_owned()]).unwrap();
516        assert_eq!(kept(&escaped_braces), ["x{1}.txt"]);
517    }
518
519    #[test]
520    // Verify an escaped bracket directory name keeps only the directory unless `/**` follows.
521    fn escaped_bracket_directory_needs_globstar_to_keep_contents() {
522        let temp = assert_fs::TempDir::new().unwrap();
523        temp.child("backup[2025]/a.txt").write_str("a").unwrap();
524
525        let plan = build_plan(temp.path(), &["backup[[]2025]".to_owned()]).unwrap();
526        assert_eq!(plan.keep_items.len(), 1);
527        assert_eq!(plan.delete_items[0].relative_path, "backup[2025]/a.txt");
528
529        let plan = build_plan(temp.path(), &["backup[[]2025]/**".to_owned()]).unwrap();
530        assert!(plan.delete_items.is_empty());
531    }
532
533    #[cfg(not(windows))]
534    #[test]
535    // Verify a backslash is a glob escape on non-Windows platforms, not a literal prefix.
536    fn backslash_is_glob_escape_on_non_windows() {
537        let temp = assert_fs::TempDir::new().unwrap();
538        temp.child("subfile.txt").write_str("escaped").unwrap();
539        temp.child("sub\\file.txt/inner.txt")
540            .write_str("literal directory")
541            .unwrap();
542
543        let plan = build_plan(temp.path(), &["sub\\file.txt".to_owned()]).unwrap();
544        assert_eq!(plan.keep_items.len(), 1);
545        assert_eq!(plan.keep_items[0].relative_path, "subfile.txt");
546    }
547
548    #[test]
549    // Verify `dir/*` matches direct children but does not keep nested descendants.
550    fn single_level_glob_does_not_keep_nested_directory_contents() {
551        let temp = assert_fs::TempDir::new().unwrap();
552        temp.child("dir/top.txt").write_str("keep").unwrap();
553        temp.child("dir/sub/nested.txt")
554            .write_str("remove")
555            .unwrap();
556
557        let plan = build_plan(temp.path(), &["dir/*".to_owned()]).unwrap();
558
559        assert_eq!(plan.direct_match_count, 2);
560        assert_eq!(plan.delete_items.len(), 1);
561        assert_eq!(plan.delete_items[0].relative_path, "dir/sub/nested.txt");
562    }
563
564    #[test]
565    // Verify keep patterns that traverse to a parent directory are rejected.
566    fn rejects_parent_traversal() {
567        let temp = assert_fs::TempDir::new().unwrap();
568        let error = build_plan(temp.path(), &["../outside".to_owned()]).unwrap_err();
569        assert!(error.to_string().contains("Parent directory traversal"));
570    }
571
572    #[test]
573    // Verify absolute keep patterns outside the root are rejected.
574    fn absolute_pattern_must_stay_within_root_boundary() {
575        let temp = assert_fs::TempDir::new().unwrap();
576        temp.child("keep.txt").write_str("keep").unwrap();
577        let sibling = temp.path().with_file_name(format!(
578            "{}-sibling",
579            temp.path().file_name().unwrap().to_string_lossy()
580        ));
581        let outside_pattern = sibling.join("*").to_string_lossy().into_owned();
582
583        let error = build_plan(temp.path(), &[outside_pattern]).unwrap_err();
584
585        assert!(error.to_string().contains("outside the processing root"));
586    }
587
588    #[test]
589    // Verify an absolute keep pattern inside the root keeps the matching item.
590    fn absolute_keep_pattern_matches_inside_root() {
591        let temp = assert_fs::TempDir::new().unwrap();
592        temp.child("keep.txt").write_str("keep").unwrap();
593        temp.child("remove.txt").write_str("remove").unwrap();
594        let root = std::fs::canonicalize(temp.path()).unwrap();
595        let keep = root.join("keep.txt").to_string_lossy().into_owned();
596
597        let plan = build_plan(temp.path(), &[keep]).unwrap();
598
599        assert_eq!(plan.delete_items.len(), 1);
600        assert_eq!(plan.delete_items[0].relative_path, "remove.txt");
601    }
602
603    #[test]
604    // Verify glob case matching follows the platform-specific policy.
605    fn glob_case_sensitivity_matches_platform() {
606        let temp = assert_fs::TempDir::new().unwrap();
607        temp.child("Keep.txt").write_str("keep").unwrap();
608
609        let plan = build_plan(temp.path(), &["keep.txt".to_owned()]).unwrap();
610
611        assert_eq!(plan.delete_items.is_empty(), cfg!(windows));
612    }
613
614    #[cfg(windows)]
615    #[test]
616    // Verify Windows root-relative patterns outside the selected root are rejected.
617    fn rejects_windows_root_relative_pattern_outside_current_root() {
618        let temp = assert_fs::TempDir::new().unwrap();
619
620        let error = build_plan(temp.path(), &["/outside/*".to_owned()]).unwrap_err();
621
622        assert!(error.to_string().contains("outside the processing root"));
623    }
624}