1use anyhow::{Context, anyhow};
2use std::ffi::OsStr;
3use std::os::unix::fs::PermissionsExt;
4use std::sync::Arc;
5use tracing::instrument;
6
7use crate::filter::TimeFilter;
8use crate::progress;
9use crate::safedir::{self, Dir, Handle};
10use crate::walk::{AdmittedEntry, AdmittedLeaf, EntryAdmission, EntryKind, LeafPermit, PermitKind};
11use crate::walk_driver::{
12 DirAction, DirPostInput, DirPreResult, EntryCx, SkippedEntry, WalkVisitor,
13 process_admitted_entry, process_entry,
14};
15
16pub type Error = crate::error::OperationError<Summary>;
19
20#[derive(Debug, Clone)]
21pub struct Settings {
22 pub fail_early: bool,
23 pub filter: Option<crate::filter::FilterSettings>,
25 pub time_filter: Option<TimeFilter>,
33 pub dry_run: Option<crate::config::DryRunMode>,
35}
36
37fn is_unsupported_io_error(err: &anyhow::Error) -> bool {
42 err.chain().any(|cause| {
43 cause
44 .downcast_ref::<std::io::Error>()
45 .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::Unsupported)
46 })
47}
48
49fn skipped_summary_for(kind: EntryKind) -> Summary {
53 match kind {
54 EntryKind::Dir => Summary {
55 directories_skipped: 1,
56 ..Default::default()
57 },
58 EntryKind::Symlink => Summary {
59 symlinks_skipped: 1,
60 ..Default::default()
61 },
62 EntryKind::File | EntryKind::Special => Summary {
63 files_skipped: 1,
64 ..Default::default()
65 },
66 }
67}
68
69#[derive(Copy, Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
70pub struct Summary {
71 pub bytes_removed: u64,
72 pub files_removed: usize,
73 pub symlinks_removed: usize,
74 pub directories_removed: usize,
75 pub files_skipped: usize,
76 pub symlinks_skipped: usize,
77 pub directories_skipped: usize,
78}
79
80impl std::ops::Add for Summary {
81 type Output = Self;
82 fn add(self, other: Self) -> Self {
83 Self {
84 bytes_removed: self.bytes_removed + other.bytes_removed,
85 files_removed: self.files_removed + other.files_removed,
86 symlinks_removed: self.symlinks_removed + other.symlinks_removed,
87 directories_removed: self.directories_removed + other.directories_removed,
88 files_skipped: self.files_skipped + other.files_skipped,
89 symlinks_skipped: self.symlinks_skipped + other.symlinks_skipped,
90 directories_skipped: self.directories_skipped + other.directories_skipped,
91 }
92 }
93}
94
95impl std::fmt::Display for Summary {
96 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
97 write!(
98 f,
99 "bytes removed: {}\n\
100 files removed: {}\n\
101 symlinks removed: {}\n\
102 directories removed: {}\n\
103 files skipped: {}\n\
104 symlinks skipped: {}\n\
105 directories skipped: {}\n",
106 bytesize::ByteSize(self.bytes_removed),
107 self.files_removed,
108 self.symlinks_removed,
109 self.directories_removed,
110 self.files_skipped,
111 self.symlinks_skipped,
112 self.directories_skipped
113 )
114 }
115}
116
117struct RelaxedDir {
124 handle: Handle,
125 original_mode: u32,
126}
127
128impl RelaxedDir {
129 fn prepare(handle: &Handle, original_mode: u32) -> std::io::Result<Self> {
131 Ok(Self {
132 handle: handle.try_clone()?,
133 original_mode,
134 })
135 }
136
137 async fn restore(self) -> std::io::Result<()> {
139 safedir::chmod_via_proc_fd(
140 &self.handle,
141 congestion::Side::Destination,
142 self.original_mode,
143 )
144 .await
145 }
146}
147
148async fn restore_retained_dir(
149 relaxed: Option<RelaxedDir>,
150 path: &std::path::Path,
151) -> anyhow::Result<()> {
152 if let Some(relaxed) = relaxed {
153 relaxed
154 .restore()
155 .await
156 .with_context(|| format!("failed to restore filter-retained directory {path:?}"))?;
157 }
158 Ok(())
159}
160
161#[instrument(skip(prog_track, settings))]
173pub async fn rm(
174 prog_track: &'static progress::Progress,
175 path: &std::path::Path,
176 settings: &Settings,
177) -> Result<Summary, Error> {
178 let permit = crate::walk::ensure_leaf_permit(PermitKind::PendingMeta, None).await;
182 enum RmRootSetup {
183 Complete(Summary),
184 Ready {
185 operand: crate::walk::RootOperand,
186 parent: Arc<Dir>,
187 entry: AdmittedEntry,
188 },
189 }
190 let setup = safedir::with_optional_fd_admission(
191 permit.as_ref().map(LeafPermit::admission),
192 async move {
193 let operand = crate::walk::split_root_operand(path)
200 .await
201 .map_err(|err| Error::new(err, Default::default()))?;
202 let parent_path = operand.parent.as_path();
203 let name = operand.name.as_os_str();
204 let path = operand.display.as_path();
205 let parent = Dir::open_parent_dir(parent_path, congestion::Side::Source)
211 .await
212 .with_context(|| format!("cannot open parent directory {parent_path:?}"))
213 .map_err(|err| Error::new(err, Default::default()))?;
214 let parent = Arc::new(parent.into_tree());
216 let entry = crate::walk::classify_admitted_entry(&parent, name, permit)
219 .await
220 .with_context(|| format!("failed reading metadata from {path:?}"))
221 .map_err(|err| Error::new(err, Default::default()))?;
222 if let Some(ref filter) = settings.filter {
223 let name_path = std::path::Path::new(name);
224 let result =
225 filter.should_include_root_item(name_path, entry.kind() == EntryKind::Dir);
226 match result {
227 crate::filter::FilterResult::Included => {}
228 result => {
229 let kind = entry.kind();
230 if let Some(mode) = settings.dry_run {
231 crate::dry_run::report_skip(path, &result, mode, kind.label_long());
232 }
233 kind.inc_skipped(prog_track);
234 return Ok(RmRootSetup::Complete(skipped_summary_for(kind)));
235 }
236 }
237 }
238 Ok(RmRootSetup::Ready {
239 operand,
240 parent,
241 entry,
242 })
243 },
244 )
245 .await?;
246 let (operand, parent, entry) = match setup {
247 RmRootSetup::Complete(summary) => return Ok(summary),
248 RmRootSetup::Ready {
249 operand,
250 parent,
251 entry,
252 } => (operand, parent, entry),
253 };
254 let name = operand.name.as_os_str();
255 let path = operand.display.as_path();
256 let visitor = Arc::new(RmVisitor {
260 prog_track,
261 settings: settings.clone(),
262 });
263 let root_cx = EntryCx::root(
264 Arc::clone(&parent),
265 name.to_owned(),
266 path.to_path_buf(),
267 prog_track,
268 );
269 process_admitted_entry(visitor, root_cx, (), entry).await }
271
272pub async fn rm_child(
296 prog_track: &'static progress::Progress,
297 parent: &Arc<Dir>,
298 name: &OsStr,
299 rel_path: &std::path::Path,
300 settings: &Settings,
301) -> Result<Summary, Error> {
302 rm_child_admitted(
303 prog_track,
304 parent,
305 name,
306 rel_path,
307 settings,
308 EntryAdmission::RootOrDelegated,
309 )
310 .await
311}
312
313pub(crate) async fn rm_child_admitted(
319 prog_track: &'static progress::Progress,
320 parent: &Arc<Dir>,
321 name: &OsStr,
322 rel_path: &std::path::Path,
323 settings: &Settings,
324 admission: EntryAdmission,
325) -> Result<Summary, Error> {
326 rm_child_with_source(
327 prog_track,
328 parent,
329 name,
330 rel_path,
331 settings,
332 RmChildSource::Unclassified(admission),
333 )
334 .await
335}
336
337pub(crate) async fn rm_child_admitted_entry(
339 prog_track: &'static progress::Progress,
340 parent: &Arc<Dir>,
341 name: &OsStr,
342 rel_path: &std::path::Path,
343 settings: &Settings,
344 entry: AdmittedEntry,
345) -> Result<Summary, Error> {
346 rm_child_with_source(
347 prog_track,
348 parent,
349 name,
350 rel_path,
351 settings,
352 RmChildSource::Admitted(entry),
353 )
354 .await
355}
356
357enum RmChildSource {
358 Unclassified(EntryAdmission),
359 Admitted(AdmittedEntry),
360}
361
362#[allow(clippy::too_many_arguments)]
363async fn rm_child_with_source(
364 prog_track: &'static progress::Progress,
365 parent: &Arc<Dir>,
366 name: &OsStr,
367 rel_path: &std::path::Path,
368 settings: &Settings,
369 source: RmChildSource,
370) -> Result<Summary, Error> {
371 let visitor = Arc::new(RmVisitor {
374 prog_track,
375 settings: settings.clone(),
376 });
377 let root_cx = EntryCx::seeded(
378 Arc::clone(parent),
379 name.to_owned(),
380 rel_path.to_path_buf(),
381 prog_track,
382 );
383 match source {
384 RmChildSource::Unclassified(admission) => {
385 process_entry(visitor, root_cx, (), admission).await
386 }
387 RmChildSource::Admitted(entry) => process_admitted_entry(visitor, root_cx, (), entry).await,
388 }
389}
390struct RmVisitor {
396 prog_track: &'static progress::Progress,
397 settings: Settings,
398}
399
400struct RmDirState {
403 relaxed: Option<RelaxedDir>,
406 time_metadata: Option<anyhow::Result<std::fs::Metadata>>,
410 matches_no_include: bool,
415}
416
417impl WalkVisitor for RmVisitor {
418 type Summary = Summary;
419 type DirContext = ();
420 type DirState = RmDirState;
421
422 fn root_dir_context(&self) {}
423
424 fn permit_kind(&self) -> PermitKind {
425 PermitKind::PendingMeta
429 }
430
431 fn fail_early(&self) -> bool {
432 self.settings.fail_early
433 }
434
435 fn filter(&self) -> Option<&crate::filter::FilterSettings> {
436 self.settings.filter.as_ref()
437 }
438
439 fn filter_requires_admitted_entry(&self) -> bool {
440 true
441 }
442
443 fn filter_allows_hint_only_skip(&self, _dir_ctx: &Self::DirContext) -> bool {
444 self.settings.dry_run.is_none()
447 }
448
449 fn on_skip(
450 &self,
451 cx: &SkippedEntry<'_>,
452 kind: EntryKind,
453 skip_result: &crate::filter::FilterResult,
454 ) -> Summary {
455 cx.report_skip(self.settings.dry_run, skip_result, kind);
458 skipped_summary_for(kind)
459 }
460
461 async fn visit_leaf(
462 &self,
463 cx: &EntryCx,
464 _parent_ctx: &(),
465 leaf: AdmittedLeaf,
466 ) -> Result<Summary, Error> {
467 let kind = leaf.kind();
468 let prog_track = self.prog_track;
469 let settings = &self.settings;
470 let parent = &cx.parent;
471 let name = cx.name.as_os_str();
472 let path = cx.real_path.as_path();
473 tracing::debug!("not a directory, just remove");
474 let is_symlink = kind == EntryKind::Symlink;
475 let file_size = if is_symlink {
476 0
477 } else {
478 crate::preserve::Metadata::size(leaf.handle().meta())
479 };
480 if let Some(ref time_filter) = settings.time_filter {
482 let entry_type = if is_symlink { "symlink" } else { "file" };
483 let make_skipped_summary = || {
484 tracing::debug!("skipping {:?} due to time filter", &path);
485 if is_symlink {
486 prog_track.symlinks_skipped.inc();
487 Summary {
488 symlinks_skipped: 1,
489 ..Default::default()
490 }
491 } else {
492 prog_track.files_skipped.inc();
493 Summary {
494 files_skipped: 1,
495 ..Default::default()
496 }
497 }
498 };
499 let metadata =
503 match safedir::stat_meta_via_proc_fd(leaf.handle(), congestion::Side::Source).await
504 {
505 Ok(md) => md,
506 Err(err) => {
507 let err = anyhow::Error::new(err).context(format!(
508 "failed reading metadata for time filter on {path:?}"
509 ));
510 if settings.fail_early {
511 return Err(Error::new(err, Default::default()));
512 }
513 if is_unsupported_io_error(&err) {
515 tracing::warn!(
516 "time filter evaluation unsupported for {} {:?}, skipping: {:#}",
517 entry_type,
518 &path,
519 &err
520 );
521 } else {
522 tracing::error!(
523 "time filter evaluation failed for {} {:?}, skipping: {:#}",
524 entry_type,
525 &path,
526 &err
527 );
528 }
529 return Ok(make_skipped_summary());
530 }
531 };
532 match time_filter.matches(&metadata) {
533 Ok(result) => {
534 if let Some(skip_reason) = result.as_skip_reason() {
535 if let Some(mode) = settings.dry_run {
536 crate::dry_run::report_time_skip(path, skip_reason, mode, entry_type);
537 }
538 return Ok(make_skipped_summary());
539 }
540 }
541 Err(err) => {
542 let err = err.context(format!("failed evaluating time filter on {:?}", &path));
543 if settings.fail_early {
544 return Err(Error::new(err, Default::default()));
545 }
546 if is_unsupported_io_error(&err) {
550 tracing::warn!(
551 "time filter evaluation unsupported for {} {:?}, skipping: {:#}",
552 entry_type,
553 &path,
554 &err
555 );
556 } else {
557 tracing::error!(
558 "time filter evaluation failed for {} {:?}, skipping: {:#}",
559 entry_type,
560 &path,
561 &err
562 );
563 }
564 return Ok(make_skipped_summary());
565 }
566 }
567 }
568 if settings.dry_run.is_some() {
570 let entry_type = if is_symlink { "symlink" } else { "file" };
571 crate::dry_run::report_action("remove", path, None, entry_type);
572 return Ok(Summary {
573 bytes_removed: file_size,
574 files_removed: if is_symlink { 0 } else { 1 },
575 symlinks_removed: if is_symlink { 1 } else { 0 },
576 ..Default::default()
577 });
578 }
579 if let Err(err) = parent
590 .unlink_at_on(name, congestion::Side::Destination)
591 .await
592 .with_context(|| format!("failed removing {:?}", &path))
593 {
594 return Err(Error::new(err, Default::default()));
595 }
596 if is_symlink {
597 prog_track.symlinks_removed.inc();
598 return Ok(Summary {
599 symlinks_removed: 1,
600 ..Default::default()
601 });
602 }
603 prog_track.files_removed.inc();
604 prog_track.bytes_removed.add(file_size);
605 Ok(Summary {
606 bytes_removed: file_size,
607 files_removed: 1,
608 ..Default::default()
609 })
610 }
611
612 async fn dir_pre(&self, cx: &EntryCx, _parent_ctx: &(), handle: &Handle) -> DirPreResult<Self> {
613 let settings = &self.settings;
614 let path = cx.real_path.as_path();
615 tracing::debug!("remove contents of the directory first");
616 let time_metadata: Option<anyhow::Result<std::fs::Metadata>> =
625 if settings.time_filter.is_some() {
626 Some(
627 safedir::stat_meta_via_proc_fd(handle, congestion::Side::Source)
628 .await
629 .map_err(|err| {
630 anyhow::Error::new(err).context(format!(
631 "failed reading metadata for time filter on {path:?}"
632 ))
633 }),
634 )
635 } else {
636 None
637 };
638 let matches_no_include = settings
644 .filter
645 .as_ref()
646 .is_some_and(|f| f.has_includes() && !f.directly_matches_include(&cx.rel_path, true));
647 let mut relaxed: Option<RelaxedDir> = None;
654 if settings.dry_run.is_none() {
655 let original_mode =
656 crate::preserve::Metadata::permissions(handle.meta()).mode() & 0o7777;
657 if original_mode & 0o700 != 0o700 {
662 tracing::debug!("directory is not writable/traversable - relax the permissions");
663 let prepared = RelaxedDir::prepare(handle, original_mode)
666 .with_context(|| format!("failed to pin relaxed directory {path:?}"))
667 .map_err(|err| Error::new(err, Default::default()))?;
668 safedir::chmod_via_proc_fd(handle, congestion::Side::Destination, 0o700)
671 .await
672 .with_context(|| {
673 format!("failed to make {path:?} directory readable and writable")
674 })
675 .map_err(|err| Error::new(err, Default::default()))?;
676 relaxed = Some(prepared);
677 }
678 }
679 let dir = cx
683 .parent
684 .open_dir(&cx.name)
685 .await
686 .with_context(|| format!("failed reading directory {path:?}"))
687 .map_err(|err| Error::new(err, Default::default()))?;
688 dir.verify_same_inode(handle)
689 .await
690 .with_context(|| {
691 format!("directory {path:?} changed identity before descent (possible TOCTOU swap)")
692 })
693 .map_err(|err| Error::new(err, Default::default()))?;
694 let dir = Arc::new(dir);
695 Ok(DirAction::Descend {
696 dir,
697 child_ctx: (),
698 state: RmDirState {
699 relaxed,
700 time_metadata,
701 matches_no_include,
702 },
703 })
704 }
705
706 async fn dir_post(
707 &self,
708 cx: &EntryCx,
709 state: RmDirState,
710 child_result: DirPostInput<Self>,
711 ) -> Result<Summary, Error> {
712 let prog_track = self.prog_track;
713 let settings = &self.settings;
714 let path = cx.real_path.as_path();
715 let RmDirState {
716 relaxed,
717 time_metadata,
718 matches_no_include,
719 } = state;
720 let mut rm_summary = match child_result {
723 Ok((summary, _)) => summary,
724 Err(err) => return Err(err),
725 };
726 tracing::debug!("finally remove the empty directory");
727 let anything_removed = rm_summary.files_removed > 0
728 || rm_summary.symlinks_removed > 0
729 || rm_summary.directories_removed > 0;
730 let anything_skipped = rm_summary.files_skipped > 0
731 || rm_summary.symlinks_skipped > 0
732 || rm_summary.directories_skipped > 0;
733 let traversed_only = !anything_removed && matches_no_include;
736 let dir_passes_time_filter: bool = if let Some(ref time_filter) = settings.time_filter {
743 let matched = time_metadata.unwrap().and_then(|md| {
746 time_filter.matches(&md).map_err(|err| {
747 err.context(format!("failed evaluating time filter on {path:?}"))
748 })
749 });
750 match matched {
751 Ok(result) => match result.as_skip_reason() {
752 Some(reason) => {
753 if let Some(mode) = settings.dry_run {
754 crate::dry_run::report_time_skip(path, reason, mode, "dir");
755 }
756 false
757 }
758 None => true,
759 },
760 Err(err) => {
761 if settings.fail_early {
762 return Err(Error::new(err, rm_summary));
763 }
764 if is_unsupported_io_error(&err) {
768 tracing::warn!(
769 "time filter evaluation unsupported for dir {:?}, leaving it intact: {:#}",
770 &path,
771 &err
772 );
773 } else {
774 tracing::error!(
775 "time filter evaluation failed for dir {:?}, leaving it intact: {:#}",
776 &path,
777 &err
778 );
779 }
780 false
781 }
782 }
783 } else {
784 true
785 };
786 if settings.dry_run.is_some() {
793 if traversed_only || anything_skipped || !dir_passes_time_filter {
794 tracing::debug!(
795 "dry-run: directory {:?} would not be removed (removed={}, skipped={}, time_ok={})",
796 &path,
797 anything_removed,
798 anything_skipped,
799 dir_passes_time_filter
800 );
801 if !dir_passes_time_filter {
802 prog_track.directories_skipped.inc();
803 rm_summary.directories_skipped += 1;
804 }
805 } else {
806 crate::dry_run::report_action("remove", path, None, "dir");
807 rm_summary.directories_removed += 1;
808 }
809 return Ok(rm_summary);
810 }
811 if traversed_only {
815 tracing::debug!(
816 "directory {:?} had nothing removed, leaving it intact",
817 &path
818 );
819 restore_retained_dir(relaxed, path)
820 .await
821 .map_err(|err| Error::new(err, rm_summary))?;
822 return Ok(rm_summary);
823 }
824 if !dir_passes_time_filter {
827 tracing::debug!(
828 "directory {:?} skipped by time filter, leaving it intact",
829 &path
830 );
831 prog_track.directories_skipped.inc();
832 rm_summary.directories_skipped += 1;
833 restore_retained_dir(relaxed, path)
834 .await
835 .map_err(|err| Error::new(err, rm_summary))?;
836 return Ok(rm_summary);
837 }
838 #[cfg(test)]
845 let _final_rmdir_gate_visit = {
846 crate::testutils::wait_on_blocking_path_gate(path, libc::AT_FDCWD)
849 };
850 let any_filter_active = settings.filter.is_some() || settings.time_filter.is_some();
851 match cx
852 .parent
853 .rmdir_at_on(&cx.name, congestion::Side::Destination)
854 .await
855 {
856 Ok(()) => {
857 prog_track.directories_removed.inc();
858 rm_summary.directories_removed += 1;
859 }
860 Err(err) if any_filter_active => {
861 if err.kind() == std::io::ErrorKind::DirectoryNotEmpty
865 || err.raw_os_error() == Some(39)
866 {
867 tracing::info!(
868 "directory {:?} not empty after filtering, leaving it intact",
869 &path
870 );
871 restore_retained_dir(relaxed, path)
872 .await
873 .map_err(|restore_err| Error::new(restore_err, rm_summary))?;
874 } else {
875 return Err(Error::new(
876 anyhow!(err).context(format!("failed removing directory {:?}", &path)),
877 rm_summary,
878 ));
879 }
880 }
881 Err(err) => {
882 return Err(Error::new(
883 anyhow!(err).context(format!("failed removing directory {:?}", &path)),
884 rm_summary,
885 ));
886 }
887 }
888 Ok(rm_summary)
889 }
890}
891
892#[cfg(test)]
893mod tests {
894 use super::*;
895 use crate::config::DryRunMode;
896 use crate::testutils;
897 use crate::walk_driver::ProcessedChildren;
898 use tracing_test::traced_test;
899
900 static PROGRESS: std::sync::LazyLock<progress::Progress> =
901 std::sync::LazyLock::new(progress::Progress::new);
902
903 #[tokio::test]
904 #[traced_test]
905 async fn no_write_permission() -> Result<(), anyhow::Error> {
906 let tmp_dir = testutils::setup_test_dir().await?;
907 let test_path = tmp_dir.as_path();
908 let filepaths = vec![
909 test_path.join("foo").join("0.txt"),
910 test_path.join("foo").join("bar").join("2.txt"),
911 test_path.join("foo").join("baz").join("4.txt"),
912 test_path.join("foo").join("baz"),
913 ];
914 for fpath in &filepaths {
915 tokio::fs::set_permissions(&fpath, std::fs::Permissions::from_mode(0o555)).await?;
917 }
918 let summary = rm(
919 &PROGRESS,
920 &test_path.join("foo"),
921 &Settings {
922 fail_early: false,
923 filter: None,
924 dry_run: None,
925 time_filter: None,
926 },
927 )
928 .await?;
929 assert!(!test_path.join("foo").exists());
930 assert_eq!(summary.files_removed, 5);
931 assert_eq!(summary.symlinks_removed, 2);
932 assert_eq!(summary.directories_removed, 3);
933 Ok(())
934 }
935
936 #[tokio::test]
937 #[traced_test]
938 async fn removal_error_leaves_temporary_directory_mode() -> Result<(), anyhow::Error> {
939 let tmp = tempfile::tempdir()?;
948 let parent = tmp.path().join("parent");
949 let dst = parent.join("dst");
950 tokio::fs::create_dir(&parent).await?;
951 tokio::fs::create_dir(&dst).await?;
952 tokio::fs::write(dst.join("inside.txt"), b"x").await?;
953 tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o555)).await?;
955 tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o555)).await?;
957
958 let result = rm(
959 &PROGRESS,
960 &dst,
961 &Settings {
962 fail_early: false,
963 filter: None,
964 dry_run: None,
965 time_filter: None,
966 },
967 )
968 .await;
969
970 tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o755)).await?;
972
973 assert!(
974 result.is_err(),
975 "rm must fail when its dst can be emptied but the parent dir blocks remove_dir"
976 );
977 let mode = tokio::fs::metadata(&dst).await?.permissions().mode() & 0o7777;
978 assert_eq!(
979 mode, 0o700,
980 "a removal error unexpectedly restored the temporary directory mode (got {mode:o}o)"
981 );
982
983 tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o755)).await?;
985 Ok(())
986 }
987
988 #[tokio::test]
989 #[traced_test]
990 async fn parent_dir_no_write_permission() -> Result<(), anyhow::Error> {
991 let tmp_dir = testutils::setup_test_dir().await?;
992 let test_path = tmp_dir.as_path();
993 tokio::fs::set_permissions(
995 &test_path.join("foo").join("bar"),
996 std::fs::Permissions::from_mode(0o555),
997 )
998 .await?;
999 let result = rm(
1000 &PROGRESS,
1001 &test_path.join("foo").join("bar").join("2.txt"),
1002 &Settings {
1003 fail_early: true,
1004 filter: None,
1005 dry_run: None,
1006 time_filter: None,
1007 },
1008 )
1009 .await;
1010 assert!(result.is_err());
1012 let err = result.unwrap_err();
1013 let err_string = format!("{:#}", err);
1014 assert!(
1016 err_string.contains("Permission denied") || err_string.contains("permission denied"),
1017 "Error should contain 'Permission denied' but got: {}",
1018 err_string
1019 );
1020 Ok(())
1021 }
1022
1023 mod filter_tests {
1024 use super::*;
1025 use crate::filter::FilterSettings;
1026 #[tokio::test]
1028 #[traced_test]
1029 async fn test_path_pattern_matches_nested_files() -> Result<(), anyhow::Error> {
1030 let tmp_dir = testutils::setup_test_dir().await?;
1031 let test_path = tmp_dir.as_path();
1032 let mut filter = FilterSettings::new();
1034 filter.add_include("bar/*.txt").unwrap();
1035 let summary = rm(
1036 &PROGRESS,
1037 &test_path.join("foo"),
1038 &Settings {
1039 fail_early: false,
1040 filter: Some(filter),
1041 dry_run: None,
1042 time_filter: None,
1043 },
1044 )
1045 .await?;
1046 assert_eq!(
1048 summary.files_removed, 3,
1049 "should remove 3 files matching bar/*.txt"
1050 );
1051 assert_eq!(summary.bytes_removed, 3, "should report 3 bytes removed");
1053 assert!(
1055 !test_path.join("foo/bar/1.txt").exists(),
1056 "bar/1.txt should be removed"
1057 );
1058 assert!(
1059 !test_path.join("foo/bar/2.txt").exists(),
1060 "bar/2.txt should be removed"
1061 );
1062 assert!(
1063 !test_path.join("foo/bar/3.txt").exists(),
1064 "bar/3.txt should be removed"
1065 );
1066 assert!(
1068 test_path.join("foo/0.txt").exists(),
1069 "0.txt should still exist"
1070 );
1071 Ok(())
1072 }
1073 #[tokio::test]
1075 #[traced_test]
1076 async fn test_filter_applies_to_single_file_source() -> Result<(), anyhow::Error> {
1077 let tmp_dir = testutils::setup_test_dir().await?;
1078 let test_path = tmp_dir.as_path();
1079 let mut filter = FilterSettings::new();
1081 filter.add_exclude("*.txt").unwrap();
1082 let summary = rm(
1083 &PROGRESS,
1084 &test_path.join("foo/0.txt"), &Settings {
1086 fail_early: false,
1087 filter: Some(filter),
1088 dry_run: None,
1089 time_filter: None,
1090 },
1091 )
1092 .await?;
1093 assert_eq!(
1095 summary.files_removed, 0,
1096 "file matching exclude pattern should not be removed"
1097 );
1098 assert!(
1099 test_path.join("foo/0.txt").exists(),
1100 "excluded file should still exist"
1101 );
1102 Ok(())
1103 }
1104 #[tokio::test]
1106 #[traced_test]
1107 async fn test_filter_applies_to_root_directory() -> Result<(), anyhow::Error> {
1108 let test_path = testutils::create_temp_dir().await?;
1109 tokio::fs::create_dir_all(test_path.join("excluded_dir")).await?;
1111 tokio::fs::write(test_path.join("excluded_dir/file.txt"), "content").await?;
1112 let mut filter = FilterSettings::new();
1114 filter.add_exclude("*_dir/").unwrap();
1115 let result = rm(
1116 &PROGRESS,
1117 &test_path.join("excluded_dir"),
1118 &Settings {
1119 fail_early: false,
1120 filter: Some(filter),
1121 dry_run: None,
1122 time_filter: None,
1123 },
1124 )
1125 .await?;
1126 assert_eq!(
1128 result.directories_removed, 0,
1129 "root directory matching exclude should not be removed"
1130 );
1131 assert!(
1132 test_path.join("excluded_dir").exists(),
1133 "excluded root directory should still exist"
1134 );
1135 Ok(())
1136 }
1137 #[tokio::test]
1139 #[traced_test]
1140 async fn test_filter_applies_to_root_symlink() -> Result<(), anyhow::Error> {
1141 let test_path = testutils::create_temp_dir().await?;
1142 tokio::fs::write(test_path.join("target.txt"), "content").await?;
1144 tokio::fs::symlink(
1145 test_path.join("target.txt"),
1146 test_path.join("excluded_link"),
1147 )
1148 .await?;
1149 let mut filter = FilterSettings::new();
1151 filter.add_exclude("*_link").unwrap();
1152 let result = rm(
1153 &PROGRESS,
1154 &test_path.join("excluded_link"),
1155 &Settings {
1156 fail_early: false,
1157 filter: Some(filter),
1158 dry_run: None,
1159 time_filter: None,
1160 },
1161 )
1162 .await?;
1163 assert_eq!(
1165 result.symlinks_removed, 0,
1166 "root symlink matching exclude should not be removed"
1167 );
1168 assert!(
1169 test_path.join("excluded_link").exists(),
1170 "excluded root symlink should still exist"
1171 );
1172 Ok(())
1173 }
1174 #[tokio::test]
1176 #[traced_test]
1177 async fn test_combined_include_exclude_patterns() -> Result<(), anyhow::Error> {
1178 let tmp_dir = testutils::setup_test_dir().await?;
1179 let test_path = tmp_dir.as_path();
1180 let mut filter = FilterSettings::new();
1187 filter.add_include("bar/*.txt").unwrap();
1188 filter.add_exclude("bar/2.txt").unwrap();
1189 let summary = rm(
1190 &PROGRESS,
1191 &test_path.join("foo"),
1192 &Settings {
1193 fail_early: false,
1194 filter: Some(filter),
1195 dry_run: None,
1196 time_filter: None,
1197 },
1198 )
1199 .await?;
1200 assert_eq!(summary.files_removed, 2, "should remove 2 files");
1203 assert_eq!(
1204 summary.files_skipped, 2,
1205 "should skip 2 files (bar/2.txt excluded, 0.txt no match)"
1206 );
1207 assert!(
1209 !test_path.join("foo/bar/1.txt").exists(),
1210 "bar/1.txt should be removed"
1211 );
1212 assert!(
1213 test_path.join("foo/bar/2.txt").exists(),
1214 "bar/2.txt should be excluded"
1215 );
1216 assert!(
1217 !test_path.join("foo/bar/3.txt").exists(),
1218 "bar/3.txt should be removed"
1219 );
1220 Ok(())
1221 }
1222 #[tokio::test]
1224 #[traced_test]
1225 async fn test_skipped_counts_comprehensive() -> Result<(), anyhow::Error> {
1226 let tmp_dir = testutils::setup_test_dir().await?;
1227 let test_path = tmp_dir.as_path();
1228 let mut filter = FilterSettings::new();
1235 filter.add_exclude("bar/").unwrap();
1236 let summary = rm(
1237 &PROGRESS,
1238 &test_path.join("foo"),
1239 &Settings {
1240 fail_early: false,
1241 filter: Some(filter),
1242 dry_run: None,
1243 time_filter: None,
1244 },
1245 )
1246 .await?;
1247 assert_eq!(summary.files_removed, 2, "should remove 2 files");
1252 assert_eq!(summary.symlinks_removed, 2, "should remove 2 symlinks");
1253 assert_eq!(
1254 summary.directories_removed, 1,
1255 "should remove 1 directory (baz only, foo not empty)"
1256 );
1257 assert_eq!(
1258 summary.directories_skipped, 1,
1259 "should skip 1 directory (bar)"
1260 );
1261 assert!(
1263 test_path.join("foo/bar").exists(),
1264 "bar directory should still exist"
1265 );
1266 assert!(
1268 test_path.join("foo").exists(),
1269 "foo directory should still exist (contains bar)"
1270 );
1271 Ok(())
1272 }
1273 #[tokio::test]
1276 #[traced_test]
1277 async fn test_empty_dir_not_removed_when_only_traversed() -> Result<(), anyhow::Error> {
1278 let test_path = testutils::create_temp_dir().await?;
1279 tokio::fs::write(test_path.join("foo"), "content").await?;
1285 tokio::fs::write(test_path.join("bar"), "content").await?;
1286 tokio::fs::create_dir(test_path.join("baz")).await?;
1287 let mut filter = FilterSettings::new();
1289 filter.add_include("foo").unwrap();
1290 let summary = rm(
1291 &PROGRESS,
1292 &test_path,
1293 &Settings {
1294 fail_early: false,
1295 filter: Some(filter),
1296 dry_run: None,
1297 time_filter: None,
1298 },
1299 )
1300 .await?;
1301 assert_eq!(summary.files_removed, 1, "should remove only 'foo' file");
1303 assert_eq!(
1304 summary.directories_removed, 0,
1305 "should NOT remove empty 'baz' directory"
1306 );
1307 assert!(!test_path.join("foo").exists(), "foo should be removed");
1309 assert!(test_path.join("bar").exists(), "bar should still exist");
1311 assert!(
1313 test_path.join("baz").exists(),
1314 "empty baz directory should NOT be removed"
1315 );
1316 Ok(())
1317 }
1318 #[tokio::test]
1322 #[traced_test]
1323 async fn test_exclude_only_removes_empty_directory() -> Result<(), anyhow::Error> {
1324 let test_path = testutils::create_temp_dir().await?;
1325 tokio::fs::write(test_path.join("foo"), "content").await?;
1331 tokio::fs::write(test_path.join("bar.log"), "content").await?;
1332 tokio::fs::create_dir(test_path.join("baz")).await?;
1333 let mut filter = FilterSettings::new();
1335 filter.add_exclude("*.log").unwrap();
1336 let summary = rm(
1337 &PROGRESS,
1338 &test_path,
1339 &Settings {
1340 fail_early: false,
1341 filter: Some(filter),
1342 dry_run: None,
1343 time_filter: None,
1344 },
1345 )
1346 .await?;
1347 assert_eq!(summary.files_removed, 1, "should remove 'foo'");
1349 assert_eq!(summary.files_skipped, 1, "should skip 'bar.log'");
1350 assert_eq!(
1351 summary.directories_removed, 1,
1352 "should remove empty 'baz' directory"
1353 );
1354 assert!(!test_path.join("foo").exists(), "foo should be removed");
1355 assert!(
1356 test_path.join("bar.log").exists(),
1357 "bar.log should still exist"
1358 );
1359 assert!(
1360 !test_path.join("baz").exists(),
1361 "empty baz directory should be removed"
1362 );
1363 Ok(())
1364 }
1365 #[tokio::test]
1367 #[traced_test]
1368 async fn test_dry_run_empty_dir_not_reported_as_removed() -> Result<(), anyhow::Error> {
1369 let test_path = testutils::create_temp_dir().await?;
1370 tokio::fs::write(test_path.join("foo"), "content").await?;
1376 tokio::fs::write(test_path.join("bar"), "content").await?;
1377 tokio::fs::create_dir(test_path.join("baz")).await?;
1378 let mut filter = FilterSettings::new();
1380 filter.add_include("foo").unwrap();
1381 let summary = rm(
1382 &PROGRESS,
1383 &test_path,
1384 &Settings {
1385 fail_early: false,
1386 filter: Some(filter),
1387 dry_run: Some(DryRunMode::Explain),
1388 time_filter: None,
1389 },
1390 )
1391 .await?;
1392 assert_eq!(
1394 summary.files_removed, 1,
1395 "should report only 'foo' would be removed"
1396 );
1397 assert_eq!(
1398 summary.directories_removed, 0,
1399 "should NOT report empty 'baz' would be removed"
1400 );
1401 assert!(test_path.join("foo").exists(), "foo should still exist");
1403 assert!(test_path.join("bar").exists(), "bar should still exist");
1404 assert!(test_path.join("baz").exists(), "baz should still exist");
1405 Ok(())
1406 }
1407 #[tokio::test]
1410 #[traced_test]
1411 async fn test_include_directly_matched_empty_dir_is_removed() -> Result<(), anyhow::Error> {
1412 let test_path = testutils::create_temp_dir().await?;
1413 tokio::fs::write(test_path.join("foo"), "content").await?;
1418 tokio::fs::create_dir(test_path.join("baz")).await?;
1419 let mut filter = FilterSettings::new();
1421 filter.add_include("baz/").unwrap();
1422 let summary = rm(
1423 &PROGRESS,
1424 &test_path,
1425 &Settings {
1426 fail_early: false,
1427 filter: Some(filter),
1428 dry_run: None,
1429 time_filter: None,
1430 },
1431 )
1432 .await?;
1433 assert_eq!(
1434 summary.directories_removed, 1,
1435 "should remove directly matched empty 'baz' directory"
1436 );
1437 assert_eq!(summary.files_removed, 0, "should not remove 'foo'");
1438 assert!(test_path.join("foo").exists(), "foo should still exist");
1439 assert!(
1440 !test_path.join("baz").exists(),
1441 "directly matched empty baz directory should be removed"
1442 );
1443 Ok(())
1444 }
1445 }
1446 mod dry_run_tests {
1447 use super::*;
1448 use crate::filter::FilterSettings;
1449
1450 #[tokio::test(flavor = "current_thread")]
1451 async fn dry_run_rechecks_a_directory_hint_before_previewing_an_included_file()
1452 -> Result<(), anyhow::Error> {
1453 let root = testutils::create_temp_dir().await?;
1454 let target = root.join("target");
1455 tokio::fs::create_dir(&target).await?;
1456 tokio::fs::write(target.join("node"), "CURRENT").await?;
1457 let mut filter = FilterSettings::new();
1458 filter.add_exclude("node/")?;
1459 assert!(!matches!(
1460 filter.should_include(std::path::Path::new("node"), true),
1461 crate::filter::FilterResult::Included
1462 ));
1463 assert!(matches!(
1464 filter.should_include(std::path::Path::new("node"), false),
1465 crate::filter::FilterResult::Included
1466 ));
1467 let settings = Settings {
1468 fail_early: false,
1469 filter: Some(filter),
1470 dry_run: Some(DryRunMode::Brief),
1471 time_filter: None,
1472 };
1473 let admission = testutils::AdmissionLimit::new().await;
1474 admission.set_files_in_flight(1);
1475 let target_dir =
1476 Arc::new(Dir::open_root_dir(&target, false, congestion::Side::Source).await?);
1477 let visitor = Arc::new(RmVisitor {
1478 prog_track: &PROGRESS,
1479 settings,
1480 });
1481 let root_cx = EntryCx::root(
1482 Arc::clone(&target_dir),
1483 std::ffi::OsString::from("target"),
1484 target.clone(),
1485 &PROGRESS,
1486 );
1487 let result = admission
1488 .run_with_timeout(
1489 std::time::Duration::from_secs(20),
1490 crate::task_scope::scope_tasks(crate::walk_driver::walk_dir_entries(
1491 visitor,
1492 target_dir,
1493 &root_cx,
1494 &(),
1495 vec![(std::ffi::OsString::from("node"), Some(EntryKind::Dir))],
1496 )),
1497 )
1498 .await
1499 .context("rm dry-run hint recheck did not finish at a cap of one")??;
1500 let returned = admission
1501 .run_with_timeout(
1502 std::time::Duration::from_secs(20),
1503 throttle::pending_meta_permit(),
1504 )
1505 .await
1506 .context("rm dry-run hint recheck did not return pending-meta capacity")?;
1507 drop(returned);
1508 let (summary, processed) = result;
1509 assert!(processed.names().is_none());
1510 assert_eq!(summary.files_removed, 1);
1511 assert_eq!(summary.directories_skipped, 0);
1512 assert_eq!(
1513 tokio::fs::read_to_string(target.join("node")).await?,
1514 "CURRENT"
1515 );
1516 Ok(())
1517 }
1518
1519 #[tokio::test]
1521 #[traced_test]
1522 async fn test_dry_run_preserves_readonly_permissions() -> Result<(), anyhow::Error> {
1523 let tmp_dir = testutils::setup_test_dir().await?;
1524 let test_path = tmp_dir.as_path();
1525 let readonly_dir = test_path.join("foo/bar");
1526 tokio::fs::set_permissions(&readonly_dir, std::fs::Permissions::from_mode(0o555))
1528 .await?;
1529 let before_mode = tokio::fs::metadata(&readonly_dir)
1531 .await?
1532 .permissions()
1533 .mode()
1534 & 0o777;
1535 assert_eq!(
1536 before_mode, 0o555,
1537 "directory should be read-only before dry-run"
1538 );
1539 let summary = rm(
1540 &PROGRESS,
1541 &readonly_dir,
1542 &Settings {
1543 fail_early: false,
1544 filter: None,
1545 dry_run: Some(DryRunMode::Brief),
1546 time_filter: None,
1547 },
1548 )
1549 .await?;
1550 assert!(
1552 readonly_dir.exists(),
1553 "directory should still exist after dry-run"
1554 );
1555 let after_mode = tokio::fs::metadata(&readonly_dir)
1557 .await?
1558 .permissions()
1559 .mode()
1560 & 0o777;
1561 assert_eq!(
1562 after_mode, 0o555,
1563 "dry-run should not modify directory permissions"
1564 );
1565 assert!(
1567 summary.directories_removed > 0 || summary.files_removed > 0,
1568 "dry-run should report what would be removed"
1569 );
1570 Ok(())
1571 }
1572 #[tokio::test]
1575 #[traced_test]
1576 async fn test_dry_run_with_filter_non_empty_directory() -> Result<(), anyhow::Error> {
1577 let tmp_dir = testutils::setup_test_dir().await?;
1578 let test_path = tmp_dir.as_path();
1579 let mut filter = crate::filter::FilterSettings::new();
1586 filter.add_exclude("bar/").unwrap();
1587 let summary = rm(
1588 &PROGRESS,
1589 &test_path.join("foo"),
1590 &Settings {
1591 fail_early: false,
1592 filter: Some(filter),
1593 dry_run: Some(DryRunMode::Brief),
1594 time_filter: None,
1595 },
1596 )
1597 .await?;
1598 assert!(
1600 test_path.join("foo").exists(),
1601 "foo should still exist after dry-run"
1602 );
1603 assert_eq!(
1609 summary.files_removed, 2,
1610 "should report 2 files would be removed"
1611 );
1612 assert_eq!(
1613 summary.symlinks_removed, 2,
1614 "should report 2 symlinks would be removed"
1615 );
1616 assert_eq!(
1617 summary.directories_removed, 1,
1618 "should report only baz (not foo) would be removed"
1619 );
1620 assert_eq!(
1621 summary.directories_skipped, 1,
1622 "should report bar directory skipped"
1623 );
1624 Ok(())
1625 }
1626 #[tokio::test]
1629 #[traced_test]
1630 async fn test_dry_run_exclude_only_reports_empty_dir_removed() -> Result<(), anyhow::Error>
1631 {
1632 let test_path = testutils::create_temp_dir().await?;
1633 tokio::fs::write(test_path.join("foo"), "content").await?;
1639 tokio::fs::write(test_path.join("bar.log"), "content").await?;
1640 tokio::fs::create_dir(test_path.join("baz")).await?;
1641 let mut filter = FilterSettings::new();
1643 filter.add_exclude("*.log").unwrap();
1644 let summary = rm(
1645 &PROGRESS,
1646 &test_path,
1647 &Settings {
1648 fail_early: false,
1649 filter: Some(filter),
1650 dry_run: Some(DryRunMode::Explain),
1651 time_filter: None,
1652 },
1653 )
1654 .await?;
1655 assert_eq!(
1657 summary.files_removed, 1,
1658 "should report 'foo' would be removed"
1659 );
1660 assert_eq!(
1661 summary.files_skipped, 1,
1662 "should report 'bar.log' would be skipped"
1663 );
1664 assert_eq!(
1665 summary.directories_removed, 1,
1666 "should report empty 'baz' directory would be removed"
1667 );
1668 assert!(test_path.join("foo").exists(), "foo should still exist");
1670 assert!(
1671 test_path.join("bar.log").exists(),
1672 "bar.log should still exist"
1673 );
1674 assert!(test_path.join("baz").exists(), "baz should still exist");
1675 Ok(())
1676 }
1677 #[tokio::test]
1680 #[traced_test]
1681 async fn test_dry_run_include_directly_matched_empty_dir_reported()
1682 -> Result<(), anyhow::Error> {
1683 let test_path = testutils::create_temp_dir().await?;
1684 tokio::fs::write(test_path.join("foo"), "content").await?;
1689 tokio::fs::create_dir(test_path.join("baz")).await?;
1690 let mut filter = FilterSettings::new();
1692 filter.add_include("baz/").unwrap();
1693 let summary = rm(
1694 &PROGRESS,
1695 &test_path,
1696 &Settings {
1697 fail_early: false,
1698 filter: Some(filter),
1699 dry_run: Some(DryRunMode::Explain),
1700 time_filter: None,
1701 },
1702 )
1703 .await?;
1704 assert_eq!(
1705 summary.directories_removed, 1,
1706 "should report directly matched empty 'baz' would be removed"
1707 );
1708 assert_eq!(summary.files_removed, 0, "should not report 'foo'");
1709 assert!(test_path.join("foo").exists(), "foo should still exist");
1711 assert!(test_path.join("baz").exists(), "baz should still exist");
1712 Ok(())
1713 }
1714 }
1715 mod time_filter_tests {
1716 use super::*;
1717 use crate::filter::TimeFilter;
1718
1719 fn set_mtime_age(path: &std::path::Path, age: std::time::Duration) -> anyhow::Result<()> {
1720 let past = filetime::FileTime::from_system_time(std::time::SystemTime::now() - age);
1721 filetime::set_file_mtime(path, past)?;
1722 Ok(())
1723 }
1724
1725 #[tokio::test]
1727 #[traced_test]
1728 async fn removes_files_older_than_modified_before() -> Result<(), anyhow::Error> {
1729 let test_path = testutils::create_temp_dir().await?;
1730 let file = test_path.join("old.txt");
1731 tokio::fs::write(&file, "x").await?;
1732 set_mtime_age(&file, std::time::Duration::from_secs(7200))?;
1733 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1735 let summary = rm(
1736 &PROGRESS,
1737 &test_path,
1738 &Settings {
1739 fail_early: false,
1740 filter: None,
1741 time_filter: Some(TimeFilter {
1742 modified_before: Some(std::time::Duration::from_secs(3600)),
1743 created_before: None,
1744 }),
1745 dry_run: None,
1746 },
1747 )
1748 .await?;
1749 assert_eq!(summary.files_removed, 1, "old file should be removed");
1750 assert_eq!(summary.files_skipped, 0);
1751 assert!(!file.exists(), "old.txt should be removed");
1752 Ok(())
1753 }
1754
1755 #[tokio::test]
1757 #[traced_test]
1758 async fn keeps_files_newer_than_modified_before() -> Result<(), anyhow::Error> {
1759 let test_path = testutils::create_temp_dir().await?;
1760 let file = test_path.join("new.txt");
1761 tokio::fs::write(&file, "x").await?;
1762 set_mtime_age(&file, std::time::Duration::from_secs(60))?;
1763 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1764 let summary = rm(
1765 &PROGRESS,
1766 &test_path,
1767 &Settings {
1768 fail_early: false,
1769 filter: None,
1770 time_filter: Some(TimeFilter {
1771 modified_before: Some(std::time::Duration::from_secs(3600)),
1772 created_before: None,
1773 }),
1774 dry_run: None,
1775 },
1776 )
1777 .await?;
1778 assert_eq!(summary.files_removed, 0, "new file should not be removed");
1779 assert_eq!(summary.files_skipped, 1, "new file should be skipped");
1780 assert!(file.exists(), "new.txt should still exist");
1781 Ok(())
1782 }
1783
1784 #[tokio::test]
1787 #[traced_test]
1788 async fn fresh_subdirectory_is_descended_but_not_removed() -> Result<(), anyhow::Error> {
1789 let test_path = testutils::create_temp_dir().await?;
1790 let old_file = test_path.join("old.txt");
1791 let fresh_dir = test_path.join("fresh_dir");
1792 let fresh_child = fresh_dir.join("fresh_child.txt");
1793 let old_child = fresh_dir.join("old_child.txt");
1794 tokio::fs::write(&old_file, "x").await?;
1795 tokio::fs::create_dir(&fresh_dir).await?;
1796 tokio::fs::write(&fresh_child, "x").await?;
1797 tokio::fs::write(&old_child, "x").await?;
1798 set_mtime_age(&old_file, std::time::Duration::from_secs(7200))?;
1799 set_mtime_age(&old_child, std::time::Duration::from_secs(7200))?;
1800 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1803 let summary = rm(
1804 &PROGRESS,
1805 &test_path,
1806 &Settings {
1807 fail_early: false,
1808 filter: None,
1809 time_filter: Some(TimeFilter {
1810 modified_before: Some(std::time::Duration::from_secs(3600)),
1811 created_before: None,
1812 }),
1813 dry_run: None,
1814 },
1815 )
1816 .await?;
1817 assert_eq!(summary.files_removed, 2, "old.txt and old_child removed");
1819 assert_eq!(
1820 summary.files_skipped, 1,
1821 "fresh_child skipped inside fresh_dir"
1822 );
1823 assert_eq!(
1824 summary.directories_skipped, 1,
1825 "fresh_dir itself is skipped at removal time"
1826 );
1827 assert_eq!(
1828 summary.directories_removed, 0,
1829 "root survives because fresh_dir is still inside it"
1830 );
1831 assert!(!old_file.exists());
1832 assert!(!old_child.exists(), "old_child inside fresh_dir removed");
1833 assert!(
1834 fresh_dir.exists(),
1835 "fresh_dir kept despite its old child being removed"
1836 );
1837 assert!(fresh_child.exists(), "fresh_child inside fresh_dir kept");
1838 Ok(())
1839 }
1840
1841 #[tokio::test]
1844 #[traced_test]
1845 async fn old_dir_with_new_file_leaves_non_empty_dir_without_error()
1846 -> Result<(), anyhow::Error> {
1847 let test_path = testutils::create_temp_dir().await?;
1848 let old_dir = test_path.join("old_dir");
1849 tokio::fs::create_dir(&old_dir).await?;
1850 let new_file = old_dir.join("new.txt");
1851 tokio::fs::write(&new_file, "x").await?;
1852 set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
1853 set_mtime_age(&old_dir, std::time::Duration::from_secs(7200))?;
1854 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1855 tokio::fs::set_permissions(&old_dir, std::fs::Permissions::from_mode(0o555)).await?;
1856 let result = rm(
1857 &PROGRESS,
1858 &test_path,
1859 &Settings {
1860 fail_early: false,
1861 filter: None,
1862 time_filter: Some(TimeFilter {
1863 modified_before: Some(std::time::Duration::from_secs(3600)),
1864 created_before: None,
1865 }),
1866 dry_run: None,
1867 },
1868 )
1869 .await;
1870 let summary = result.expect("ENOTEMPTY should not surface as an error");
1871 assert_eq!(summary.files_skipped, 1, "new file should be skipped");
1872 assert_eq!(
1873 summary.directories_removed, 0,
1874 "old_dir cannot be removed while new.txt remains"
1875 );
1876 assert!(old_dir.exists(), "old_dir should still exist");
1877 assert!(new_file.exists(), "new.txt should still exist");
1878 assert_eq!(
1879 tokio::fs::metadata(&old_dir).await?.permissions().mode() & 0o7777,
1880 0o555,
1881 "ENOTEMPTY retention did not restore the original directory mode"
1882 );
1883 assert!(
1885 logs_contain("not empty after filtering, leaving it intact"),
1886 "should log ENOTEMPTY case at info"
1887 );
1888 Ok(())
1889 }
1890
1891 #[tokio::test]
1893 #[traced_test]
1894 async fn old_empty_directory_is_removed() -> Result<(), anyhow::Error> {
1895 let test_path = testutils::create_temp_dir().await?;
1896 let old_empty = test_path.join("old_empty");
1897 tokio::fs::create_dir(&old_empty).await?;
1898 set_mtime_age(&old_empty, std::time::Duration::from_secs(7200))?;
1899 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1900 let summary = rm(
1901 &PROGRESS,
1902 &test_path,
1903 &Settings {
1904 fail_early: false,
1905 filter: None,
1906 time_filter: Some(TimeFilter {
1907 modified_before: Some(std::time::Duration::from_secs(3600)),
1908 created_before: None,
1909 }),
1910 dry_run: None,
1911 },
1912 )
1913 .await?;
1914 assert_eq!(summary.directories_removed, 2);
1916 assert!(!old_empty.exists());
1917 assert!(!test_path.exists());
1918 Ok(())
1919 }
1920
1921 #[tokio::test]
1923 #[traced_test]
1924 async fn time_filter_combines_with_glob_exclude() -> Result<(), anyhow::Error> {
1925 let test_path = testutils::create_temp_dir().await?;
1926 let old_keep = test_path.join("keep.log");
1927 let old_drop = test_path.join("drop.txt");
1928 let new_drop = test_path.join("recent.txt");
1929 tokio::fs::write(&old_keep, "x").await?;
1930 tokio::fs::write(&old_drop, "x").await?;
1931 tokio::fs::write(&new_drop, "x").await?;
1932 set_mtime_age(&old_keep, std::time::Duration::from_secs(7200))?;
1933 set_mtime_age(&old_drop, std::time::Duration::from_secs(7200))?;
1934 set_mtime_age(&new_drop, std::time::Duration::from_secs(60))?;
1935 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1936 let mut filter = crate::filter::FilterSettings::new();
1937 filter.add_exclude("*.log").unwrap();
1938 let summary = rm(
1939 &PROGRESS,
1940 &test_path,
1941 &Settings {
1942 fail_early: false,
1943 filter: Some(filter),
1944 time_filter: Some(TimeFilter {
1945 modified_before: Some(std::time::Duration::from_secs(3600)),
1946 created_before: None,
1947 }),
1948 dry_run: None,
1949 },
1950 )
1951 .await?;
1952 assert_eq!(summary.files_removed, 1, "only old_drop should be removed");
1954 assert_eq!(
1955 summary.files_skipped, 2,
1956 "old_keep and recent_drop should be skipped"
1957 );
1958 assert!(
1959 old_keep.exists(),
1960 "keep.log excluded by glob, should remain"
1961 );
1962 assert!(!old_drop.exists(), "drop.txt should be removed");
1963 assert!(new_drop.exists(), "recent.txt should remain (too new)");
1964 Ok(())
1965 }
1966
1967 #[tokio::test]
1969 #[traced_test]
1970 async fn time_filter_with_dry_run() -> Result<(), anyhow::Error> {
1971 let test_path = testutils::create_temp_dir().await?;
1972 let old_file = test_path.join("old.txt");
1973 let new_file = test_path.join("new.txt");
1974 tokio::fs::write(&old_file, "x").await?;
1975 tokio::fs::write(&new_file, "x").await?;
1976 set_mtime_age(&old_file, std::time::Duration::from_secs(7200))?;
1977 set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
1978 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1979 let summary = rm(
1980 &PROGRESS,
1981 &test_path,
1982 &Settings {
1983 fail_early: false,
1984 filter: None,
1985 time_filter: Some(TimeFilter {
1986 modified_before: Some(std::time::Duration::from_secs(3600)),
1987 created_before: None,
1988 }),
1989 dry_run: Some(DryRunMode::Explain),
1990 },
1991 )
1992 .await?;
1993 assert_eq!(
1994 summary.files_removed, 1,
1995 "should report old file would be removed"
1996 );
1997 assert_eq!(
1998 summary.files_skipped, 1,
1999 "should report new file would be skipped"
2000 );
2001 assert!(old_file.exists(), "old.txt should still exist (dry-run)");
2002 assert!(new_file.exists(), "new.txt should still exist (dry-run)");
2003 Ok(())
2004 }
2005
2006 #[tokio::test]
2009 #[traced_test]
2010 async fn fresh_top_level_directory_is_traversed_but_not_removed()
2011 -> Result<(), anyhow::Error> {
2012 let test_path = testutils::create_temp_dir().await?;
2013 let old_inside = test_path.join("old.txt");
2014 tokio::fs::write(&old_inside, "x").await?;
2015 set_mtime_age(&old_inside, std::time::Duration::from_secs(7200))?;
2016 tokio::fs::set_permissions(&test_path, std::fs::Permissions::from_mode(0o555)).await?;
2018 let summary = rm(
2019 &PROGRESS,
2020 &test_path,
2021 &Settings {
2022 fail_early: false,
2023 filter: None,
2024 time_filter: Some(TimeFilter {
2025 modified_before: Some(std::time::Duration::from_secs(3600)),
2026 created_before: None,
2027 }),
2028 dry_run: None,
2029 },
2030 )
2031 .await?;
2032 assert_eq!(
2033 summary.files_removed, 1,
2034 "old child should be removed despite fresh parent"
2035 );
2036 assert_eq!(
2037 summary.directories_skipped, 1,
2038 "fresh root itself is skipped at removal time"
2039 );
2040 assert_eq!(
2041 summary.directories_removed, 0,
2042 "fresh root must not be removed"
2043 );
2044 assert!(test_path.exists(), "fresh root should still exist");
2045 assert!(!old_inside.exists(), "old child should be gone");
2046 assert_eq!(
2047 tokio::fs::metadata(&test_path).await?.permissions().mode() & 0o7777,
2048 0o555,
2049 "time-filter retention did not restore the original directory mode"
2050 );
2051 Ok(())
2052 }
2053
2054 #[tokio::test]
2056 #[traced_test]
2057 async fn time_filter_on_root_file_argument() -> Result<(), anyhow::Error> {
2058 let test_path = testutils::create_temp_dir().await?;
2059 let new_file = test_path.join("new.txt");
2060 tokio::fs::write(&new_file, "x").await?;
2061 set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
2062 let summary = rm(
2063 &PROGRESS,
2064 &new_file,
2065 &Settings {
2066 fail_early: false,
2067 filter: None,
2068 time_filter: Some(TimeFilter {
2069 modified_before: Some(std::time::Duration::from_secs(3600)),
2070 created_before: None,
2071 }),
2072 dry_run: None,
2073 },
2074 )
2075 .await?;
2076 assert_eq!(summary.files_removed, 0);
2077 assert_eq!(
2078 summary.files_skipped, 1,
2079 "root file too new should be skipped"
2080 );
2081 assert!(new_file.exists(), "root file should still exist");
2082 Ok(())
2083 }
2084 }
2085
2086 mod max_files_in_flight_tests {
2088 use super::*;
2089
2090 #[tokio::test]
2094 async fn filtered_root_waits_for_admission_before_setup() -> Result<(), anyhow::Error> {
2095 let root = testutils::create_temp_dir().await?;
2096 let path = root.join("victim");
2097 tokio::fs::write(&path, b"x").await?;
2098 let mut filter = crate::filter::FilterSettings::new();
2099 filter.add_exclude("victim")?;
2100 let settings = Settings {
2101 fail_early: true,
2102 filter: Some(filter),
2103 dry_run: None,
2104 time_filter: None,
2105 };
2106 let admission = testutils::AdmissionLimit::new().await;
2107 admission.set_files_in_flight(1);
2108 let stat_resource =
2109 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
2110 admission.set_max_ops_in_flight(stat_resource, 1);
2111 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
2112 let operation = rm(&PROGRESS, &path, &settings);
2113 tokio::pin!(operation);
2114 let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
2115 let mut second_permit = Box::pin(throttle::pending_meta_permit());
2116 let setup_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
2117 drop(second_permit);
2118 drop(held_stat);
2119 let result = admission
2120 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
2121 .await;
2122 assert!(
2123 stopped_at_stat_gate,
2124 "rm root did not reach the held stat gate"
2125 );
2126 let summary =
2127 result.context("rm root did not resume after stat capacity was released")??;
2128 assert!(
2129 !setup_bypassed_admission,
2130 "rm performed root setup before pending-metadata admission"
2131 );
2132 assert_eq!(summary.files_skipped, 1);
2133 Ok(())
2134 }
2135
2136 #[tokio::test]
2139 #[traced_test]
2140 async fn wide_rm_under_files_in_flight_saturation() -> Result<(), anyhow::Error> {
2141 let test_path = testutils::create_temp_dir().await?;
2142 let file_count = 200;
2143 for i in 0..file_count {
2144 tokio::fs::write(
2145 test_path.join(format!("{}.txt", i)),
2146 format!("content-{}", i),
2147 )
2148 .await?;
2149 }
2150 let admission = testutils::AdmissionLimit::new().await;
2152 admission.set_files_in_flight(4);
2153 let summary = admission
2154 .run_with_timeout(
2155 std::time::Duration::from_secs(30),
2156 rm(
2157 &PROGRESS,
2158 &test_path,
2159 &Settings {
2160 fail_early: true,
2161 filter: None,
2162 dry_run: None,
2163 time_filter: None,
2164 },
2165 ),
2166 )
2167 .await
2168 .context("rm timed out — possible deadlock")??;
2169 assert_eq!(summary.files_removed, file_count);
2170 assert_eq!(summary.directories_removed, 1);
2171 assert!(!test_path.exists());
2172 Ok(())
2173 }
2174
2175 #[tokio::test]
2178 #[traced_test]
2179 async fn deep_tree_no_deadlock_under_files_in_flight_saturation()
2180 -> Result<(), anyhow::Error> {
2181 let test_path = testutils::create_temp_dir().await?;
2182 let depth = 20;
2183 let files_per_level = 5;
2184 let limit = 1;
2185 let mut dir = test_path.clone();
2187 for level in 0..depth {
2188 tokio::fs::create_dir_all(&dir).await?;
2189 for f in 0..files_per_level {
2190 tokio::fs::write(
2191 dir.join(format!("f{}_{}.txt", level, f)),
2192 format!("L{}F{}", level, f),
2193 )
2194 .await?;
2195 }
2196 dir = dir.join(format!("d{}", level));
2197 }
2198 let admission = testutils::AdmissionLimit::new().await;
2199 admission.set_files_in_flight(limit);
2200 let summary = admission
2201 .run_with_timeout(
2202 std::time::Duration::from_secs(30),
2203 rm(
2204 &PROGRESS,
2205 &test_path,
2206 &Settings {
2207 fail_early: true,
2208 filter: None,
2209 dry_run: None,
2210 time_filter: None,
2211 },
2212 ),
2213 )
2214 .await
2215 .context("rm timed out — possible deadlock")?
2216 .context("rm failed")?;
2217 assert_eq!(summary.files_removed, depth * files_per_level);
2218 assert_eq!(summary.directories_removed, depth);
2219 assert!(!test_path.exists());
2220 Ok(())
2221 }
2222
2223 #[tokio::test]
2239 #[traced_test]
2240 async fn hinted_leaf_that_is_dir_drops_permit_before_recursion() -> anyhow::Result<()> {
2241 let root = testutils::create_temp_dir().await?;
2242 let dir_path = root.join("d");
2244 tokio::fs::create_dir(&dir_path).await?;
2245 tokio::fs::write(dir_path.join("c"), b"x").await?;
2246 let admission = testutils::AdmissionLimit::new().await;
2249 admission.set_files_in_flight(1);
2250 let parent = Dir::open_parent_dir(&root, congestion::Side::Source)
2252 .await
2253 .context("open parent dir")?;
2254 let parent = Arc::new(parent.into_tree());
2255 let name = std::ffi::OsStr::new("d");
2256 let handle = parent.child(name).await.context("classify d")?;
2257 assert_eq!(
2258 handle.kind(),
2259 EntryKind::Dir,
2260 "fixture `d` must be a directory"
2261 );
2262 drop(handle);
2263 let settings = Settings {
2264 fail_early: true,
2265 filter: None,
2266 dry_run: None,
2267 time_filter: None,
2268 };
2269 let visitor = Arc::new(RmVisitor {
2270 prog_track: &PROGRESS,
2271 settings: settings.clone(),
2272 });
2273 let cx = EntryCx::root(
2274 Arc::clone(&parent),
2275 name.to_owned(),
2276 dir_path.clone(),
2277 &PROGRESS,
2278 );
2279 let permit =
2282 crate::walk::preacquire_leaf_permit(PermitKind::PendingMeta, Some(EntryKind::File))
2283 .await;
2284 assert!(permit.is_some(), "the pre-acquire must take the one permit");
2285 let result = admission
2286 .run_with_timeout(
2287 std::time::Duration::from_secs(20),
2288 process_entry(visitor, cx, (), permit),
2289 )
2290 .await;
2291 let summary = result
2292 .context(
2293 "process_entry hung — leaf permit held across directory recursion (deadlock)",
2294 )?
2295 .map_err(|e| e.source)?;
2296 assert_eq!(summary.files_removed, 1, "child file should be removed");
2297 assert_eq!(
2298 summary.directories_removed, 1,
2299 "directory should be removed"
2300 );
2301 assert!(!dir_path.exists(), "directory `d` should be gone");
2302 Ok(())
2303 }
2304 }
2305
2306 mod race_tests {
2308 use super::*;
2309
2310 static RACE_PROGRESS: std::sync::LazyLock<progress::Progress> =
2311 std::sync::LazyLock::new(progress::Progress::new);
2312
2313 #[tokio::test]
2314 async fn non_directory_action_cannot_remove_directory_replacement() -> anyhow::Result<()> {
2315 let tmp = tempfile::tempdir()?;
2316 let entry = tmp.path().join("entry");
2317 let original = tmp.path().join("original");
2318 tokio::fs::write(&entry, b"original").await?;
2319 let parent = Arc::new(
2320 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2321 .await?
2322 .into_tree(),
2323 );
2324 let handle = parent.child(OsStr::new("entry")).await?;
2325 let leaf = AdmittedLeaf::try_new(handle, None)
2326 .map_err(|_| anyhow::anyhow!("file fixture classified as a directory"))?;
2327 tokio::fs::rename(&entry, &original).await?;
2328 tokio::fs::create_dir(&entry).await?;
2329 tokio::fs::write(entry.join("replacement-child"), b"replacement").await?;
2330 let visitor = RmVisitor {
2331 prog_track: &RACE_PROGRESS,
2332 settings: Settings {
2333 fail_early: true,
2334 filter: None,
2335 time_filter: None,
2336 dry_run: None,
2337 },
2338 };
2339 let cx = EntryCx::root(
2340 parent,
2341 OsStr::new("entry").to_owned(),
2342 entry.clone(),
2343 &RACE_PROGRESS,
2344 )
2345 .with_relative_path(std::path::PathBuf::from("entry"));
2346 let error = visitor
2347 .visit_leaf(&cx, &(), leaf)
2348 .await
2349 .expect_err("a nondirectory unlink must reject a replacement directory");
2350 assert!(format!("{:#}", error.source).contains("failed removing"));
2351 assert_eq!(tokio::fs::read(&original).await?, b"original");
2352 assert_eq!(
2353 tokio::fs::read(entry.join("replacement-child")).await?,
2354 b"replacement"
2355 );
2356 Ok(())
2357 }
2358
2359 #[tokio::test]
2360 async fn directory_replacement_is_not_descended_after_classification() -> anyhow::Result<()>
2361 {
2362 let tmp = tempfile::tempdir()?;
2363 let entry = tmp.path().join("entry");
2364 let original = tmp.path().join("original");
2365 tokio::fs::create_dir(&entry).await?;
2366 let parent = Arc::new(
2367 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2368 .await?
2369 .into_tree(),
2370 );
2371 let handle = parent.child(OsStr::new("entry")).await?;
2372 tokio::fs::rename(&entry, &original).await?;
2373 tokio::fs::create_dir(&entry).await?;
2374 tokio::fs::write(entry.join("replacement-child"), b"replacement").await?;
2375 let visitor = RmVisitor {
2376 prog_track: &RACE_PROGRESS,
2377 settings: Settings {
2378 fail_early: true,
2379 filter: None,
2380 time_filter: None,
2381 dry_run: None,
2382 },
2383 };
2384 let cx = EntryCx::root(
2385 parent,
2386 OsStr::new("entry").to_owned(),
2387 entry.clone(),
2388 &RACE_PROGRESS,
2389 )
2390 .with_relative_path(std::path::PathBuf::from("entry"));
2391 let error = match visitor.dir_pre(&cx, &(), &handle).await {
2392 Ok(_) => anyhow::bail!("a replacement passed the directory identity check"),
2393 Err(error) => error,
2394 };
2395 assert!(format!("{:#}", error.source).contains("changed identity before descent"));
2396 assert_eq!(
2397 tokio::fs::read(entry.join("replacement-child")).await?,
2398 b"replacement"
2399 );
2400 Ok(())
2401 }
2402
2403 #[tokio::test]
2404 async fn final_rmdir_removes_an_empty_replacement_in_the_walked_slot() -> anyhow::Result<()>
2405 {
2406 let tmp = tempfile::tempdir()?;
2407 let entry = tmp.path().join("entry");
2408 let original = tmp.path().join("original");
2409 tokio::fs::create_dir(&entry).await?;
2410 let parent = Arc::new(
2411 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2412 .await?
2413 .into_tree(),
2414 );
2415 let handle = parent.child(OsStr::new("entry")).await?;
2416 let visitor = RmVisitor {
2417 prog_track: &RACE_PROGRESS,
2418 settings: Settings {
2419 fail_early: true,
2420 filter: None,
2421 time_filter: None,
2422 dry_run: None,
2423 },
2424 };
2425 let cx = EntryCx::root(
2426 parent,
2427 OsStr::new("entry").to_owned(),
2428 entry.clone(),
2429 &RACE_PROGRESS,
2430 )
2431 .with_relative_path(std::path::PathBuf::from("entry"));
2432 let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2433 DirAction::Descend { state, .. } => state,
2434 DirAction::Skip(_) => anyhow::bail!("unfiltered directory fixture was skipped"),
2435 };
2436 tokio::fs::rename(&entry, &original).await?;
2437 tokio::fs::create_dir(&entry).await?;
2438 let summary = visitor
2439 .dir_post(
2440 &cx,
2441 state,
2442 Ok((Summary::default(), ProcessedChildren::default())),
2443 )
2444 .await?;
2445 assert_eq!(summary.directories_removed, 1);
2446 assert!(!entry.exists(), "the empty slot replacement survived rmdir");
2447 assert!(original.is_dir());
2448 Ok(())
2449 }
2450
2451 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2452 async fn intended_removal_keeps_temporary_mode_until_rmdir() -> anyhow::Result<()> {
2453 let tmp = tempfile::tempdir()?;
2454 let entry = tmp.path().join("entry");
2455 tokio::fs::create_dir(&entry).await?;
2456 tokio::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o555)).await?;
2457 let parent = Arc::new(
2458 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2459 .await?
2460 .into_tree(),
2461 );
2462 let handle = parent.child(OsStr::new("entry")).await?;
2463 let visitor = RmVisitor {
2464 prog_track: &RACE_PROGRESS,
2465 settings: Settings {
2466 fail_early: true,
2467 filter: None,
2468 time_filter: None,
2469 dry_run: None,
2470 },
2471 };
2472 let cx = EntryCx::root(
2473 parent,
2474 OsStr::new("entry").to_owned(),
2475 entry.clone(),
2476 &RACE_PROGRESS,
2477 )
2478 .with_relative_path(std::path::PathBuf::from("entry"));
2479 let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2480 DirAction::Descend { state, .. } => state,
2481 DirAction::Skip(_) => anyhow::bail!("unfiltered directory fixture was skipped"),
2482 };
2483 assert_eq!(
2484 tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2485 0o700,
2486 "dir_pre must relax the directory before final removal"
2487 );
2488
2489 let mut gate = testutils::BlockingPathGate::install(entry.clone());
2490 let mut task = tokio::spawn(async move {
2491 visitor
2492 .dir_post(
2493 &cx,
2494 state,
2495 Ok((Summary::default(), ProcessedChildren::default())),
2496 )
2497 .await
2498 });
2499 let timeout = std::time::Duration::from_secs(20);
2500 let gate_start = tokio::time::timeout(timeout, gate.wait_started()).await;
2501 if !matches!(&gate_start, Ok(Ok(_))) {
2502 gate.release_all();
2503 task.abort();
2504 let _ = task.await;
2505 match gate_start {
2506 Ok(Err(error)) => {
2507 return Err(error.context("final rmdir did not reach its pre-syscall gate"));
2508 }
2509 Err(error) => {
2510 return Err(anyhow::Error::new(error)
2511 .context("final rmdir did not reach its pre-syscall gate"));
2512 }
2513 Ok(Ok(_)) => unreachable!(),
2514 }
2515 }
2516 let checked_mode = tokio::fs::metadata(&entry)
2517 .await
2518 .map(|metadata| metadata.permissions().mode() & 0o7777);
2519 gate.release_all();
2520 let owner_join = match tokio::time::timeout(timeout, &mut task).await {
2521 Ok(result) => result,
2522 Err(error) => {
2523 task.abort();
2524 let _ = task.await;
2525 return Err(anyhow::Error::new(error)
2526 .context("final rmdir did not quiesce after its gate released"));
2527 }
2528 };
2529 let result = owner_join.context("final rmdir task panicked")?;
2530 let summary = result.map_err(|error| error.source)?;
2531 assert_eq!(
2532 checked_mode?, 0o700,
2533 "the intended-removal path restored metadata before the rmdir boundary"
2534 );
2535 assert!(!entry.exists(), "the by-name rmdir left the directory name");
2536 assert_eq!(summary.directories_removed, 1);
2537 Ok(())
2538 }
2539
2540 #[tokio::test]
2541 async fn filtered_retention_restores_mode_through_chmod_admission() -> anyhow::Result<()> {
2542 let tmp = tempfile::tempdir()?;
2543 let entry = tmp.path().join("entry");
2544 tokio::fs::create_dir(&entry).await?;
2545 tokio::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o555)).await?;
2546 let mut filter = crate::filter::FilterSettings::new();
2547 filter.add_include("other")?;
2548 let parent = Arc::new(
2549 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2550 .await?
2551 .into_tree(),
2552 );
2553 let handle = parent.child(OsStr::new("entry")).await?;
2554 let visitor = RmVisitor {
2555 prog_track: &RACE_PROGRESS,
2556 settings: Settings {
2557 fail_early: true,
2558 filter: Some(filter),
2559 time_filter: None,
2560 dry_run: None,
2561 },
2562 };
2563 let cx = EntryCx::root(
2564 parent,
2565 OsStr::new("entry").to_owned(),
2566 entry.clone(),
2567 &RACE_PROGRESS,
2568 )
2569 .with_relative_path(std::path::PathBuf::from("entry"));
2570 let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2571 DirAction::Descend { state, .. } => state,
2572 DirAction::Skip(_) => anyhow::bail!("include-filter ancestor was skipped"),
2573 };
2574 assert_eq!(
2575 tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2576 0o700,
2577 "dir_pre did not relax the protected directory"
2578 );
2579
2580 let admission = testutils::AdmissionLimit::new().await;
2581 let chmod_resource =
2582 throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod);
2583 admission.set_max_ops_in_flight(chmod_resource, 1);
2584 let held_chmod = throttle::ops_in_flight_permit(chmod_resource).await;
2585 let processed = ProcessedChildren::default();
2586 let restore = visitor.dir_post(&cx, state, Ok((Summary::default(), processed)));
2587 tokio::pin!(restore);
2588 assert!(
2589 futures::poll!(restore.as_mut()).is_pending(),
2590 "filtered retention bypassed Destination/Chmod admission"
2591 );
2592 assert_eq!(
2593 tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2594 0o700,
2595 "filtered retention restored the mode while chmod admission was held"
2596 );
2597 drop(held_chmod);
2598 let summary = admission
2599 .run_with_timeout(std::time::Duration::from_secs(20), restore.as_mut())
2600 .await
2601 .context("filtered mode restore did not resume after chmod admission")?
2602 .map_err(|error| error.source)?;
2603 assert!(entry.is_dir(), "filtered retention removed the directory");
2604 assert_eq!(summary.directories_removed, 0);
2605 assert_eq!(
2606 tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2607 0o555,
2608 "filtered retention did not restore the original directory mode"
2609 );
2610 Ok(())
2611 }
2612
2613 fn spawn_dir_symlink_swapper(
2620 tree: std::path::PathBuf,
2621 sentinel: std::path::PathBuf,
2622 stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
2623 ) -> std::thread::JoinHandle<()> {
2624 std::thread::spawn(move || {
2625 let sub = tree.join("sub");
2626 let staged_dir = tree.join("__staged_sub_dir");
2627 let staged_link = tree.join("__staged_sub_link");
2628 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
2629 let _ = std::fs::remove_dir_all(&staged_dir);
2631 if std::fs::create_dir(&staged_dir).is_ok() {
2632 let _ = std::fs::write(staged_dir.join("real.txt"), b"REAL");
2633 let _ = std::fs::remove_dir_all(&sub);
2637 let _ = std::fs::remove_file(&sub);
2638 let _ = std::fs::rename(&staged_dir, &sub);
2639 }
2640 let _ = std::fs::remove_file(&staged_link);
2642 if std::os::unix::fs::symlink(&sentinel, &staged_link).is_ok() {
2643 let _ = std::fs::remove_dir_all(&sub);
2644 let _ = std::fs::remove_file(&sub);
2645 let _ = std::fs::rename(&staged_link, &sub);
2646 }
2647 }
2648 })
2649 }
2650
2651 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2663 async fn intermediate_dir_swap_never_deletes_out_of_tree_sentinel() -> anyhow::Result<()> {
2664 let tmp = testutils::create_temp_dir().await?;
2665 let root = tmp.as_path();
2666 let sentinel = root.join("sentinel_tree");
2668 tokio::fs::create_dir(&sentinel).await?;
2669 tokio::fs::write(sentinel.join("secret1.txt"), b"SECRET-1").await?;
2670 tokio::fs::create_dir(sentinel.join("subdir")).await?;
2671 tokio::fs::write(sentinel.join("subdir").join("secret2.txt"), b"SECRET-2").await?;
2672
2673 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2674 let swapper =
2675 spawn_dir_symlink_swapper(root.to_path_buf(), sentinel.clone(), stop.clone());
2676
2677 let settings = Settings {
2678 fail_early: false,
2679 filter: None,
2680 dry_run: None,
2681 time_filter: None,
2682 };
2683 let mut removed = 0usize;
2684 let mut errored = 0usize;
2685 for i in 0..400 {
2686 let tree = root.join("tree");
2694 let _ = tokio::fs::create_dir(&tree).await;
2695 for d in 0..16 {
2696 let sib = tree.join(format!("sib_{d}"));
2697 let _ = tokio::fs::create_dir(&sib).await;
2698 for f in 0..4 {
2699 let _ = tokio::fs::write(sib.join(format!("f{f}.txt")), b"x").await;
2700 }
2701 }
2702 let sub = tree.join("sub");
2703 if i % 2 == 0 {
2704 let _ = tokio::fs::remove_dir_all(&sub).await;
2707 let _ = tokio::fs::remove_file(&sub).await;
2708 let _ = tokio::fs::symlink(&sentinel, &sub).await;
2709 } else if tokio::fs::symlink_metadata(&sub).await.is_err() {
2710 let _ = tokio::fs::create_dir(&sub).await;
2711 let _ = tokio::fs::write(sub.join("real.txt"), b"REAL").await;
2712 }
2713 let result = tokio::time::timeout(
2714 std::time::Duration::from_secs(30),
2715 super::rm(&RACE_PROGRESS, &tree, &settings),
2716 )
2717 .await
2718 .expect("rm must not hang under concurrent dir swapping");
2719 match result {
2720 Ok(_) => removed += 1,
2721 Err(_) => errored += 1, }
2723 assert!(
2728 sentinel.exists(),
2729 "iteration {i}: sentinel directory was deleted — rm followed the symlink"
2730 );
2731 let s1 = tokio::fs::read(sentinel.join("secret1.txt")).await;
2732 assert!(
2733 matches!(&s1, Ok(b) if b == b"SECRET-1"),
2734 "iteration {i}: sentinel/secret1.txt was deleted or altered — rm followed the symlink"
2735 );
2736 let s2 = tokio::fs::read(sentinel.join("subdir").join("secret2.txt")).await;
2737 assert!(
2738 matches!(&s2, Ok(b) if b == b"SECRET-2"),
2739 "iteration {i}: sentinel/subdir/secret2.txt was deleted — rm recursed through the symlink"
2740 );
2741 let _ = tokio::fs::remove_dir_all(root.join("tree")).await;
2743 }
2744
2745 stop.store(true, std::sync::atomic::Ordering::Relaxed);
2746 swapper.join().expect("dir swapper thread panicked");
2747 tracing::info!("intermediate dir swap: removed={removed}, errored={errored}");
2749 assert!(
2750 removed + errored > 0,
2751 "expected at least one observable outcome across the iterations"
2752 );
2753 Ok(())
2754 }
2755 }
2756}