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 protection: None,
261 prog_track,
262 settings: settings.clone(),
263 });
264 let root_cx = EntryCx::root(
265 Arc::clone(&parent),
266 name.to_owned(),
267 path.to_path_buf(),
268 prog_track,
269 );
270 process_admitted_entry(visitor, root_cx, (), entry).await }
272
273pub async fn rm_child(
297 prog_track: &'static progress::Progress,
298 parent: &Arc<Dir>,
299 name: &OsStr,
300 rel_path: &std::path::Path,
301 settings: &Settings,
302) -> Result<Summary, Error> {
303 rm_child_admitted(
304 prog_track,
305 parent,
306 name,
307 rel_path,
308 settings,
309 EntryAdmission::RootOrDelegated,
310 None,
311 )
312 .await
313}
314
315pub(crate) async fn rm_child_admitted(
321 prog_track: &'static progress::Progress,
322 parent: &Arc<Dir>,
323 name: &OsStr,
324 rel_path: &std::path::Path,
325 settings: &Settings,
326 admission: EntryAdmission,
327 protection: Option<Arc<crate::input_protection::InputProtection>>,
328) -> Result<Summary, Error> {
329 rm_child_with_source(
330 prog_track,
331 parent,
332 name,
333 rel_path,
334 settings,
335 RmChildSource::Unclassified(admission),
336 protection,
337 )
338 .await
339}
340
341pub(crate) async fn rm_child_admitted_entry(
343 prog_track: &'static progress::Progress,
344 parent: &Arc<Dir>,
345 name: &OsStr,
346 rel_path: &std::path::Path,
347 settings: &Settings,
348 entry: AdmittedEntry,
349 protection: Option<Arc<crate::input_protection::InputProtection>>,
350) -> Result<Summary, Error> {
351 rm_child_with_source(
352 prog_track,
353 parent,
354 name,
355 rel_path,
356 settings,
357 RmChildSource::Admitted(entry),
358 protection,
359 )
360 .await
361}
362
363enum RmChildSource {
364 Unclassified(EntryAdmission),
365 Admitted(AdmittedEntry),
366}
367
368#[allow(clippy::too_many_arguments)]
369async fn rm_child_with_source(
370 prog_track: &'static progress::Progress,
371 parent: &Arc<Dir>,
372 name: &OsStr,
373 rel_path: &std::path::Path,
374 settings: &Settings,
375 source: RmChildSource,
376 protection: Option<Arc<crate::input_protection::InputProtection>>,
377) -> Result<Summary, Error> {
378 let visitor = Arc::new(RmVisitor {
381 protection,
382 prog_track,
383 settings: settings.clone(),
384 });
385 let root_cx = EntryCx::seeded(
386 Arc::clone(parent),
387 name.to_owned(),
388 rel_path.to_path_buf(),
389 prog_track,
390 );
391 match source {
392 RmChildSource::Unclassified(admission) => {
393 process_entry(visitor, root_cx, (), admission).await
394 }
395 RmChildSource::Admitted(entry) => process_admitted_entry(visitor, root_cx, (), entry).await,
396 }
397}
398struct RmVisitor {
404 protection: Option<Arc<crate::input_protection::InputProtection>>,
405 prog_track: &'static progress::Progress,
406 settings: Settings,
407}
408
409struct RmDirState {
412 relaxed: Option<RelaxedDir>,
415 time_metadata: Option<anyhow::Result<std::fs::Metadata>>,
419 matches_no_include: bool,
424}
425
426impl WalkVisitor for RmVisitor {
427 type Summary = Summary;
428 type DirContext = ();
429 type DirState = RmDirState;
430
431 fn root_dir_context(&self) {}
432
433 fn permit_kind(&self) -> PermitKind {
434 PermitKind::PendingMeta
438 }
439
440 fn fail_early(&self) -> bool {
441 self.settings.fail_early
442 }
443
444 fn filter(&self) -> Option<&crate::filter::FilterSettings> {
445 self.settings.filter.as_ref()
446 }
447
448 fn filter_requires_admitted_entry(&self) -> bool {
449 true
450 }
451
452 fn filter_allows_hint_only_skip(&self, _dir_ctx: &Self::DirContext) -> bool {
453 self.settings.dry_run.is_none()
456 }
457
458 fn on_skip(
459 &self,
460 cx: &SkippedEntry<'_>,
461 kind: EntryKind,
462 skip_result: &crate::filter::FilterResult,
463 ) -> Summary {
464 cx.report_skip(self.settings.dry_run, skip_result, kind);
467 skipped_summary_for(kind)
468 }
469
470 async fn visit_leaf(
471 &self,
472 cx: &EntryCx,
473 _parent_ctx: &(),
474 leaf: AdmittedLeaf,
475 ) -> Result<Summary, Error> {
476 let kind = leaf.kind();
477 let prog_track = self.prog_track;
478 let settings = &self.settings;
479 let parent = &cx.parent;
480 let name = cx.name.as_os_str();
481 let path = cx.real_path.as_path();
482 tracing::debug!("not a directory, just remove");
483 let is_symlink = kind == EntryKind::Symlink;
484 let file_size = if is_symlink {
485 0
486 } else {
487 crate::preserve::Metadata::size(leaf.handle().meta())
488 };
489 if let Some(ref time_filter) = settings.time_filter {
491 let entry_type = if is_symlink { "symlink" } else { "file" };
492 let make_skipped_summary = || {
493 tracing::debug!("skipping {:?} due to time filter", &path);
494 if is_symlink {
495 prog_track.symlinks_skipped.inc();
496 Summary {
497 symlinks_skipped: 1,
498 ..Default::default()
499 }
500 } else {
501 prog_track.files_skipped.inc();
502 Summary {
503 files_skipped: 1,
504 ..Default::default()
505 }
506 }
507 };
508 let metadata =
512 match safedir::stat_meta_via_proc_fd(leaf.handle(), congestion::Side::Source).await
513 {
514 Ok(md) => md,
515 Err(err) => {
516 let err = anyhow::Error::new(err).context(format!(
517 "failed reading metadata for time filter on {path:?}"
518 ));
519 if settings.fail_early {
520 return Err(Error::new(err, Default::default()));
521 }
522 if is_unsupported_io_error(&err) {
524 tracing::warn!(
525 "time filter evaluation unsupported for {} {:?}, skipping: {:#}",
526 entry_type,
527 &path,
528 &err
529 );
530 } else {
531 tracing::error!(
532 "time filter evaluation failed for {} {:?}, skipping: {:#}",
533 entry_type,
534 &path,
535 &err
536 );
537 }
538 return Ok(make_skipped_summary());
539 }
540 };
541 match time_filter.matches(&metadata) {
542 Ok(result) => {
543 if let Some(skip_reason) = result.as_skip_reason() {
544 if let Some(mode) = settings.dry_run {
545 crate::dry_run::report_time_skip(path, skip_reason, mode, entry_type);
546 }
547 return Ok(make_skipped_summary());
548 }
549 }
550 Err(err) => {
551 let err = err.context(format!("failed evaluating time filter on {:?}", &path));
552 if settings.fail_early {
553 return Err(Error::new(err, Default::default()));
554 }
555 if is_unsupported_io_error(&err) {
559 tracing::warn!(
560 "time filter evaluation unsupported for {} {:?}, skipping: {:#}",
561 entry_type,
562 &path,
563 &err
564 );
565 } else {
566 tracing::error!(
567 "time filter evaluation failed for {} {:?}, skipping: {:#}",
568 entry_type,
569 &path,
570 &err
571 );
572 }
573 return Ok(make_skipped_summary());
574 }
575 }
576 }
577 if let Some(protection) = &self.protection {
578 protection
579 .check_child(parent, name, path)
580 .await
581 .map_err(|error| Error::new(error.into(), Default::default()))?;
582 }
583 if settings.dry_run.is_some() {
585 let entry_type = if is_symlink { "symlink" } else { "file" };
586 crate::dry_run::report_action("remove", path, None, entry_type);
587 return Ok(Summary {
588 bytes_removed: file_size,
589 files_removed: if is_symlink { 0 } else { 1 },
590 symlinks_removed: if is_symlink { 1 } else { 0 },
591 ..Default::default()
592 });
593 }
594 if let Err(err) = parent
605 .unlink_at_on(name, congestion::Side::Destination)
606 .await
607 .with_context(|| format!("failed removing {:?}", &path))
608 {
609 return Err(Error::new(err, Default::default()));
610 }
611 if is_symlink {
612 prog_track.symlinks_removed.inc();
613 return Ok(Summary {
614 symlinks_removed: 1,
615 ..Default::default()
616 });
617 }
618 prog_track.files_removed.inc();
619 prog_track.bytes_removed.add(file_size);
620 Ok(Summary {
621 bytes_removed: file_size,
622 files_removed: 1,
623 ..Default::default()
624 })
625 }
626
627 async fn dir_pre(&self, cx: &EntryCx, _parent_ctx: &(), handle: &Handle) -> DirPreResult<Self> {
628 let settings = &self.settings;
629 let path = cx.real_path.as_path();
630 tracing::debug!("remove contents of the directory first");
631 if let Some(protection) = &self.protection {
632 protection
633 .check_child(&cx.parent, &cx.name, path)
634 .await
635 .and_then(|()| protection.check_directory(handle.meta(), path))
636 .map_err(|error| Error::new(error.into(), Default::default()))?;
637 }
638
639 let time_metadata: Option<anyhow::Result<std::fs::Metadata>> =
648 if settings.time_filter.is_some() {
649 Some(
650 safedir::stat_meta_via_proc_fd(handle, congestion::Side::Source)
651 .await
652 .map_err(|err| {
653 anyhow::Error::new(err).context(format!(
654 "failed reading metadata for time filter on {path:?}"
655 ))
656 }),
657 )
658 } else {
659 None
660 };
661 let matches_no_include = settings
667 .filter
668 .as_ref()
669 .is_some_and(|f| f.has_includes() && !f.directly_matches_include(&cx.rel_path, true));
670 let mut relaxed: Option<RelaxedDir> = None;
677 if settings.dry_run.is_none() {
678 let original_mode =
679 crate::preserve::Metadata::permissions(handle.meta()).mode() & 0o7777;
680 if original_mode & 0o700 != 0o700 {
685 tracing::debug!("directory is not writable/traversable - relax the permissions");
686 let prepared = RelaxedDir::prepare(handle, original_mode)
689 .with_context(|| format!("failed to pin relaxed directory {path:?}"))
690 .map_err(|err| Error::new(err, Default::default()))?;
691 safedir::chmod_via_proc_fd(handle, congestion::Side::Destination, 0o700)
694 .await
695 .with_context(|| {
696 format!("failed to make {path:?} directory readable and writable")
697 })
698 .map_err(|err| Error::new(err, Default::default()))?;
699 relaxed = Some(prepared);
700 }
701 }
702 let (dir, _) = cx
706 .parent
707 .open_dir_with_meta(&cx.name)
708 .await
709 .with_context(|| format!("failed reading directory {path:?}"))
710 .map_err(|err| Error::new(err, Default::default()))?;
711 dir.verify_same_inode(handle)
712 .await
713 .with_context(|| {
714 format!("directory {path:?} changed identity before descent (possible TOCTOU swap)")
715 })
716 .map_err(|err| Error::new(err, Default::default()))?;
717 let dir = Arc::new(dir);
718 Ok(DirAction::Descend {
719 dir,
720 child_ctx: (),
721 state: RmDirState {
722 relaxed,
723 time_metadata,
724 matches_no_include,
725 },
726 })
727 }
728
729 async fn dir_post(
730 &self,
731 cx: &EntryCx,
732 state: RmDirState,
733 child_result: DirPostInput<Self>,
734 ) -> Result<Summary, Error> {
735 let prog_track = self.prog_track;
736 let settings = &self.settings;
737 let path = cx.real_path.as_path();
738 let RmDirState {
739 relaxed,
740 time_metadata,
741 matches_no_include,
742 } = state;
743 let mut rm_summary = match child_result {
746 Ok((summary, _)) => summary,
747 Err(err) => return Err(err),
748 };
749 tracing::debug!("finally remove the empty directory");
750 let anything_removed = rm_summary.files_removed > 0
751 || rm_summary.symlinks_removed > 0
752 || rm_summary.directories_removed > 0;
753 let anything_skipped = rm_summary.files_skipped > 0
754 || rm_summary.symlinks_skipped > 0
755 || rm_summary.directories_skipped > 0;
756 let traversed_only = !anything_removed && matches_no_include;
759 let dir_passes_time_filter: bool = if let Some(ref time_filter) = settings.time_filter {
766 let matched = time_metadata.unwrap().and_then(|md| {
769 time_filter.matches(&md).map_err(|err| {
770 err.context(format!("failed evaluating time filter on {path:?}"))
771 })
772 });
773 match matched {
774 Ok(result) => match result.as_skip_reason() {
775 Some(reason) => {
776 if let Some(mode) = settings.dry_run {
777 crate::dry_run::report_time_skip(path, reason, mode, "dir");
778 }
779 false
780 }
781 None => true,
782 },
783 Err(err) => {
784 if settings.fail_early {
785 return Err(Error::new(err, rm_summary));
786 }
787 if is_unsupported_io_error(&err) {
791 tracing::warn!(
792 "time filter evaluation unsupported for dir {:?}, leaving it intact: {:#}",
793 &path,
794 &err
795 );
796 } else {
797 tracing::error!(
798 "time filter evaluation failed for dir {:?}, leaving it intact: {:#}",
799 &path,
800 &err
801 );
802 }
803 false
804 }
805 }
806 } else {
807 true
808 };
809 if settings.dry_run.is_some() {
816 if traversed_only || anything_skipped || !dir_passes_time_filter {
817 tracing::debug!(
818 "dry-run: directory {:?} would not be removed (removed={}, skipped={}, time_ok={})",
819 &path,
820 anything_removed,
821 anything_skipped,
822 dir_passes_time_filter
823 );
824 if !dir_passes_time_filter {
825 prog_track.directories_skipped.inc();
826 rm_summary.directories_skipped += 1;
827 }
828 } else {
829 crate::dry_run::report_action("remove", path, None, "dir");
830 rm_summary.directories_removed += 1;
831 }
832 return Ok(rm_summary);
833 }
834 if traversed_only {
838 tracing::debug!(
839 "directory {:?} had nothing removed, leaving it intact",
840 &path
841 );
842 restore_retained_dir(relaxed, path)
843 .await
844 .map_err(|err| Error::new(err, rm_summary))?;
845 return Ok(rm_summary);
846 }
847 if !dir_passes_time_filter {
850 tracing::debug!(
851 "directory {:?} skipped by time filter, leaving it intact",
852 &path
853 );
854 prog_track.directories_skipped.inc();
855 rm_summary.directories_skipped += 1;
856 restore_retained_dir(relaxed, path)
857 .await
858 .map_err(|err| Error::new(err, rm_summary))?;
859 return Ok(rm_summary);
860 }
861 #[cfg(test)]
868 let _final_rmdir_gate_visit = {
869 crate::testutils::wait_on_blocking_path_gate(path, libc::AT_FDCWD)
872 };
873 let any_filter_active = settings.filter.is_some() || settings.time_filter.is_some();
874 match cx
875 .parent
876 .rmdir_at_on(&cx.name, congestion::Side::Destination)
877 .await
878 {
879 Ok(()) => {
880 prog_track.directories_removed.inc();
881 rm_summary.directories_removed += 1;
882 }
883 Err(err) if any_filter_active => {
884 if err.kind() == std::io::ErrorKind::DirectoryNotEmpty
888 || err.raw_os_error() == Some(39)
889 {
890 tracing::info!(
891 "directory {:?} not empty after filtering, leaving it intact",
892 &path
893 );
894 restore_retained_dir(relaxed, path)
895 .await
896 .map_err(|restore_err| Error::new(restore_err, rm_summary))?;
897 } else {
898 return Err(Error::new(
899 anyhow!(err).context(format!("failed removing directory {:?}", &path)),
900 rm_summary,
901 ));
902 }
903 }
904 Err(err) => {
905 return Err(Error::new(
906 anyhow!(err).context(format!("failed removing directory {:?}", &path)),
907 rm_summary,
908 ));
909 }
910 }
911 Ok(rm_summary)
912 }
913}
914
915#[cfg(test)]
916mod tests {
917 use super::*;
918 use crate::config::DryRunMode;
919 use crate::testutils;
920 use crate::walk_driver::ProcessedChildren;
921 use tracing_test::traced_test;
922
923 static PROGRESS: std::sync::LazyLock<progress::Progress> =
924 std::sync::LazyLock::new(progress::Progress::new);
925
926 #[tokio::test]
927 #[traced_test]
928 async fn no_write_permission() -> Result<(), anyhow::Error> {
929 let tmp_dir = testutils::setup_test_dir().await?;
930 let test_path = tmp_dir.as_path();
931 let filepaths = vec![
932 test_path.join("foo").join("0.txt"),
933 test_path.join("foo").join("bar").join("2.txt"),
934 test_path.join("foo").join("baz").join("4.txt"),
935 test_path.join("foo").join("baz"),
936 ];
937 for fpath in &filepaths {
938 tokio::fs::set_permissions(&fpath, std::fs::Permissions::from_mode(0o555)).await?;
940 }
941 let summary = rm(
942 &PROGRESS,
943 &test_path.join("foo"),
944 &Settings {
945 fail_early: false,
946 filter: None,
947 dry_run: None,
948 time_filter: None,
949 },
950 )
951 .await?;
952 assert!(!test_path.join("foo").exists());
953 assert_eq!(summary.files_removed, 5);
954 assert_eq!(summary.symlinks_removed, 2);
955 assert_eq!(summary.directories_removed, 3);
956 Ok(())
957 }
958
959 #[tokio::test]
960 #[traced_test]
961 async fn removal_error_leaves_temporary_directory_mode() -> Result<(), anyhow::Error> {
962 let tmp = tempfile::tempdir()?;
971 let parent = tmp.path().join("parent");
972 let dst = parent.join("dst");
973 tokio::fs::create_dir(&parent).await?;
974 tokio::fs::create_dir(&dst).await?;
975 tokio::fs::write(dst.join("inside.txt"), b"x").await?;
976 tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o555)).await?;
978 tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o555)).await?;
980
981 let result = rm(
982 &PROGRESS,
983 &dst,
984 &Settings {
985 fail_early: false,
986 filter: None,
987 dry_run: None,
988 time_filter: None,
989 },
990 )
991 .await;
992
993 tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o755)).await?;
995
996 assert!(
997 result.is_err(),
998 "rm must fail when its dst can be emptied but the parent dir blocks remove_dir"
999 );
1000 let mode = tokio::fs::metadata(&dst).await?.permissions().mode() & 0o7777;
1001 assert_eq!(
1002 mode, 0o700,
1003 "a removal error unexpectedly restored the temporary directory mode (got {mode:o}o)"
1004 );
1005
1006 tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o755)).await?;
1008 Ok(())
1009 }
1010
1011 #[tokio::test]
1012 #[traced_test]
1013 async fn parent_dir_no_write_permission() -> Result<(), anyhow::Error> {
1014 let tmp_dir = testutils::setup_test_dir().await?;
1015 let test_path = tmp_dir.as_path();
1016 tokio::fs::set_permissions(
1018 &test_path.join("foo").join("bar"),
1019 std::fs::Permissions::from_mode(0o555),
1020 )
1021 .await?;
1022 let result = rm(
1023 &PROGRESS,
1024 &test_path.join("foo").join("bar").join("2.txt"),
1025 &Settings {
1026 fail_early: true,
1027 filter: None,
1028 dry_run: None,
1029 time_filter: None,
1030 },
1031 )
1032 .await;
1033 assert!(result.is_err());
1035 let err = result.unwrap_err();
1036 let err_string = format!("{:#}", err);
1037 assert!(
1039 err_string.contains("Permission denied") || err_string.contains("permission denied"),
1040 "Error should contain 'Permission denied' but got: {}",
1041 err_string
1042 );
1043 Ok(())
1044 }
1045
1046 mod filter_tests {
1047 use super::*;
1048 use crate::filter::FilterSettings;
1049 #[tokio::test]
1051 #[traced_test]
1052 async fn test_path_pattern_matches_nested_files() -> Result<(), anyhow::Error> {
1053 let tmp_dir = testutils::setup_test_dir().await?;
1054 let test_path = tmp_dir.as_path();
1055 let mut filter = FilterSettings::new();
1057 filter.add_include("bar/*.txt").unwrap();
1058 let summary = rm(
1059 &PROGRESS,
1060 &test_path.join("foo"),
1061 &Settings {
1062 fail_early: false,
1063 filter: Some(filter),
1064 dry_run: None,
1065 time_filter: None,
1066 },
1067 )
1068 .await?;
1069 assert_eq!(
1071 summary.files_removed, 3,
1072 "should remove 3 files matching bar/*.txt"
1073 );
1074 assert_eq!(summary.bytes_removed, 3, "should report 3 bytes removed");
1076 assert!(
1078 !test_path.join("foo/bar/1.txt").exists(),
1079 "bar/1.txt should be removed"
1080 );
1081 assert!(
1082 !test_path.join("foo/bar/2.txt").exists(),
1083 "bar/2.txt should be removed"
1084 );
1085 assert!(
1086 !test_path.join("foo/bar/3.txt").exists(),
1087 "bar/3.txt should be removed"
1088 );
1089 assert!(
1091 test_path.join("foo/0.txt").exists(),
1092 "0.txt should still exist"
1093 );
1094 Ok(())
1095 }
1096 #[tokio::test]
1098 #[traced_test]
1099 async fn test_filter_applies_to_single_file_source() -> Result<(), anyhow::Error> {
1100 let tmp_dir = testutils::setup_test_dir().await?;
1101 let test_path = tmp_dir.as_path();
1102 let mut filter = FilterSettings::new();
1104 filter.add_exclude("*.txt").unwrap();
1105 let summary = rm(
1106 &PROGRESS,
1107 &test_path.join("foo/0.txt"), &Settings {
1109 fail_early: false,
1110 filter: Some(filter),
1111 dry_run: None,
1112 time_filter: None,
1113 },
1114 )
1115 .await?;
1116 assert_eq!(
1118 summary.files_removed, 0,
1119 "file matching exclude pattern should not be removed"
1120 );
1121 assert!(
1122 test_path.join("foo/0.txt").exists(),
1123 "excluded file should still exist"
1124 );
1125 Ok(())
1126 }
1127 #[tokio::test]
1129 #[traced_test]
1130 async fn test_filter_applies_to_root_directory() -> Result<(), anyhow::Error> {
1131 let test_path = testutils::create_temp_dir().await?;
1132 tokio::fs::create_dir_all(test_path.join("excluded_dir")).await?;
1134 tokio::fs::write(test_path.join("excluded_dir/file.txt"), "content").await?;
1135 let mut filter = FilterSettings::new();
1137 filter.add_exclude("*_dir/").unwrap();
1138 let result = rm(
1139 &PROGRESS,
1140 &test_path.join("excluded_dir"),
1141 &Settings {
1142 fail_early: false,
1143 filter: Some(filter),
1144 dry_run: None,
1145 time_filter: None,
1146 },
1147 )
1148 .await?;
1149 assert_eq!(
1151 result.directories_removed, 0,
1152 "root directory matching exclude should not be removed"
1153 );
1154 assert!(
1155 test_path.join("excluded_dir").exists(),
1156 "excluded root directory should still exist"
1157 );
1158 Ok(())
1159 }
1160 #[tokio::test]
1162 #[traced_test]
1163 async fn test_filter_applies_to_root_symlink() -> Result<(), anyhow::Error> {
1164 let test_path = testutils::create_temp_dir().await?;
1165 tokio::fs::write(test_path.join("target.txt"), "content").await?;
1167 tokio::fs::symlink(
1168 test_path.join("target.txt"),
1169 test_path.join("excluded_link"),
1170 )
1171 .await?;
1172 let mut filter = FilterSettings::new();
1174 filter.add_exclude("*_link").unwrap();
1175 let result = rm(
1176 &PROGRESS,
1177 &test_path.join("excluded_link"),
1178 &Settings {
1179 fail_early: false,
1180 filter: Some(filter),
1181 dry_run: None,
1182 time_filter: None,
1183 },
1184 )
1185 .await?;
1186 assert_eq!(
1188 result.symlinks_removed, 0,
1189 "root symlink matching exclude should not be removed"
1190 );
1191 assert!(
1192 test_path.join("excluded_link").exists(),
1193 "excluded root symlink should still exist"
1194 );
1195 Ok(())
1196 }
1197 #[tokio::test]
1199 #[traced_test]
1200 async fn test_combined_include_exclude_patterns() -> Result<(), anyhow::Error> {
1201 let tmp_dir = testutils::setup_test_dir().await?;
1202 let test_path = tmp_dir.as_path();
1203 let mut filter = FilterSettings::new();
1210 filter.add_include("bar/*.txt").unwrap();
1211 filter.add_exclude("bar/2.txt").unwrap();
1212 let summary = rm(
1213 &PROGRESS,
1214 &test_path.join("foo"),
1215 &Settings {
1216 fail_early: false,
1217 filter: Some(filter),
1218 dry_run: None,
1219 time_filter: None,
1220 },
1221 )
1222 .await?;
1223 assert_eq!(summary.files_removed, 2, "should remove 2 files");
1226 assert_eq!(
1227 summary.files_skipped, 2,
1228 "should skip 2 files (bar/2.txt excluded, 0.txt no match)"
1229 );
1230 assert!(
1232 !test_path.join("foo/bar/1.txt").exists(),
1233 "bar/1.txt should be removed"
1234 );
1235 assert!(
1236 test_path.join("foo/bar/2.txt").exists(),
1237 "bar/2.txt should be excluded"
1238 );
1239 assert!(
1240 !test_path.join("foo/bar/3.txt").exists(),
1241 "bar/3.txt should be removed"
1242 );
1243 Ok(())
1244 }
1245 #[tokio::test]
1247 #[traced_test]
1248 async fn test_skipped_counts_comprehensive() -> Result<(), anyhow::Error> {
1249 let tmp_dir = testutils::setup_test_dir().await?;
1250 let test_path = tmp_dir.as_path();
1251 let mut filter = FilterSettings::new();
1258 filter.add_exclude("bar/").unwrap();
1259 let summary = rm(
1260 &PROGRESS,
1261 &test_path.join("foo"),
1262 &Settings {
1263 fail_early: false,
1264 filter: Some(filter),
1265 dry_run: None,
1266 time_filter: None,
1267 },
1268 )
1269 .await?;
1270 assert_eq!(summary.files_removed, 2, "should remove 2 files");
1275 assert_eq!(summary.symlinks_removed, 2, "should remove 2 symlinks");
1276 assert_eq!(
1277 summary.directories_removed, 1,
1278 "should remove 1 directory (baz only, foo not empty)"
1279 );
1280 assert_eq!(
1281 summary.directories_skipped, 1,
1282 "should skip 1 directory (bar)"
1283 );
1284 assert!(
1286 test_path.join("foo/bar").exists(),
1287 "bar directory should still exist"
1288 );
1289 assert!(
1291 test_path.join("foo").exists(),
1292 "foo directory should still exist (contains bar)"
1293 );
1294 Ok(())
1295 }
1296 #[tokio::test]
1299 #[traced_test]
1300 async fn test_empty_dir_not_removed_when_only_traversed() -> Result<(), anyhow::Error> {
1301 let test_path = testutils::create_temp_dir().await?;
1302 tokio::fs::write(test_path.join("foo"), "content").await?;
1308 tokio::fs::write(test_path.join("bar"), "content").await?;
1309 tokio::fs::create_dir(test_path.join("baz")).await?;
1310 let mut filter = FilterSettings::new();
1312 filter.add_include("foo").unwrap();
1313 let summary = rm(
1314 &PROGRESS,
1315 &test_path,
1316 &Settings {
1317 fail_early: false,
1318 filter: Some(filter),
1319 dry_run: None,
1320 time_filter: None,
1321 },
1322 )
1323 .await?;
1324 assert_eq!(summary.files_removed, 1, "should remove only 'foo' file");
1326 assert_eq!(
1327 summary.directories_removed, 0,
1328 "should NOT remove empty 'baz' directory"
1329 );
1330 assert!(!test_path.join("foo").exists(), "foo should be removed");
1332 assert!(test_path.join("bar").exists(), "bar should still exist");
1334 assert!(
1336 test_path.join("baz").exists(),
1337 "empty baz directory should NOT be removed"
1338 );
1339 Ok(())
1340 }
1341 #[tokio::test]
1345 #[traced_test]
1346 async fn test_exclude_only_removes_empty_directory() -> Result<(), anyhow::Error> {
1347 let test_path = testutils::create_temp_dir().await?;
1348 tokio::fs::write(test_path.join("foo"), "content").await?;
1354 tokio::fs::write(test_path.join("bar.log"), "content").await?;
1355 tokio::fs::create_dir(test_path.join("baz")).await?;
1356 let mut filter = FilterSettings::new();
1358 filter.add_exclude("*.log").unwrap();
1359 let summary = rm(
1360 &PROGRESS,
1361 &test_path,
1362 &Settings {
1363 fail_early: false,
1364 filter: Some(filter),
1365 dry_run: None,
1366 time_filter: None,
1367 },
1368 )
1369 .await?;
1370 assert_eq!(summary.files_removed, 1, "should remove 'foo'");
1372 assert_eq!(summary.files_skipped, 1, "should skip 'bar.log'");
1373 assert_eq!(
1374 summary.directories_removed, 1,
1375 "should remove empty 'baz' directory"
1376 );
1377 assert!(!test_path.join("foo").exists(), "foo should be removed");
1378 assert!(
1379 test_path.join("bar.log").exists(),
1380 "bar.log should still exist"
1381 );
1382 assert!(
1383 !test_path.join("baz").exists(),
1384 "empty baz directory should be removed"
1385 );
1386 Ok(())
1387 }
1388 #[tokio::test]
1390 #[traced_test]
1391 async fn test_dry_run_empty_dir_not_reported_as_removed() -> Result<(), anyhow::Error> {
1392 let test_path = testutils::create_temp_dir().await?;
1393 tokio::fs::write(test_path.join("foo"), "content").await?;
1399 tokio::fs::write(test_path.join("bar"), "content").await?;
1400 tokio::fs::create_dir(test_path.join("baz")).await?;
1401 let mut filter = FilterSettings::new();
1403 filter.add_include("foo").unwrap();
1404 let summary = rm(
1405 &PROGRESS,
1406 &test_path,
1407 &Settings {
1408 fail_early: false,
1409 filter: Some(filter),
1410 dry_run: Some(DryRunMode::Explain),
1411 time_filter: None,
1412 },
1413 )
1414 .await?;
1415 assert_eq!(
1417 summary.files_removed, 1,
1418 "should report only 'foo' would be removed"
1419 );
1420 assert_eq!(
1421 summary.directories_removed, 0,
1422 "should NOT report empty 'baz' would be removed"
1423 );
1424 assert!(test_path.join("foo").exists(), "foo should still exist");
1426 assert!(test_path.join("bar").exists(), "bar should still exist");
1427 assert!(test_path.join("baz").exists(), "baz should still exist");
1428 Ok(())
1429 }
1430 #[tokio::test]
1433 #[traced_test]
1434 async fn test_include_directly_matched_empty_dir_is_removed() -> Result<(), anyhow::Error> {
1435 let test_path = testutils::create_temp_dir().await?;
1436 tokio::fs::write(test_path.join("foo"), "content").await?;
1441 tokio::fs::create_dir(test_path.join("baz")).await?;
1442 let mut filter = FilterSettings::new();
1444 filter.add_include("baz/").unwrap();
1445 let summary = rm(
1446 &PROGRESS,
1447 &test_path,
1448 &Settings {
1449 fail_early: false,
1450 filter: Some(filter),
1451 dry_run: None,
1452 time_filter: None,
1453 },
1454 )
1455 .await?;
1456 assert_eq!(
1457 summary.directories_removed, 1,
1458 "should remove directly matched empty 'baz' directory"
1459 );
1460 assert_eq!(summary.files_removed, 0, "should not remove 'foo'");
1461 assert!(test_path.join("foo").exists(), "foo should still exist");
1462 assert!(
1463 !test_path.join("baz").exists(),
1464 "directly matched empty baz directory should be removed"
1465 );
1466 Ok(())
1467 }
1468 }
1469 mod dry_run_tests {
1470 use super::*;
1471 use crate::filter::FilterSettings;
1472
1473 #[tokio::test(flavor = "current_thread")]
1474 async fn dry_run_rechecks_a_directory_hint_before_previewing_an_included_file()
1475 -> Result<(), anyhow::Error> {
1476 let root = testutils::create_temp_dir().await?;
1477 let target = root.join("target");
1478 tokio::fs::create_dir(&target).await?;
1479 tokio::fs::write(target.join("node"), "CURRENT").await?;
1480 let mut filter = FilterSettings::new();
1481 filter.add_exclude("node/")?;
1482 assert!(!matches!(
1483 filter.should_include(std::path::Path::new("node"), true),
1484 crate::filter::FilterResult::Included
1485 ));
1486 assert!(matches!(
1487 filter.should_include(std::path::Path::new("node"), false),
1488 crate::filter::FilterResult::Included
1489 ));
1490 let settings = Settings {
1491 fail_early: false,
1492 filter: Some(filter),
1493 dry_run: Some(DryRunMode::Brief),
1494 time_filter: None,
1495 };
1496 let admission = testutils::AdmissionLimit::new().await;
1497 admission.set_files_in_flight(1);
1498 let target_dir =
1499 Arc::new(Dir::open_root_dir(&target, false, congestion::Side::Source).await?);
1500 let visitor = Arc::new(RmVisitor {
1501 protection: None,
1502 prog_track: &PROGRESS,
1503 settings,
1504 });
1505 let root_cx = EntryCx::root(
1506 Arc::clone(&target_dir),
1507 std::ffi::OsString::from("target"),
1508 target.clone(),
1509 &PROGRESS,
1510 );
1511 let result = admission
1512 .run_with_timeout(
1513 std::time::Duration::from_secs(20),
1514 crate::task_scope::scope_tasks(crate::walk_driver::walk_dir_entries(
1515 visitor,
1516 target_dir,
1517 &root_cx,
1518 &(),
1519 vec![(std::ffi::OsString::from("node"), Some(EntryKind::Dir))],
1520 )),
1521 )
1522 .await
1523 .context("rm dry-run hint recheck did not finish at a cap of one")??;
1524 let returned = admission
1525 .run_with_timeout(
1526 std::time::Duration::from_secs(20),
1527 throttle::pending_meta_permit(),
1528 )
1529 .await
1530 .context("rm dry-run hint recheck did not return pending-meta capacity")?;
1531 drop(returned);
1532 let (summary, processed) = result;
1533 assert!(processed.names().is_none());
1534 assert_eq!(summary.files_removed, 1);
1535 assert_eq!(summary.directories_skipped, 0);
1536 assert_eq!(
1537 tokio::fs::read_to_string(target.join("node")).await?,
1538 "CURRENT"
1539 );
1540 Ok(())
1541 }
1542
1543 #[tokio::test]
1545 #[traced_test]
1546 async fn test_dry_run_preserves_readonly_permissions() -> Result<(), anyhow::Error> {
1547 let tmp_dir = testutils::setup_test_dir().await?;
1548 let test_path = tmp_dir.as_path();
1549 let readonly_dir = test_path.join("foo/bar");
1550 tokio::fs::set_permissions(&readonly_dir, std::fs::Permissions::from_mode(0o555))
1552 .await?;
1553 let before_mode = tokio::fs::metadata(&readonly_dir)
1555 .await?
1556 .permissions()
1557 .mode()
1558 & 0o777;
1559 assert_eq!(
1560 before_mode, 0o555,
1561 "directory should be read-only before dry-run"
1562 );
1563 let summary = rm(
1564 &PROGRESS,
1565 &readonly_dir,
1566 &Settings {
1567 fail_early: false,
1568 filter: None,
1569 dry_run: Some(DryRunMode::Brief),
1570 time_filter: None,
1571 },
1572 )
1573 .await?;
1574 assert!(
1576 readonly_dir.exists(),
1577 "directory should still exist after dry-run"
1578 );
1579 let after_mode = tokio::fs::metadata(&readonly_dir)
1581 .await?
1582 .permissions()
1583 .mode()
1584 & 0o777;
1585 assert_eq!(
1586 after_mode, 0o555,
1587 "dry-run should not modify directory permissions"
1588 );
1589 assert!(
1591 summary.directories_removed > 0 || summary.files_removed > 0,
1592 "dry-run should report what would be removed"
1593 );
1594 Ok(())
1595 }
1596 #[tokio::test]
1599 #[traced_test]
1600 async fn test_dry_run_with_filter_non_empty_directory() -> Result<(), anyhow::Error> {
1601 let tmp_dir = testutils::setup_test_dir().await?;
1602 let test_path = tmp_dir.as_path();
1603 let mut filter = crate::filter::FilterSettings::new();
1610 filter.add_exclude("bar/").unwrap();
1611 let summary = rm(
1612 &PROGRESS,
1613 &test_path.join("foo"),
1614 &Settings {
1615 fail_early: false,
1616 filter: Some(filter),
1617 dry_run: Some(DryRunMode::Brief),
1618 time_filter: None,
1619 },
1620 )
1621 .await?;
1622 assert!(
1624 test_path.join("foo").exists(),
1625 "foo should still exist after dry-run"
1626 );
1627 assert_eq!(
1633 summary.files_removed, 2,
1634 "should report 2 files would be removed"
1635 );
1636 assert_eq!(
1637 summary.symlinks_removed, 2,
1638 "should report 2 symlinks would be removed"
1639 );
1640 assert_eq!(
1641 summary.directories_removed, 1,
1642 "should report only baz (not foo) would be removed"
1643 );
1644 assert_eq!(
1645 summary.directories_skipped, 1,
1646 "should report bar directory skipped"
1647 );
1648 Ok(())
1649 }
1650 #[tokio::test]
1653 #[traced_test]
1654 async fn test_dry_run_exclude_only_reports_empty_dir_removed() -> Result<(), anyhow::Error>
1655 {
1656 let test_path = testutils::create_temp_dir().await?;
1657 tokio::fs::write(test_path.join("foo"), "content").await?;
1663 tokio::fs::write(test_path.join("bar.log"), "content").await?;
1664 tokio::fs::create_dir(test_path.join("baz")).await?;
1665 let mut filter = FilterSettings::new();
1667 filter.add_exclude("*.log").unwrap();
1668 let summary = rm(
1669 &PROGRESS,
1670 &test_path,
1671 &Settings {
1672 fail_early: false,
1673 filter: Some(filter),
1674 dry_run: Some(DryRunMode::Explain),
1675 time_filter: None,
1676 },
1677 )
1678 .await?;
1679 assert_eq!(
1681 summary.files_removed, 1,
1682 "should report 'foo' would be removed"
1683 );
1684 assert_eq!(
1685 summary.files_skipped, 1,
1686 "should report 'bar.log' would be skipped"
1687 );
1688 assert_eq!(
1689 summary.directories_removed, 1,
1690 "should report empty 'baz' directory would be removed"
1691 );
1692 assert!(test_path.join("foo").exists(), "foo should still exist");
1694 assert!(
1695 test_path.join("bar.log").exists(),
1696 "bar.log should still exist"
1697 );
1698 assert!(test_path.join("baz").exists(), "baz should still exist");
1699 Ok(())
1700 }
1701 #[tokio::test]
1704 #[traced_test]
1705 async fn test_dry_run_include_directly_matched_empty_dir_reported()
1706 -> Result<(), anyhow::Error> {
1707 let test_path = testutils::create_temp_dir().await?;
1708 tokio::fs::write(test_path.join("foo"), "content").await?;
1713 tokio::fs::create_dir(test_path.join("baz")).await?;
1714 let mut filter = FilterSettings::new();
1716 filter.add_include("baz/").unwrap();
1717 let summary = rm(
1718 &PROGRESS,
1719 &test_path,
1720 &Settings {
1721 fail_early: false,
1722 filter: Some(filter),
1723 dry_run: Some(DryRunMode::Explain),
1724 time_filter: None,
1725 },
1726 )
1727 .await?;
1728 assert_eq!(
1729 summary.directories_removed, 1,
1730 "should report directly matched empty 'baz' would be removed"
1731 );
1732 assert_eq!(summary.files_removed, 0, "should not report 'foo'");
1733 assert!(test_path.join("foo").exists(), "foo should still exist");
1735 assert!(test_path.join("baz").exists(), "baz should still exist");
1736 Ok(())
1737 }
1738 }
1739 mod time_filter_tests {
1740 use super::*;
1741 use crate::filter::TimeFilter;
1742
1743 fn set_mtime_age(path: &std::path::Path, age: std::time::Duration) -> anyhow::Result<()> {
1744 let past = filetime::FileTime::from_system_time(std::time::SystemTime::now() - age);
1745 filetime::set_file_mtime(path, past)?;
1746 Ok(())
1747 }
1748
1749 #[tokio::test]
1751 #[traced_test]
1752 async fn removes_files_older_than_modified_before() -> Result<(), anyhow::Error> {
1753 let test_path = testutils::create_temp_dir().await?;
1754 let file = test_path.join("old.txt");
1755 tokio::fs::write(&file, "x").await?;
1756 set_mtime_age(&file, std::time::Duration::from_secs(7200))?;
1757 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1759 let summary = rm(
1760 &PROGRESS,
1761 &test_path,
1762 &Settings {
1763 fail_early: false,
1764 filter: None,
1765 time_filter: Some(TimeFilter {
1766 modified_before: Some(std::time::Duration::from_secs(3600)),
1767 created_before: None,
1768 }),
1769 dry_run: None,
1770 },
1771 )
1772 .await?;
1773 assert_eq!(summary.files_removed, 1, "old file should be removed");
1774 assert_eq!(summary.files_skipped, 0);
1775 assert!(!file.exists(), "old.txt should be removed");
1776 Ok(())
1777 }
1778
1779 #[tokio::test]
1781 #[traced_test]
1782 async fn keeps_files_newer_than_modified_before() -> Result<(), anyhow::Error> {
1783 let test_path = testutils::create_temp_dir().await?;
1784 let file = test_path.join("new.txt");
1785 tokio::fs::write(&file, "x").await?;
1786 set_mtime_age(&file, std::time::Duration::from_secs(60))?;
1787 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1788 let summary = rm(
1789 &PROGRESS,
1790 &test_path,
1791 &Settings {
1792 fail_early: false,
1793 filter: None,
1794 time_filter: Some(TimeFilter {
1795 modified_before: Some(std::time::Duration::from_secs(3600)),
1796 created_before: None,
1797 }),
1798 dry_run: None,
1799 },
1800 )
1801 .await?;
1802 assert_eq!(summary.files_removed, 0, "new file should not be removed");
1803 assert_eq!(summary.files_skipped, 1, "new file should be skipped");
1804 assert!(file.exists(), "new.txt should still exist");
1805 Ok(())
1806 }
1807
1808 #[tokio::test]
1811 #[traced_test]
1812 async fn fresh_subdirectory_is_descended_but_not_removed() -> Result<(), anyhow::Error> {
1813 let test_path = testutils::create_temp_dir().await?;
1814 let old_file = test_path.join("old.txt");
1815 let fresh_dir = test_path.join("fresh_dir");
1816 let fresh_child = fresh_dir.join("fresh_child.txt");
1817 let old_child = fresh_dir.join("old_child.txt");
1818 tokio::fs::write(&old_file, "x").await?;
1819 tokio::fs::create_dir(&fresh_dir).await?;
1820 tokio::fs::write(&fresh_child, "x").await?;
1821 tokio::fs::write(&old_child, "x").await?;
1822 set_mtime_age(&old_file, std::time::Duration::from_secs(7200))?;
1823 set_mtime_age(&old_child, std::time::Duration::from_secs(7200))?;
1824 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1827 let summary = rm(
1828 &PROGRESS,
1829 &test_path,
1830 &Settings {
1831 fail_early: false,
1832 filter: None,
1833 time_filter: Some(TimeFilter {
1834 modified_before: Some(std::time::Duration::from_secs(3600)),
1835 created_before: None,
1836 }),
1837 dry_run: None,
1838 },
1839 )
1840 .await?;
1841 assert_eq!(summary.files_removed, 2, "old.txt and old_child removed");
1843 assert_eq!(
1844 summary.files_skipped, 1,
1845 "fresh_child skipped inside fresh_dir"
1846 );
1847 assert_eq!(
1848 summary.directories_skipped, 1,
1849 "fresh_dir itself is skipped at removal time"
1850 );
1851 assert_eq!(
1852 summary.directories_removed, 0,
1853 "root survives because fresh_dir is still inside it"
1854 );
1855 assert!(!old_file.exists());
1856 assert!(!old_child.exists(), "old_child inside fresh_dir removed");
1857 assert!(
1858 fresh_dir.exists(),
1859 "fresh_dir kept despite its old child being removed"
1860 );
1861 assert!(fresh_child.exists(), "fresh_child inside fresh_dir kept");
1862 Ok(())
1863 }
1864
1865 #[tokio::test]
1868 #[traced_test]
1869 async fn old_dir_with_new_file_leaves_non_empty_dir_without_error()
1870 -> Result<(), anyhow::Error> {
1871 let test_path = testutils::create_temp_dir().await?;
1872 let old_dir = test_path.join("old_dir");
1873 tokio::fs::create_dir(&old_dir).await?;
1874 let new_file = old_dir.join("new.txt");
1875 tokio::fs::write(&new_file, "x").await?;
1876 set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
1877 set_mtime_age(&old_dir, std::time::Duration::from_secs(7200))?;
1878 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1879 tokio::fs::set_permissions(&old_dir, std::fs::Permissions::from_mode(0o555)).await?;
1880 let result = rm(
1881 &PROGRESS,
1882 &test_path,
1883 &Settings {
1884 fail_early: false,
1885 filter: None,
1886 time_filter: Some(TimeFilter {
1887 modified_before: Some(std::time::Duration::from_secs(3600)),
1888 created_before: None,
1889 }),
1890 dry_run: None,
1891 },
1892 )
1893 .await;
1894 let summary = result.expect("ENOTEMPTY should not surface as an error");
1895 assert_eq!(summary.files_skipped, 1, "new file should be skipped");
1896 assert_eq!(
1897 summary.directories_removed, 0,
1898 "old_dir cannot be removed while new.txt remains"
1899 );
1900 assert!(old_dir.exists(), "old_dir should still exist");
1901 assert!(new_file.exists(), "new.txt should still exist");
1902 assert_eq!(
1903 tokio::fs::metadata(&old_dir).await?.permissions().mode() & 0o7777,
1904 0o555,
1905 "ENOTEMPTY retention did not restore the original directory mode"
1906 );
1907 assert!(
1909 logs_contain("not empty after filtering, leaving it intact"),
1910 "should log ENOTEMPTY case at info"
1911 );
1912 Ok(())
1913 }
1914
1915 #[tokio::test]
1917 #[traced_test]
1918 async fn old_empty_directory_is_removed() -> Result<(), anyhow::Error> {
1919 let test_path = testutils::create_temp_dir().await?;
1920 let old_empty = test_path.join("old_empty");
1921 tokio::fs::create_dir(&old_empty).await?;
1922 set_mtime_age(&old_empty, std::time::Duration::from_secs(7200))?;
1923 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1924 let summary = rm(
1925 &PROGRESS,
1926 &test_path,
1927 &Settings {
1928 fail_early: false,
1929 filter: None,
1930 time_filter: Some(TimeFilter {
1931 modified_before: Some(std::time::Duration::from_secs(3600)),
1932 created_before: None,
1933 }),
1934 dry_run: None,
1935 },
1936 )
1937 .await?;
1938 assert_eq!(summary.directories_removed, 2);
1940 assert!(!old_empty.exists());
1941 assert!(!test_path.exists());
1942 Ok(())
1943 }
1944
1945 #[tokio::test]
1947 #[traced_test]
1948 async fn time_filter_combines_with_glob_exclude() -> Result<(), anyhow::Error> {
1949 let test_path = testutils::create_temp_dir().await?;
1950 let old_keep = test_path.join("keep.log");
1951 let old_drop = test_path.join("drop.txt");
1952 let new_drop = test_path.join("recent.txt");
1953 tokio::fs::write(&old_keep, "x").await?;
1954 tokio::fs::write(&old_drop, "x").await?;
1955 tokio::fs::write(&new_drop, "x").await?;
1956 set_mtime_age(&old_keep, std::time::Duration::from_secs(7200))?;
1957 set_mtime_age(&old_drop, std::time::Duration::from_secs(7200))?;
1958 set_mtime_age(&new_drop, std::time::Duration::from_secs(60))?;
1959 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
1960 let mut filter = crate::filter::FilterSettings::new();
1961 filter.add_exclude("*.log").unwrap();
1962 let summary = rm(
1963 &PROGRESS,
1964 &test_path,
1965 &Settings {
1966 fail_early: false,
1967 filter: Some(filter),
1968 time_filter: Some(TimeFilter {
1969 modified_before: Some(std::time::Duration::from_secs(3600)),
1970 created_before: None,
1971 }),
1972 dry_run: None,
1973 },
1974 )
1975 .await?;
1976 assert_eq!(summary.files_removed, 1, "only old_drop should be removed");
1978 assert_eq!(
1979 summary.files_skipped, 2,
1980 "old_keep and recent_drop should be skipped"
1981 );
1982 assert!(
1983 old_keep.exists(),
1984 "keep.log excluded by glob, should remain"
1985 );
1986 assert!(!old_drop.exists(), "drop.txt should be removed");
1987 assert!(new_drop.exists(), "recent.txt should remain (too new)");
1988 Ok(())
1989 }
1990
1991 #[tokio::test]
1993 #[traced_test]
1994 async fn time_filter_with_dry_run() -> Result<(), anyhow::Error> {
1995 let test_path = testutils::create_temp_dir().await?;
1996 let old_file = test_path.join("old.txt");
1997 let new_file = test_path.join("new.txt");
1998 tokio::fs::write(&old_file, "x").await?;
1999 tokio::fs::write(&new_file, "x").await?;
2000 set_mtime_age(&old_file, std::time::Duration::from_secs(7200))?;
2001 set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
2002 set_mtime_age(&test_path, std::time::Duration::from_secs(7200))?;
2003 let summary = rm(
2004 &PROGRESS,
2005 &test_path,
2006 &Settings {
2007 fail_early: false,
2008 filter: None,
2009 time_filter: Some(TimeFilter {
2010 modified_before: Some(std::time::Duration::from_secs(3600)),
2011 created_before: None,
2012 }),
2013 dry_run: Some(DryRunMode::Explain),
2014 },
2015 )
2016 .await?;
2017 assert_eq!(
2018 summary.files_removed, 1,
2019 "should report old file would be removed"
2020 );
2021 assert_eq!(
2022 summary.files_skipped, 1,
2023 "should report new file would be skipped"
2024 );
2025 assert!(old_file.exists(), "old.txt should still exist (dry-run)");
2026 assert!(new_file.exists(), "new.txt should still exist (dry-run)");
2027 Ok(())
2028 }
2029
2030 #[tokio::test]
2033 #[traced_test]
2034 async fn fresh_top_level_directory_is_traversed_but_not_removed()
2035 -> Result<(), anyhow::Error> {
2036 let test_path = testutils::create_temp_dir().await?;
2037 let old_inside = test_path.join("old.txt");
2038 tokio::fs::write(&old_inside, "x").await?;
2039 set_mtime_age(&old_inside, std::time::Duration::from_secs(7200))?;
2040 tokio::fs::set_permissions(&test_path, std::fs::Permissions::from_mode(0o555)).await?;
2042 let summary = rm(
2043 &PROGRESS,
2044 &test_path,
2045 &Settings {
2046 fail_early: false,
2047 filter: None,
2048 time_filter: Some(TimeFilter {
2049 modified_before: Some(std::time::Duration::from_secs(3600)),
2050 created_before: None,
2051 }),
2052 dry_run: None,
2053 },
2054 )
2055 .await?;
2056 assert_eq!(
2057 summary.files_removed, 1,
2058 "old child should be removed despite fresh parent"
2059 );
2060 assert_eq!(
2061 summary.directories_skipped, 1,
2062 "fresh root itself is skipped at removal time"
2063 );
2064 assert_eq!(
2065 summary.directories_removed, 0,
2066 "fresh root must not be removed"
2067 );
2068 assert!(test_path.exists(), "fresh root should still exist");
2069 assert!(!old_inside.exists(), "old child should be gone");
2070 assert_eq!(
2071 tokio::fs::metadata(&test_path).await?.permissions().mode() & 0o7777,
2072 0o555,
2073 "time-filter retention did not restore the original directory mode"
2074 );
2075 Ok(())
2076 }
2077
2078 #[tokio::test]
2080 #[traced_test]
2081 async fn time_filter_on_root_file_argument() -> Result<(), anyhow::Error> {
2082 let test_path = testutils::create_temp_dir().await?;
2083 let new_file = test_path.join("new.txt");
2084 tokio::fs::write(&new_file, "x").await?;
2085 set_mtime_age(&new_file, std::time::Duration::from_secs(60))?;
2086 let summary = rm(
2087 &PROGRESS,
2088 &new_file,
2089 &Settings {
2090 fail_early: false,
2091 filter: None,
2092 time_filter: Some(TimeFilter {
2093 modified_before: Some(std::time::Duration::from_secs(3600)),
2094 created_before: None,
2095 }),
2096 dry_run: None,
2097 },
2098 )
2099 .await?;
2100 assert_eq!(summary.files_removed, 0);
2101 assert_eq!(
2102 summary.files_skipped, 1,
2103 "root file too new should be skipped"
2104 );
2105 assert!(new_file.exists(), "root file should still exist");
2106 Ok(())
2107 }
2108 }
2109
2110 mod max_files_in_flight_tests {
2112 use super::*;
2113
2114 #[tokio::test]
2118 async fn filtered_root_waits_for_admission_before_setup() -> Result<(), anyhow::Error> {
2119 let root = testutils::create_temp_dir().await?;
2120 let path = root.join("victim");
2121 tokio::fs::write(&path, b"x").await?;
2122 let mut filter = crate::filter::FilterSettings::new();
2123 filter.add_exclude("victim")?;
2124 let settings = Settings {
2125 fail_early: true,
2126 filter: Some(filter),
2127 dry_run: None,
2128 time_filter: None,
2129 };
2130 let admission = testutils::AdmissionLimit::new().await;
2131 admission.set_files_in_flight(1);
2132 let stat_resource =
2133 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
2134 admission.set_max_ops_in_flight(stat_resource, 1);
2135 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
2136 let operation = rm(&PROGRESS, &path, &settings);
2137 tokio::pin!(operation);
2138 let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
2139 let mut second_permit = Box::pin(throttle::pending_meta_permit());
2140 let setup_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
2141 drop(second_permit);
2142 drop(held_stat);
2143 let result = admission
2144 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
2145 .await;
2146 assert!(
2147 stopped_at_stat_gate,
2148 "rm root did not reach the held stat gate"
2149 );
2150 let summary =
2151 result.context("rm root did not resume after stat capacity was released")??;
2152 assert!(
2153 !setup_bypassed_admission,
2154 "rm performed root setup before pending-metadata admission"
2155 );
2156 assert_eq!(summary.files_skipped, 1);
2157 Ok(())
2158 }
2159
2160 #[tokio::test]
2163 #[traced_test]
2164 async fn wide_rm_under_files_in_flight_saturation() -> Result<(), anyhow::Error> {
2165 let test_path = testutils::create_temp_dir().await?;
2166 let file_count = 200;
2167 for i in 0..file_count {
2168 tokio::fs::write(
2169 test_path.join(format!("{}.txt", i)),
2170 format!("content-{}", i),
2171 )
2172 .await?;
2173 }
2174 let admission = testutils::AdmissionLimit::new().await;
2176 admission.set_files_in_flight(4);
2177 let summary = admission
2178 .run_with_timeout(
2179 std::time::Duration::from_secs(30),
2180 rm(
2181 &PROGRESS,
2182 &test_path,
2183 &Settings {
2184 fail_early: true,
2185 filter: None,
2186 dry_run: None,
2187 time_filter: None,
2188 },
2189 ),
2190 )
2191 .await
2192 .context("rm timed out — possible deadlock")??;
2193 assert_eq!(summary.files_removed, file_count);
2194 assert_eq!(summary.directories_removed, 1);
2195 assert!(!test_path.exists());
2196 Ok(())
2197 }
2198
2199 #[tokio::test]
2202 #[traced_test]
2203 async fn deep_tree_no_deadlock_under_files_in_flight_saturation()
2204 -> Result<(), anyhow::Error> {
2205 let test_path = testutils::create_temp_dir().await?;
2206 let depth = 20;
2207 let files_per_level = 5;
2208 let limit = 1;
2209 let mut dir = test_path.clone();
2211 for level in 0..depth {
2212 tokio::fs::create_dir_all(&dir).await?;
2213 for f in 0..files_per_level {
2214 tokio::fs::write(
2215 dir.join(format!("f{}_{}.txt", level, f)),
2216 format!("L{}F{}", level, f),
2217 )
2218 .await?;
2219 }
2220 dir = dir.join(format!("d{}", level));
2221 }
2222 let admission = testutils::AdmissionLimit::new().await;
2223 admission.set_files_in_flight(limit);
2224 let summary = admission
2225 .run_with_timeout(
2226 std::time::Duration::from_secs(30),
2227 rm(
2228 &PROGRESS,
2229 &test_path,
2230 &Settings {
2231 fail_early: true,
2232 filter: None,
2233 dry_run: None,
2234 time_filter: None,
2235 },
2236 ),
2237 )
2238 .await
2239 .context("rm timed out — possible deadlock")?
2240 .context("rm failed")?;
2241 assert_eq!(summary.files_removed, depth * files_per_level);
2242 assert_eq!(summary.directories_removed, depth);
2243 assert!(!test_path.exists());
2244 Ok(())
2245 }
2246
2247 #[tokio::test]
2263 #[traced_test]
2264 async fn hinted_leaf_that_is_dir_drops_permit_before_recursion() -> anyhow::Result<()> {
2265 let root = testutils::create_temp_dir().await?;
2266 let dir_path = root.join("d");
2268 tokio::fs::create_dir(&dir_path).await?;
2269 tokio::fs::write(dir_path.join("c"), b"x").await?;
2270 let admission = testutils::AdmissionLimit::new().await;
2273 admission.set_files_in_flight(1);
2274 let parent = Dir::open_parent_dir(&root, congestion::Side::Source)
2276 .await
2277 .context("open parent dir")?;
2278 let parent = Arc::new(parent.into_tree());
2279 let name = std::ffi::OsStr::new("d");
2280 let handle = parent.child(name).await.context("classify d")?;
2281 assert_eq!(
2282 handle.kind(),
2283 EntryKind::Dir,
2284 "fixture `d` must be a directory"
2285 );
2286 drop(handle);
2287 let settings = Settings {
2288 fail_early: true,
2289 filter: None,
2290 dry_run: None,
2291 time_filter: None,
2292 };
2293 let visitor = Arc::new(RmVisitor {
2294 protection: None,
2295 prog_track: &PROGRESS,
2296 settings: settings.clone(),
2297 });
2298 let cx = EntryCx::root(
2299 Arc::clone(&parent),
2300 name.to_owned(),
2301 dir_path.clone(),
2302 &PROGRESS,
2303 );
2304 let permit =
2307 crate::walk::preacquire_leaf_permit(PermitKind::PendingMeta, Some(EntryKind::File))
2308 .await;
2309 assert!(permit.is_some(), "the pre-acquire must take the one permit");
2310 let result = admission
2311 .run_with_timeout(
2312 std::time::Duration::from_secs(20),
2313 process_entry(visitor, cx, (), permit),
2314 )
2315 .await;
2316 let summary = result
2317 .context(
2318 "process_entry hung — leaf permit held across directory recursion (deadlock)",
2319 )?
2320 .map_err(|e| e.source)?;
2321 assert_eq!(summary.files_removed, 1, "child file should be removed");
2322 assert_eq!(
2323 summary.directories_removed, 1,
2324 "directory should be removed"
2325 );
2326 assert!(!dir_path.exists(), "directory `d` should be gone");
2327 Ok(())
2328 }
2329 }
2330
2331 mod race_tests {
2333 use super::*;
2334
2335 static RACE_PROGRESS: std::sync::LazyLock<progress::Progress> =
2336 std::sync::LazyLock::new(progress::Progress::new);
2337
2338 #[tokio::test]
2339 async fn non_directory_action_cannot_remove_directory_replacement() -> anyhow::Result<()> {
2340 let tmp = tempfile::tempdir()?;
2341 let entry = tmp.path().join("entry");
2342 let original = tmp.path().join("original");
2343 tokio::fs::write(&entry, b"original").await?;
2344 let parent = Arc::new(
2345 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2346 .await?
2347 .into_tree(),
2348 );
2349 let handle = parent.child(OsStr::new("entry")).await?;
2350 let leaf = AdmittedLeaf::try_new(handle, None)
2351 .map_err(|_| anyhow::anyhow!("file fixture classified as a directory"))?;
2352 tokio::fs::rename(&entry, &original).await?;
2353 tokio::fs::create_dir(&entry).await?;
2354 tokio::fs::write(entry.join("replacement-child"), b"replacement").await?;
2355 let visitor = RmVisitor {
2356 protection: None,
2357 prog_track: &RACE_PROGRESS,
2358 settings: Settings {
2359 fail_early: true,
2360 filter: None,
2361 time_filter: None,
2362 dry_run: None,
2363 },
2364 };
2365 let cx = EntryCx::root(
2366 parent,
2367 OsStr::new("entry").to_owned(),
2368 entry.clone(),
2369 &RACE_PROGRESS,
2370 )
2371 .with_relative_path(std::path::PathBuf::from("entry"));
2372 let error = visitor
2373 .visit_leaf(&cx, &(), leaf)
2374 .await
2375 .expect_err("a nondirectory unlink must reject a replacement directory");
2376 assert!(format!("{:#}", error.source).contains("failed removing"));
2377 assert_eq!(tokio::fs::read(&original).await?, b"original");
2378 assert_eq!(
2379 tokio::fs::read(entry.join("replacement-child")).await?,
2380 b"replacement"
2381 );
2382 Ok(())
2383 }
2384
2385 #[tokio::test]
2386 async fn directory_replacement_is_not_descended_after_classification() -> anyhow::Result<()>
2387 {
2388 let tmp = tempfile::tempdir()?;
2389 let entry = tmp.path().join("entry");
2390 let original = tmp.path().join("original");
2391 tokio::fs::create_dir(&entry).await?;
2392 let parent = Arc::new(
2393 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2394 .await?
2395 .into_tree(),
2396 );
2397 let handle = parent.child(OsStr::new("entry")).await?;
2398 tokio::fs::rename(&entry, &original).await?;
2399 tokio::fs::create_dir(&entry).await?;
2400 tokio::fs::write(entry.join("replacement-child"), b"replacement").await?;
2401 let visitor = RmVisitor {
2402 protection: None,
2403 prog_track: &RACE_PROGRESS,
2404 settings: Settings {
2405 fail_early: true,
2406 filter: None,
2407 time_filter: None,
2408 dry_run: None,
2409 },
2410 };
2411 let cx = EntryCx::root(
2412 parent,
2413 OsStr::new("entry").to_owned(),
2414 entry.clone(),
2415 &RACE_PROGRESS,
2416 )
2417 .with_relative_path(std::path::PathBuf::from("entry"));
2418 let error = match visitor.dir_pre(&cx, &(), &handle).await {
2419 Ok(_) => anyhow::bail!("a replacement passed the directory identity check"),
2420 Err(error) => error,
2421 };
2422 assert!(format!("{:#}", error.source).contains("changed identity before descent"));
2423 assert_eq!(
2424 tokio::fs::read(entry.join("replacement-child")).await?,
2425 b"replacement"
2426 );
2427 Ok(())
2428 }
2429
2430 #[tokio::test]
2431 async fn final_rmdir_removes_an_empty_replacement_in_the_walked_slot() -> anyhow::Result<()>
2432 {
2433 let tmp = tempfile::tempdir()?;
2434 let entry = tmp.path().join("entry");
2435 let original = tmp.path().join("original");
2436 tokio::fs::create_dir(&entry).await?;
2437 let parent = Arc::new(
2438 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2439 .await?
2440 .into_tree(),
2441 );
2442 let handle = parent.child(OsStr::new("entry")).await?;
2443 let visitor = RmVisitor {
2444 protection: None,
2445 prog_track: &RACE_PROGRESS,
2446 settings: Settings {
2447 fail_early: true,
2448 filter: None,
2449 time_filter: None,
2450 dry_run: None,
2451 },
2452 };
2453 let cx = EntryCx::root(
2454 parent,
2455 OsStr::new("entry").to_owned(),
2456 entry.clone(),
2457 &RACE_PROGRESS,
2458 )
2459 .with_relative_path(std::path::PathBuf::from("entry"));
2460 let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2461 DirAction::Descend { state, .. } => state,
2462 DirAction::Skip(_) => anyhow::bail!("unfiltered directory fixture was skipped"),
2463 };
2464 tokio::fs::rename(&entry, &original).await?;
2465 tokio::fs::create_dir(&entry).await?;
2466 let summary = visitor
2467 .dir_post(
2468 &cx,
2469 state,
2470 Ok((Summary::default(), ProcessedChildren::default())),
2471 )
2472 .await?;
2473 assert_eq!(summary.directories_removed, 1);
2474 assert!(!entry.exists(), "the empty slot replacement survived rmdir");
2475 assert!(original.is_dir());
2476 Ok(())
2477 }
2478
2479 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2480 async fn intended_removal_keeps_temporary_mode_until_rmdir() -> anyhow::Result<()> {
2481 let tmp = tempfile::tempdir()?;
2482 let entry = tmp.path().join("entry");
2483 tokio::fs::create_dir(&entry).await?;
2484 tokio::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o555)).await?;
2485 let parent = Arc::new(
2486 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2487 .await?
2488 .into_tree(),
2489 );
2490 let handle = parent.child(OsStr::new("entry")).await?;
2491 let visitor = RmVisitor {
2492 protection: None,
2493 prog_track: &RACE_PROGRESS,
2494 settings: Settings {
2495 fail_early: true,
2496 filter: None,
2497 time_filter: None,
2498 dry_run: None,
2499 },
2500 };
2501 let cx = EntryCx::root(
2502 parent,
2503 OsStr::new("entry").to_owned(),
2504 entry.clone(),
2505 &RACE_PROGRESS,
2506 )
2507 .with_relative_path(std::path::PathBuf::from("entry"));
2508 let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2509 DirAction::Descend { state, .. } => state,
2510 DirAction::Skip(_) => anyhow::bail!("unfiltered directory fixture was skipped"),
2511 };
2512 assert_eq!(
2513 tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2514 0o700,
2515 "dir_pre must relax the directory before final removal"
2516 );
2517
2518 let mut gate = testutils::BlockingPathGate::install(entry.clone());
2519 let mut task = tokio::spawn(async move {
2520 visitor
2521 .dir_post(
2522 &cx,
2523 state,
2524 Ok((Summary::default(), ProcessedChildren::default())),
2525 )
2526 .await
2527 });
2528 let timeout = std::time::Duration::from_secs(20);
2529 let gate_start = tokio::time::timeout(timeout, gate.wait_started()).await;
2530 if !matches!(&gate_start, Ok(Ok(_))) {
2531 gate.release_all();
2532 task.abort();
2533 let _ = task.await;
2534 match gate_start {
2535 Ok(Err(error)) => {
2536 return Err(error.context("final rmdir did not reach its pre-syscall gate"));
2537 }
2538 Err(error) => {
2539 return Err(anyhow::Error::new(error)
2540 .context("final rmdir did not reach its pre-syscall gate"));
2541 }
2542 Ok(Ok(_)) => unreachable!(),
2543 }
2544 }
2545 let checked_mode = tokio::fs::metadata(&entry)
2546 .await
2547 .map(|metadata| metadata.permissions().mode() & 0o7777);
2548 gate.release_all();
2549 let owner_join = match tokio::time::timeout(timeout, &mut task).await {
2550 Ok(result) => result,
2551 Err(error) => {
2552 task.abort();
2553 let _ = task.await;
2554 return Err(anyhow::Error::new(error)
2555 .context("final rmdir did not quiesce after its gate released"));
2556 }
2557 };
2558 let result = owner_join.context("final rmdir task panicked")?;
2559 let summary = result.map_err(|error| error.source)?;
2560 assert_eq!(
2561 checked_mode?, 0o700,
2562 "the intended-removal path restored metadata before the rmdir boundary"
2563 );
2564 assert!(!entry.exists(), "the by-name rmdir left the directory name");
2565 assert_eq!(summary.directories_removed, 1);
2566 Ok(())
2567 }
2568
2569 #[tokio::test]
2570 async fn filtered_retention_restores_mode_through_chmod_admission() -> anyhow::Result<()> {
2571 let tmp = tempfile::tempdir()?;
2572 let entry = tmp.path().join("entry");
2573 tokio::fs::create_dir(&entry).await?;
2574 tokio::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o555)).await?;
2575 let mut filter = crate::filter::FilterSettings::new();
2576 filter.add_include("other")?;
2577 let parent = Arc::new(
2578 Dir::open_parent_dir(tmp.path(), congestion::Side::Source)
2579 .await?
2580 .into_tree(),
2581 );
2582 let handle = parent.child(OsStr::new("entry")).await?;
2583 let visitor = RmVisitor {
2584 protection: None,
2585 prog_track: &RACE_PROGRESS,
2586 settings: Settings {
2587 fail_early: true,
2588 filter: Some(filter),
2589 time_filter: None,
2590 dry_run: None,
2591 },
2592 };
2593 let cx = EntryCx::root(
2594 parent,
2595 OsStr::new("entry").to_owned(),
2596 entry.clone(),
2597 &RACE_PROGRESS,
2598 )
2599 .with_relative_path(std::path::PathBuf::from("entry"));
2600 let state = match visitor.dir_pre(&cx, &(), &handle).await? {
2601 DirAction::Descend { state, .. } => state,
2602 DirAction::Skip(_) => anyhow::bail!("include-filter ancestor was skipped"),
2603 };
2604 assert_eq!(
2605 tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2606 0o700,
2607 "dir_pre did not relax the protected directory"
2608 );
2609
2610 let admission = testutils::AdmissionLimit::new().await;
2611 let chmod_resource =
2612 throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod);
2613 admission.set_max_ops_in_flight(chmod_resource, 1);
2614 let held_chmod = throttle::ops_in_flight_permit(chmod_resource).await;
2615 let processed = ProcessedChildren::default();
2616 let restore = visitor.dir_post(&cx, state, Ok((Summary::default(), processed)));
2617 tokio::pin!(restore);
2618 assert!(
2619 futures::poll!(restore.as_mut()).is_pending(),
2620 "filtered retention bypassed Destination/Chmod admission"
2621 );
2622 assert_eq!(
2623 tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2624 0o700,
2625 "filtered retention restored the mode while chmod admission was held"
2626 );
2627 drop(held_chmod);
2628 let summary = admission
2629 .run_with_timeout(std::time::Duration::from_secs(20), restore.as_mut())
2630 .await
2631 .context("filtered mode restore did not resume after chmod admission")?
2632 .map_err(|error| error.source)?;
2633 assert!(entry.is_dir(), "filtered retention removed the directory");
2634 assert_eq!(summary.directories_removed, 0);
2635 assert_eq!(
2636 tokio::fs::metadata(&entry).await?.permissions().mode() & 0o7777,
2637 0o555,
2638 "filtered retention did not restore the original directory mode"
2639 );
2640 Ok(())
2641 }
2642
2643 fn spawn_dir_symlink_swapper(
2650 tree: std::path::PathBuf,
2651 sentinel: std::path::PathBuf,
2652 ) -> crate::testutils::SwapperGuard {
2653 crate::testutils::SwapperGuard::spawn(move |stop| {
2654 let sub = tree.join("sub");
2655 let staged_dir = tree.join("__staged_sub_dir");
2656 let staged_link = tree.join("__staged_sub_link");
2657 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
2658 let _ = std::fs::remove_dir_all(&staged_dir);
2660 if std::fs::create_dir(&staged_dir).is_ok() {
2661 let _ = std::fs::write(staged_dir.join("real.txt"), b"REAL");
2662 let _ = std::fs::remove_dir_all(&sub);
2666 let _ = std::fs::remove_file(&sub);
2667 let _ = std::fs::rename(&staged_dir, &sub);
2668 }
2669 let _ = std::fs::remove_file(&staged_link);
2671 if std::os::unix::fs::symlink(&sentinel, &staged_link).is_ok() {
2672 let _ = std::fs::remove_dir_all(&sub);
2673 let _ = std::fs::remove_file(&sub);
2674 let _ = std::fs::rename(&staged_link, &sub);
2675 }
2676 }
2677 })
2678 }
2679
2680 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2692 async fn intermediate_dir_swap_never_deletes_out_of_tree_sentinel() -> anyhow::Result<()> {
2693 let tmp = testutils::create_temp_dir().await?;
2694 let root = tmp.as_path();
2695 let sentinel = root.join("sentinel_tree");
2697 tokio::fs::create_dir(&sentinel).await?;
2698 tokio::fs::write(sentinel.join("secret1.txt"), b"SECRET-1").await?;
2699 tokio::fs::create_dir(sentinel.join("subdir")).await?;
2700 tokio::fs::write(sentinel.join("subdir").join("secret2.txt"), b"SECRET-2").await?;
2701
2702 let tree = root.join("tree");
2703 let swapper = spawn_dir_symlink_swapper(tree.clone(), sentinel.clone());
2704
2705 let settings = Settings {
2706 fail_early: false,
2707 filter: None,
2708 dry_run: None,
2709 time_filter: None,
2710 };
2711 let mut removed = 0usize;
2712 let mut errored = 0usize;
2713 for i in 0..400 {
2714 let _ = tokio::fs::create_dir(&tree).await;
2722 for d in 0..16 {
2723 let sib = tree.join(format!("sib_{d}"));
2724 let _ = tokio::fs::create_dir(&sib).await;
2725 for f in 0..4 {
2726 let _ = tokio::fs::write(sib.join(format!("f{f}.txt")), b"x").await;
2727 }
2728 }
2729 let sub = tree.join("sub");
2730 if i % 2 == 0 {
2731 let _ = tokio::fs::remove_dir_all(&sub).await;
2734 let _ = tokio::fs::remove_file(&sub).await;
2735 let _ = tokio::fs::symlink(&sentinel, &sub).await;
2736 } else if tokio::fs::symlink_metadata(&sub).await.is_err() {
2737 let _ = tokio::fs::create_dir(&sub).await;
2738 let _ = tokio::fs::write(sub.join("real.txt"), b"REAL").await;
2739 }
2740 let result = tokio::time::timeout(
2741 std::time::Duration::from_secs(30),
2742 super::rm(&RACE_PROGRESS, &tree, &settings),
2743 )
2744 .await
2745 .expect("rm must not hang under concurrent dir swapping");
2746 let summary = match result {
2747 Ok(summary) => summary,
2748 Err(error) => {
2749 errored += 1;
2750 error.summary
2751 }
2752 };
2753 removed +=
2754 summary.files_removed + summary.symlinks_removed + summary.directories_removed;
2755 assert!(
2760 sentinel.exists(),
2761 "iteration {i}: sentinel directory was deleted — rm followed the symlink"
2762 );
2763 let s1 = tokio::fs::read(sentinel.join("secret1.txt")).await;
2764 assert!(
2765 matches!(&s1, Ok(b) if b == b"SECRET-1"),
2766 "iteration {i}: sentinel/secret1.txt was deleted or altered — rm followed the symlink"
2767 );
2768 let s2 = tokio::fs::read(sentinel.join("subdir").join("secret2.txt")).await;
2769 assert!(
2770 matches!(&s2, Ok(b) if b == b"SECRET-2"),
2771 "iteration {i}: sentinel/subdir/secret2.txt was deleted — rm recursed through the symlink"
2772 );
2773 let _ = tokio::fs::remove_dir_all(&tree).await;
2775 }
2776
2777 drop(swapper);
2778 tracing::info!("intermediate dir swap: removed={removed}, errored={errored}");
2780 assert!(
2781 removed > 0,
2782 "expected actual removals across the concurrent iterations"
2783 );
2784 Ok(())
2785 }
2786 }
2787}