Debian Codegraph @

tests/by-util/test_rm.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore rootlink dotdot rootfile deleteme keepme topfile mkdirat RDONLY FDCWD SIGSEGV rootbind submounts rprivate rbind overlayfs ENAMETOOLONG
7 #![allow(clippy::stable_sort_primitive)]
8
9 use std::process::Stdio;
10
11 use uutests::{at_and_ucmd, new_ucmd, util::TestScenario, util_name};
12
13 #[test]
14 fn test_invalid_arg() {
15 new_ucmd!().arg("--definitely-invalid").fails_with_code(1);
16 }
17
18 #[test]
19 fn test_one_file() {
20 let (at, mut ucmd) = at_and_ucmd!();
21 let file = "test_rm_one_file";
22
23 at.touch(file);
24
25 ucmd.arg(file).succeeds().no_stderr();
26
27 assert!(!at.file_exists(file));
28 }
29
30 #[test]
31 fn test_failed() {
32 let file = "test_rm_one_file"; // Doesn't exist
33
34 new_ucmd!()
35 .arg(file)
36 .fails()
37 .stderr_contains(format!("cannot remove '{file}': No such file or directory"));
38 }
39
40 #[test]
41 fn test_multiple_files() {
42 let (at, mut ucmd) = at_and_ucmd!();
43 let file_a = "test_rm_multiple_file_a";
44 let file_b = "test_rm_multiple_file_b";
45
46 at.touch(file_a);
47 at.touch(file_b);
48
49 ucmd.arg(file_a).arg(file_b).succeeds().no_stderr();
50
51 assert!(!at.file_exists(file_a));
52 assert!(!at.file_exists(file_b));
53 }
54
55 #[test]
56 fn test_interactive() {
57 let scene = TestScenario::new(util_name!());
58 let at = &scene.fixtures;
59
60 let file_a = "test_rm_interactive_file_a";
61 let file_b = "test_rm_interactive_file_b";
62
63 at.touch(file_a);
64 at.touch(file_b);
65 assert!(at.file_exists(file_a));
66 assert!(at.file_exists(file_b));
67
68 scene
69 .ucmd()
70 .arg("-i")
71 .arg(file_a)
72 .arg(file_b)
73 .pipe_in("n")
74 .succeeds();
75
76 assert!(at.file_exists(file_a));
77 assert!(at.file_exists(file_b));
78
79 scene
80 .ucmd()
81 .arg("-i")
82 .arg(file_a)
83 .arg(file_b)
84 .pipe_in("Yesh") // spell-checker:disable-line
85 .succeeds();
86
87 assert!(!at.file_exists(file_a));
88 assert!(at.file_exists(file_b));
89 }
90
91 #[test]
92 fn test_force() {
93 let (at, mut ucmd) = at_and_ucmd!();
94 let file_a = "test_rm_force_a";
95 let file_b = "test_rm_force_b";
96
97 at.touch(file_a);
98 at.touch(file_b);
99 assert!(at.file_exists(file_a));
100 assert!(at.file_exists(file_b));
101
102 ucmd.arg("-f")
103 .arg(file_a)
104 .arg(file_b)
105 .succeeds()
106 .no_stderr();
107
108 assert!(!at.file_exists(file_a));
109 assert!(!at.file_exists(file_b));
110 }
111
112 #[test]
113 fn test_force_multiple() {
114 let (at, mut ucmd) = at_and_ucmd!();
115 let file_a = "test_rm_force_a";
116 let file_b = "test_rm_force_b";
117
118 at.touch(file_a);
119 at.touch(file_b);
120 assert!(at.file_exists(file_a));
121 assert!(at.file_exists(file_b));
122
123 ucmd.arg("-f")
124 .arg("-f")
125 .arg("-f")
126 .arg(file_a)
127 .arg(file_b)
128 .succeeds()
129 .no_stderr();
130
131 assert!(!at.file_exists(file_a));
132 assert!(!at.file_exists(file_b));
133 }
134
135 #[test]
136 fn test_empty_directory() {
137 let (at, mut ucmd) = at_and_ucmd!();
138 let dir = "test_rm_empty_directory";
139
140 at.mkdir(dir);
141
142 ucmd.arg("-d").arg(dir).succeeds().no_stderr();
143
144 assert!(!at.dir_exists(dir));
145 }
146
147 #[test]
148 fn test_empty_directory_verbose() {
149 let (at, mut ucmd) = at_and_ucmd!();
150 let dir = "test_rm_empty_directory_verbose";
151
152 at.mkdir(dir);
153
154 ucmd.arg("-d")
155 .arg("-v")
156 .arg(dir)
157 .succeeds()
158 .stdout_only(format!("removed directory '{dir}'\n"));
159
160 assert!(!at.dir_exists(dir));
161 }
162
163 #[test]
164 fn test_non_empty_directory() {
165 let (at, mut ucmd) = at_and_ucmd!();
166 let dir = "test_rm_non_empty_dir";
167 let file_a = &format!("{dir}/test_rm_non_empty_file_a");
168
169 at.mkdir(dir);
170 at.touch(file_a);
171
172 #[cfg(windows)]
173 let expected = "rm: cannot remove 'test_rm_non_empty_dir': The directory is not empty.\n";
174 #[cfg(not(windows))]
175 let expected = "rm: cannot remove 'test_rm_non_empty_dir': Directory not empty\n";
176 ucmd.arg("-d").arg(dir).fails().stderr_only(expected);
177 assert!(at.file_exists(file_a));
178 assert!(at.dir_exists(dir));
179 }
180
181 #[test]
182 fn test_recursive() {
183 let (at, mut ucmd) = at_and_ucmd!();
184 let dir = "test_rm_recursive_directory";
185 let file_a = "test_rm_recursive_directory/test_rm_recursive_file_a";
186 let file_b = "test_rm_recursive_directory/test_rm_recursive_file_b";
187
188 at.mkdir(dir);
189 at.touch(file_a);
190 at.touch(file_b);
191
192 ucmd.arg("-r").arg(dir).succeeds().no_stderr();
193
194 assert!(!at.dir_exists(dir));
195 assert!(!at.file_exists(file_a));
196 assert!(!at.file_exists(file_b));
197 }
198
199 #[test]
200 fn test_one_file_system_same_device() {
201 // Cross-device skipping needs a mount point (root privileges), so here we
202 // only guard the single-device case: the whole tree must still be removed.
203 let (at, mut ucmd) = at_and_ucmd!();
204 let dir = "test_rm_one_file_system_dir";
205 let subdir = format!("{dir}/subdir");
206 let file = format!("{subdir}/file");
207
208 at.mkdir(dir);
209 at.mkdir(&subdir);
210 at.touch(&file);
211
212 ucmd.arg("--one-file-system")
213 .arg("-rf")
214 .arg(dir)
215 .succeeds()
216 .no_stderr();
217
218 assert!(!at.file_exists(&file));
219 assert!(!at.dir_exists(&subdir));
220 assert!(!at.dir_exists(dir));
221 }
222
223 #[test]
224 fn test_preserve_root_all_same_device() {
225 // Refusing to cross a device boundary needs a mount point (root
226 // privileges); without one, --preserve-root=all must remove the tree as
227 // usual since it stays on a single device.
228 let (at, mut ucmd) = at_and_ucmd!();
229 let dir = "test_rm_preserve_root_all_dir";
230 let subdir = format!("{dir}/subdir");
231 let file = format!("{subdir}/file");
232
233 at.mkdir(dir);
234 at.mkdir(&subdir);
235 at.touch(&file);
236
237 ucmd.arg("--preserve-root=all")
238 .arg("-rf")
239 .arg(dir)
240 .succeeds()
241 .no_stderr();
242
243 assert!(!at.dir_exists(dir));
244 }
245
246 #[test]
247 fn test_preserve_root_rejects_unknown_value() {
248 new_ucmd!()
249 .arg("--preserve-root=bogus")
250 .arg("-rf")
251 .arg("anything")
252 .fails()
253 .stderr_contains("invalid value 'bogus'");
254 }
255
256 #[test]
257 fn test_recursive_multiple() {
258 let (at, mut ucmd) = at_and_ucmd!();
259 let dir = "test_rm_recursive_directory";
260 let file_a = "test_rm_recursive_directory/test_rm_recursive_file_a";
261 let file_b = "test_rm_recursive_directory/test_rm_recursive_file_b";
262
263 at.mkdir(dir);
264 at.touch(file_a);
265 at.touch(file_b);
266
267 ucmd.arg("-r")
268 .arg("-r")
269 .arg("-r")
270 .arg(dir)
271 .succeeds()
272 .no_stderr();
273
274 assert!(!at.dir_exists(dir));
275 assert!(!at.file_exists(file_a));
276 assert!(!at.file_exists(file_b));
277 }
278
279 #[cfg(target_os = "linux")]
280 #[test]
281 fn test_recursive_long_filepath() {
282 let (at, mut ucmd) = at_and_ucmd!();
283 let dir = "test_rm_recursive_directory";
284 let mkdir = "test_rm_recursive_directory/".repeat(35);
285 let file_a = mkdir.clone() + "test_rm_recursive_file_a";
286 assert!(file_a.len() > 1000);
287
288 at.mkdir_all(&mkdir);
289 at.touch(&file_a);
290
291 ucmd.arg("-r").arg(dir).succeeds().no_stderr();
292
293 assert!(!at.dir_exists(dir));
294 assert!(!at.file_exists(file_a));
295 }
296
297 #[test]
298 fn test_directory_without_flag() {
299 let (at, mut ucmd) = at_and_ucmd!();
300 let dir = "test_rm_directory_without_flag_dir";
301
302 at.mkdir(dir);
303
304 ucmd.arg(dir)
305 .fails()
306 .stderr_contains(format!("cannot remove '{dir}': Is a directory"));
307 }
308
309 #[test]
310 #[cfg(windows)]
311 // https://github.com/uutils/coreutils/issues/3200
312 fn test_directory_with_trailing_backslash() {
313 let (at, mut ucmd) = at_and_ucmd!();
314 let dir = "dir";
315
316 at.mkdir(dir);
317
318 ucmd.arg(".\\dir\\").arg("-rf").succeeds();
319 assert!(!at.dir_exists(dir));
320 }
321
322 #[test]
323 fn test_verbose() {
324 let (at, mut ucmd) = at_and_ucmd!();
325 let file_a = "test_rm_verbose_file_a";
326 let file_b = "test_rm_verbose_file_b";
327
328 at.touch(file_a);
329 at.touch(file_b);
330
331 ucmd.arg("-v")
332 .arg(file_a)
333 .arg(file_b)
334 .succeeds()
335 .stdout_only(format!("removed '{file_a}'\nremoved '{file_b}'\n"));
336 }
337
338 // Regression test for issue #10551: `rm -v` must report a verbose output
339 // write failure on stderr and exit 1 instead of panicking.
340 #[test]
341 #[cfg(target_os = "linux")]
342 fn test_verbose_write_error_does_not_panic() {
343 use std::fs::OpenOptions;
344
345 let (at, mut ucmd) = at_and_ucmd!();
346 let file = "test_rm_verbose_write_error_file";
347
348 at.touch(file);
349
350 let dev_full = OpenOptions::new().write(true).open("/dev/full").unwrap();
351
352 ucmd.arg("-v")
353 .arg(file)
354 .set_stdout(dev_full)
355 .fails()
356 .code_is(1)
357 .stderr_contains("No space left on device")
358 .stderr_does_not_contain("panicked");
359
360 assert!(!at.file_exists(file));
361 }
362
363 // Directory variant of the #10551 regression test.
364 #[test]
365 #[cfg(target_os = "linux")]
366 fn test_verbose_write_error_does_not_panic_dir() {
367 use std::fs::OpenOptions;
368
369 let (at, mut ucmd) = at_and_ucmd!();
370 let dir = "test_rm_verbose_write_error_dir";
371 let file = "test_rm_verbose_write_error_dir/a";
372
373 at.mkdir(dir);
374 at.touch(file);
375
376 let dev_full = OpenOptions::new().write(true).open("/dev/full").unwrap();
377
378 ucmd.arg("-r")
379 .arg("-v")
380 .arg(dir)
381 .set_stdout(dev_full)
382 .fails()
383 .code_is(1)
384 .stderr_contains("No space left on device")
385 .stderr_does_not_contain("panicked");
386
387 // A broken stdout must not stop the removal itself.
388 assert!(!at.file_exists(file));
389 assert!(!at.dir_exists(dir));
390 }
391
392 // A broken standard output must be reported once, not once per removed entry.
393 #[test]
394 #[cfg(target_os = "linux")]
395 fn test_verbose_write_error_reported_once() {
396 use std::fs::OpenOptions;
397
398 let (at, mut ucmd) = at_and_ucmd!();
399 let dir = "test_rm_verbose_write_error_once";
400
401 at.mkdir(dir);
402 for name in ["alpha", "bravo", "charlie", "delta"] {
403 at.touch(format!("{dir}/{name}"));
404 }
405
406 let dev_full = OpenOptions::new().write(true).open("/dev/full").unwrap();
407
408 let result = ucmd
409 .arg("-r")
410 .arg("-v")
411 .arg(dir)
412 .set_stdout(dev_full)
413 .fails();
414 result.code_is(1);
415 assert_eq!(
416 result
417 .stderr_str()
418 .matches("No space left on device")
419 .count(),
420 1
421 );
422
423 assert!(!at.dir_exists(dir));
424 }
425
426 #[test]
427 #[cfg(not(windows))]
428 // on unix symlink_dir is a file
429 fn test_symlink_dir() {
430 let (at, mut ucmd) = at_and_ucmd!();
431
432 let dir = "test_rm_symlink_dir_directory";
433 let link = "test_rm_symlink_dir_link";
434
435 at.mkdir(dir);
436 at.symlink_dir(dir, link);
437
438 ucmd.arg(link).succeeds();
439 }
440
441 #[test]
442 #[cfg(windows)]
443 // on windows removing symlink_dir requires "-r" or "-d"
444 fn test_symlink_dir() {
445 let scene = TestScenario::new(util_name!());
446 let at = &scene.fixtures;
447
448 let dir = "test_rm_symlink_dir_directory";
449 let link = "test_rm_symlink_dir_link";
450
451 at.mkdir(dir);
452 at.symlink_dir(dir, link);
453
454 scene
455 .ucmd()
456 .arg(link)
457 .fails()
458 .stderr_contains(format!("cannot remove '{link}': Is a directory"));
459
460 assert!(at.dir_exists(link));
461
462 scene.ucmd().arg("-r").arg(link).succeeds();
463 }
464
465 #[test]
466 fn test_invalid_symlink() {
467 let (at, mut ucmd) = at_and_ucmd!();
468 let link = "test_rm_invalid_symlink";
469
470 at.symlink_file(link, link);
471
472 ucmd.arg(link).succeeds();
473 }
474
475 #[test]
476 fn test_force_no_operand() {
477 new_ucmd!().arg("-f").succeeds().no_stderr();
478 }
479
480 #[test]
481 fn test_no_operand() {
482 new_ucmd!().fails().usage_error("missing operand");
483 }
484
485 #[test]
486 fn test_verbose_slash() {
487 let (at, mut ucmd) = at_and_ucmd!();
488 let dir = "test_rm_verbose_slash_directory";
489 let file_a = &format!("{dir}/test_rm_verbose_slash_file_a");
490
491 at.mkdir(dir);
492 at.touch(file_a);
493
494 let file_a_normalized = &format!(
495 "{dir}{}test_rm_verbose_slash_file_a",
496 std::path::MAIN_SEPARATOR
497 );
498
499 ucmd.arg("-r")
500 .arg("-f")
501 .arg("-v")
502 .arg(format!("{dir}///"))
503 .succeeds()
504 .stdout_only(format!(
505 "removed '{file_a_normalized}'\nremoved directory '{dir}'\n"
506 ));
507
508 assert!(!at.dir_exists(dir));
509 assert!(!at.file_exists(file_a));
510 }
511
512 #[test]
513 fn test_silently_accepts_presume_input_tty2() {
514 let (at, mut ucmd) = at_and_ucmd!();
515 let file_2 = "test_rm_silently_accepts_presume_input_tty2";
516
517 at.touch(file_2);
518
519 ucmd.arg("---presume-input-tty").arg(file_2).succeeds();
520
521 assert!(!at.file_exists(file_2));
522 }
523
524 #[test]
525 fn test_interactive_never() {
526 let scene = TestScenario::new(util_name!());
527 let at = &scene.fixtures;
528 let file = "a";
529
530 for arg in ["never", "no", "none"] {
531 at.touch(file);
532 #[cfg(feature = "chmod")]
533 scene.ccmd("chmod").arg("0").arg(file).succeeds();
534
535 scene
536 .ucmd()
537 .arg(format!("--interactive={arg}"))
538 .arg(file)
539 .succeeds()
540 .no_output();
541
542 assert!(!at.file_exists(file));
543 }
544 }
545
546 #[test]
547 fn test_interactive_always() {
548 let scene = TestScenario::new(util_name!());
549 let at = &scene.fixtures;
550
551 let file_a = "a";
552 let file_b = "b";
553
554 for arg in [
555 "-i",
556 "--interactive",
557 "--interactive=always",
558 "--interactive=yes",
559 ] {
560 at.touch(file_a);
561 at.touch(file_b);
562
563 scene
564 .ucmd()
565 .arg(arg)
566 .arg(file_a)
567 .arg(file_b)
568 .pipe_in("y\ny")
569 .succeeds()
570 .no_stdout();
571
572 assert!(!at.file_exists(file_a));
573 assert!(!at.file_exists(file_b));
574 }
575 }
576
577 #[test]
578 fn test_interactive_once_prompt() {
579 let (at, mut ucmd) = at_and_ucmd!();
580
581 let file1 = "test_rm_interactive_once_recursive_prompt_file1";
582 let file2 = "test_rm_interactive_once_recursive_prompt_file2";
583 let file3 = "test_rm_interactive_once_recursive_prompt_file3";
584 let file4 = "test_rm_interactive_once_recursive_prompt_file4";
585
586 at.touch(file1);
587 at.touch(file2);
588 at.touch(file3);
589 at.touch(file4);
590
591 ucmd.arg("--interactive=once")
592 .arg(file1)
593 .arg(file2)
594 .arg(file3)
595 .arg(file4)
596 .pipe_in("y")
597 .succeeds()
598 .stderr_contains("remove 4 arguments?");
599
600 assert!(!at.file_exists(file1));
601 assert!(!at.file_exists(file2));
602 assert!(!at.file_exists(file3));
603 assert!(!at.file_exists(file4));
604 }
605
606 #[test]
607 fn test_interactive_once_recursive_prompt() {
608 let (at, mut ucmd) = at_and_ucmd!();
609
610 let file1 = "test_rm_interactive_once_recursive_prompt_file1";
611
612 at.touch(file1);
613
614 ucmd.arg("--interactive=once")
615 .arg("-r")
616 .arg(file1)
617 .pipe_in("y")
618 .succeeds()
619 .stderr_contains("remove 1 argument recursively?");
620
621 assert!(!at.file_exists(file1));
622 }
623
624 #[test]
625 fn test_descend_directory() {
626 // This test descends into each directory and deletes the files and folders inside of them
627 // This test will have the rm process asks 6 question and us answering Y to them will delete all the files and folders
628
629 // Needed for talking with stdin on platforms where CRLF or LF matters
630 const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" };
631
632 let yes = format!("y{END_OF_LINE}");
633
634 let scene = TestScenario::new(util_name!());
635 let at = &scene.fixtures;
636
637 let file_1 = "a/at.txt";
638 let file_2 = "a/b/bt.txt";
639
640 at.mkdir_all("a/b/");
641 at.touch(file_1);
642 at.touch(file_2);
643
644 let mut child = scene
645 .ucmd()
646 .set_stdin(Stdio::piped())
647 .arg("-ri")
648 .arg("a")
649 .run_no_wait();
650 child.try_write_in(yes.as_bytes()).unwrap();
651 child.try_write_in(yes.as_bytes()).unwrap();
652 child.try_write_in(yes.as_bytes()).unwrap();
653 child.try_write_in(yes.as_bytes()).unwrap();
654 child.try_write_in(yes.as_bytes()).unwrap();
655 child.try_write_in(yes.as_bytes()).unwrap();
656
657 child.wait().unwrap();
658
659 assert!(!at.dir_exists("a/b"));
660 assert!(!at.dir_exists("a"));
661 assert!(!at.file_exists(file_1));
662 assert!(!at.file_exists(file_2));
663 }
664
665 #[cfg(feature = "chmod")]
666 #[test]
667 fn test_prompts() {
668 use std::io::Write;
669
670 // Needed for talking with stdin on platforms where CRLF or LF matters
671 const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" };
672
673 let mut answers = [
674 "rm: descend into directory 'a'?",
675 "rm: remove write-protected regular empty file 'a/empty-no-write'?",
676 "rm: remove symbolic link 'a/slink'?",
677 "rm: remove symbolic link 'a/slink-dot'?",
678 "rm: remove write-protected regular file 'a/f-no-write'?",
679 "rm: remove regular empty file 'a/empty'?",
680 "rm: remove directory 'a/b'?",
681 "rm: remove write-protected directory 'a/b-no-write'?",
682 "rm: remove directory 'a'?",
683 ];
684
685 answers.sort();
686
687 let yes = format!("y{END_OF_LINE}");
688
689 let scene = TestScenario::new(util_name!());
690 let at = &scene.fixtures;
691
692 at.mkdir("a/");
693
694 let file_1 = "a/empty";
695 let file_2 = "a/empty-no-write";
696 let file_3 = "a/f-no-write";
697
698 at.touch(file_1);
699 at.touch(file_2);
700 at.make_file(file_3)
701 .write_all(b"not-empty")
702 .expect("Couldn't write to a/f-no-write");
703
704 at.symlink_dir("a/empty-f", "a/slink");
705 at.symlink_dir(".", "a/slink-dot");
706
707 let dir_1 = "a/b/";
708 let dir_2 = "a/b-no-write/";
709
710 at.mkdir(dir_1);
711 at.mkdir(dir_2);
712
713 scene
714 .ccmd("chmod")
715 .arg("u-w")
716 .arg(file_3)
717 .arg(dir_2)
718 .arg(file_2)
719 .succeeds();
720
721 let mut child = scene
722 .ucmd()
723 .set_stdin(Stdio::piped())
724 .arg("-ri")
725 .arg("a")
726 .run_no_wait();
727 for _ in 0..9 {
728 child.try_write_in(yes.as_bytes()).unwrap();
729 }
730
731 let result = child.wait().unwrap();
732
733 let mut trimmed_output = Vec::new();
734 for string in result.stderr_str().split("rm: ") {
735 if !string.is_empty() {
736 let trimmed_string = format!("rm: {string}").trim().to_string();
737 trimmed_output.push(trimmed_string);
738 }
739 }
740
741 trimmed_output.sort();
742
743 assert_eq!(trimmed_output.len(), answers.len());
744
745 for (i, checking_string) in trimmed_output.iter().enumerate() {
746 assert_eq!(checking_string, answers[i]);
747 }
748
749 assert!(!at.dir_exists("a"));
750 }
751
752 #[cfg(feature = "chmod")]
753 #[test]
754 fn test_prompts_no_tty() {
755 // This test ensures InteractiveMode.PromptProtected proceeds silently with non-interactive stdin
756
757 use std::io::Write;
758
759 let scene = TestScenario::new(util_name!());
760 let at = &scene.fixtures;
761
762 at.mkdir("a/");
763
764 let file_1 = "a/empty";
765 let file_2 = "a/empty-no-write";
766 let file_3 = "a/f-no-write";
767
768 at.touch(file_1);
769 at.touch(file_2);
770 at.make_file(file_3)
771 .write_all(b"not-empty")
772 .expect("Couldn't write to a/f-no-write");
773
774 at.symlink_dir("a/empty-f", "a/slink");
775 at.symlink_dir(".", "a/slink-dot");
776
777 let dir_1 = "a/b/";
778 let dir_2 = "a/b-no-write/";
779
780 at.mkdir(dir_1);
781 at.mkdir(dir_2);
782
783 scene
784 .ccmd("chmod")
785 .arg("u-w")
786 .arg(file_3)
787 .arg(dir_2)
788 .arg(file_2)
789 .succeeds();
790
791 scene.ucmd().arg("-r").arg("a").succeeds().no_output();
792
793 assert!(!at.dir_exists("a"));
794 }
795
796 #[test]
797 fn test_force_prompts_order() {
798 // Needed for talking with stdin on platforms where CRLF or LF matters
799 const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" };
800
801 let yes = format!("y{END_OF_LINE}");
802
803 let scene = TestScenario::new(util_name!());
804 let at = &scene.fixtures;
805
806 let empty_file = "empty";
807
808 at.touch(empty_file);
809
810 // This should cause rm to prompt to remove regular empty file
811 let mut child = scene
812 .ucmd()
813 .set_stdin(Stdio::piped())
814 .arg("-fi")
815 .arg(empty_file)
816 .run_no_wait();
817 child.try_write_in(yes.as_bytes()).unwrap();
818
819 let result = child.wait().unwrap();
820 result.stderr_only("rm: remove regular empty file 'empty'? ");
821
822 assert!(!at.file_exists(empty_file));
823
824 at.touch(empty_file);
825
826 // This should not cause rm to prompt to remove regular empty file
827 scene
828 .ucmd()
829 .arg("-if")
830 .arg(empty_file)
831 .succeeds()
832 .no_stderr();
833 assert!(!at.file_exists(empty_file));
834 }
835
836 #[test]
837 #[ignore = "issue #3722"]
838 fn test_directory_rights_rm1() {
839 let (at, mut ucmd) = at_and_ucmd!();
840 at.mkdir_all("b/a/p");
841 at.mkdir_all("b/c");
842 at.mkdir_all("b/d");
843 at.set_readonly("b/a");
844 ucmd.args(&["-rf", "b"])
845 .fails()
846 .stderr_contains("Permission denied");
847 assert!(at.dir_exists("b/a/p"));
848 assert!(!at.dir_exists("b/c"));
849 assert!(!at.dir_exists("b/d"));
850 }
851
852 #[cfg(feature = "chmod")]
853 #[test]
854 fn test_prompt_write_protected_yes() {
855 let scene = TestScenario::new(util_name!());
856 let at = &scene.fixtures;
857 let file_1 = "test_rm_prompt_write_protected_1";
858
859 at.touch(file_1);
860
861 scene.ccmd("chmod").arg("0").arg(file_1).succeeds();
862
863 scene
864 .ucmd()
865 .arg("---presume-input-tty")
866 .arg(file_1)
867 .pipe_in("y")
868 .succeeds()
869 .stderr_contains("rm: remove write-protected regular empty file");
870 assert!(!at.file_exists(file_1));
871 }
872
873 #[cfg(feature = "chmod")]
874 #[test]
875 fn test_prompt_write_protected_no() {
876 let scene = TestScenario::new(util_name!());
877 let at = &scene.fixtures;
878 let file_2 = "test_rm_prompt_write_protected_2";
879
880 at.touch(file_2);
881
882 scene.ccmd("chmod").arg("0").arg(file_2).succeeds();
883
884 scene
885 .ucmd()
886 .arg("---presume-input-tty")
887 .arg(file_2)
888 .pipe_in("n")
889 .succeeds()
890 .stderr_contains("rm: remove write-protected regular empty file");
891 assert!(at.file_exists(file_2));
892 }
893
894 #[cfg(feature = "chmod")]
895 #[test]
896 fn test_remove_inaccessible_dir() {
897 let scene = TestScenario::new(util_name!());
898 let at = &scene.fixtures;
899 let dir_1 = "test_rm_protected";
900
901 at.mkdir(dir_1);
902
903 scene.ccmd("chmod").arg("0").arg(dir_1).succeeds();
904
905 scene.ucmd().arg("-rf").arg(dir_1).succeeds();
906 assert!(!at.dir_exists(dir_1));
907 }
908
909 #[test]
910 #[cfg(not(windows))]
911 fn test_current_or_parent_dir_rm4() {
912 let ts = TestScenario::new(util_name!());
913 let at = &ts.fixtures;
914
915 at.mkdir("d");
916
917 let file_1 = "file1";
918 let file_2 = "d/file2";
919
920 at.touch(file_1);
921 at.touch(file_2);
922
923 let answers = [
924 "rm: refusing to remove '.' or '..' directory: skipping 'd/.'",
925 "rm: refusing to remove '.' or '..' directory: skipping 'd/./'",
926 "rm: refusing to remove '.' or '..' directory: skipping 'd/./'",
927 "rm: refusing to remove '.' or '..' directory: skipping 'd/..'",
928 "rm: refusing to remove '.' or '..' directory: skipping 'd/../'",
929 "rm: refusing to remove '.' or '..' directory: skipping '.'",
930 "rm: refusing to remove '.' or '..' directory: skipping './'",
931 "rm: refusing to remove '.' or '..' directory: skipping '../'",
932 "rm: refusing to remove '.' or '..' directory: skipping '..'",
933 ];
934 let std_err_str = ts
935 .ucmd()
936 .arg("-rf")
937 .arg("d/.")
938 .arg("d/./")
939 .arg("d/.////")
940 .arg("d/..")
941 .arg("d/../")
942 .arg(".")
943 .arg("./")
944 .arg("../")
945 .arg("..")
946 .fails()
947 .stderr_move_str();
948
949 for (idx, line) in std_err_str.lines().enumerate() {
950 assert_eq!(line, answers[idx]);
951 }
952 // checks that no file was silently removed
953 assert!(at.dir_exists("d"));
954 assert!(at.file_exists(file_1));
955 assert!(at.file_exists(file_2));
956 }
957
958 #[test]
959 #[cfg(windows)]
960 fn test_current_or_parent_dir_rm4_windows() {
961 let ts = TestScenario::new(util_name!());
962 let at = &ts.fixtures;
963
964 at.mkdir("d");
965
966 let file_1 = "file1";
967 let file_2 = "d/file2";
968
969 at.touch(file_1);
970 at.touch(file_2);
971
972 let answers = [
973 "rm: refusing to remove '.' or '..' directory: skipping 'd\\.'",
974 "rm: refusing to remove '.' or '..' directory: skipping 'd\\.\\'",
975 "rm: refusing to remove '.' or '..' directory: skipping 'd\\.\\'",
976 "rm: refusing to remove '.' or '..' directory: skipping 'd\\..'",
977 "rm: refusing to remove '.' or '..' directory: skipping 'd\\..\\'",
978 "rm: refusing to remove '.' or '..' directory: skipping '.'",
979 "rm: refusing to remove '.' or '..' directory: skipping '.\\'",
980 "rm: refusing to remove '.' or '..' directory: skipping '..'",
981 "rm: refusing to remove '.' or '..' directory: skipping '..\\'",
982 ];
983 let std_err_str = ts
984 .ucmd()
985 .arg("-rf")
986 .arg("d\\.")
987 .arg("d\\.\\")
988 .arg("d\\.\\\\\\\\")
989 .arg("d\\..")
990 .arg("d\\..\\")
991 .arg(".")
992 .arg(".\\")
993 .arg("..")
994 .arg("..\\")
995 .fails()
996 .stderr_move_str();
997
998 for (idx, line) in std_err_str.lines().enumerate() {
999 assert_eq!(line, answers[idx]);
1000 }
1001
1002 // checks that no file was silently removed
1003 assert!(at.dir_exists("d"));
1004 assert!(at.file_exists(file_1));
1005 assert!(at.file_exists(file_2));
1006 }
1007
1008 #[test]
1009 #[cfg(not(windows))]
1010 fn test_fifo_removal() {
1011 use std::time::Duration;
1012
1013 let scene = TestScenario::new(util_name!());
1014 let at = &scene.fixtures;
1015 at.mkfifo("some_fifo");
1016
1017 scene
1018 .ucmd()
1019 .arg("some_fifo")
1020 .timeout(Duration::from_secs(2))
1021 .succeeds();
1022 }
1023
1024 #[test]
1025 fn test_uchild_when_run_no_wait_with_a_blocking_command() {
1026 let ts = TestScenario::new("rm");
1027 let at = &ts.fixtures;
1028
1029 at.mkdir("a");
1030 at.touch("a/empty");
1031
1032 #[cfg(target_vendor = "apple")]
1033 let delay: u64 = 2000;
1034 #[cfg(not(target_vendor = "apple"))]
1035 let delay: u64 = 1000;
1036
1037 let yes = if cfg!(windows) { "y\r\n" } else { "y\n" };
1038
1039 let mut child = ts
1040 .ucmd()
1041 .set_stdin(Stdio::piped())
1042 .stderr_to_stdout()
1043 .args(&["-riv", "a"])
1044 .run_no_wait();
1045 child
1046 .make_assertion_with_delay(delay)
1047 .is_alive()
1048 .with_current_output()
1049 .stdout_is("rm: descend into directory 'a'? ");
1050
1051 #[cfg(windows)]
1052 let expected = "rm: descend into directory 'a'? \
1053 rm: remove regular empty file 'a\\empty'? ";
1054 #[cfg(unix)]
1055 let expected = "rm: descend into directory 'a'? \
1056 rm: remove regular empty file 'a/empty'? ";
1057 child.write_in(yes);
1058 child
1059 .make_assertion_with_delay(delay)
1060 .is_alive()
1061 .with_all_output()
1062 .stdout_is(expected);
1063
1064 #[cfg(windows)]
1065 let expected = "removed 'a\\empty'\nrm: remove directory 'a'? ";
1066 #[cfg(unix)]
1067 let expected = "removed 'a/empty'\nrm: remove directory 'a'? ";
1068
1069 child
1070 .write_in(yes)
1071 .make_assertion_with_delay(delay)
1072 .is_alive()
1073 .with_exact_output(44, 0)
1074 .stdout_only(expected);
1075
1076 let expected = "removed directory 'a'\n";
1077
1078 child.write_in(yes);
1079 child.wait().unwrap().stdout_only(expected).success();
1080 }
1081
1082 #[test]
1083 fn test_recursive_interactive() {
1084 let (at, mut ucmd) = at_and_ucmd!();
1085 at.mkdir("a");
1086 at.mkdir("a/b");
1087 #[cfg(windows)]
1088 let expected =
1089 "rm: descend into directory 'a'? rm: remove directory 'a\\b'? rm: remove directory 'a'? ";
1090 #[cfg(not(windows))]
1091 let expected =
1092 "rm: descend into directory 'a'? rm: remove directory 'a/b'? rm: remove directory 'a'? ";
1093 ucmd.args(&["-i", "-r", "a"])
1094 .pipe_in("y\ny\ny\n")
1095 .succeeds()
1096 .stderr_only(expected);
1097 assert!(!at.dir_exists("a/b"));
1098 assert!(!at.dir_exists("a"));
1099 }
1100
1101 // Avoid an infinite recursion due to a symbolic link to the current directory.
1102 #[test]
1103 fn test_recursive_symlink_loop() {
1104 let (at, mut ucmd) = at_and_ucmd!();
1105 at.mkdir("d");
1106 at.relative_symlink_file(".", "d/link");
1107 #[cfg(windows)]
1108 let expected = "rm: descend into directory 'd'? rm: remove symbolic link 'd\\link'? rm: remove directory 'd'? ";
1109 #[cfg(not(windows))]
1110 let expected = "rm: descend into directory 'd'? rm: remove symbolic link 'd/link'? rm: remove directory 'd'? ";
1111 ucmd.args(&["-i", "-r", "d"])
1112 .pipe_in("y\ny\ny\n")
1113 .succeeds()
1114 .stderr_only(expected);
1115 assert!(!at.symlink_exists("d/link"));
1116 assert!(!at.dir_exists("d"));
1117 }
1118
1119 #[cfg(not(windows))]
1120 #[test]
1121 fn test_only_first_error_recursive() {
1122 let (at, mut ucmd) = at_and_ucmd!();
1123 at.mkdir("a");
1124 at.mkdir("a/b");
1125 at.touch("a/b/file");
1126 // Make the inner directory not writable.
1127 at.set_mode("a/b", 0o0555);
1128
1129 // To match the behavior of GNU `rm`, print an error message for
1130 // the file in the non-writable directory, but don't print the
1131 // error messages that would have appeared when trying to remove
1132 // the directories containing the file.
1133 ucmd.args(&["-r", "-f", "a"])
1134 .fails()
1135 .stderr_only("rm: cannot remove 'a/b/file': Permission denied\n");
1136 assert!(at.file_exists("a/b/file"));
1137 assert!(at.dir_exists("a/b"));
1138 assert!(at.dir_exists("a"));
1139 }
1140
1141 #[cfg(not(windows))]
1142 #[test]
1143 fn test_unreadable_and_nonempty_dir() {
1144 let (at, mut ucmd) = at_and_ucmd!();
1145 at.mkdir_all("a/b");
1146 at.set_mode("a", 0o0333);
1147
1148 ucmd.args(&["-r", "-f", "a"])
1149 .fails()
1150 .stderr_only("rm: cannot remove 'a': Permission denied\n");
1151 assert!(at.dir_exists("a/b"));
1152 assert!(at.dir_exists("a"));
1153 }
1154
1155 #[cfg(not(windows))]
1156 #[test]
1157 fn test_recursive_remove_unreadable_subdir() {
1158 // Regression test for https://github.com/uutils/coreutils/issues/10966
1159 let (at, mut ucmd) = at_and_ucmd!();
1160 at.mkdir_all("foo/bar");
1161 at.touch("foo/bar/baz");
1162 at.set_mode("foo/bar", 0o0000);
1163
1164 let result = ucmd.args(&["-r", "-f", "foo"]).fails();
1165 result.stderr_contains("Permission denied");
1166 result.stderr_contains("foo/bar");
1167
1168 at.set_mode("foo/bar", 0o0755);
1169 }
1170
1171 #[cfg(not(windows))]
1172 #[test]
1173 fn test_inaccessible_dir() {
1174 let (at, mut ucmd) = at_and_ucmd!();
1175 at.mkdir("dir");
1176 at.set_mode("dir", 0o0333);
1177 ucmd.args(&["-d", "dir"]).succeeds().no_output();
1178 assert!(!at.dir_exists("dir"));
1179 }
1180
1181 #[cfg(not(windows))]
1182 #[test]
1183 fn test_inaccessible_dir_nonempty() {
1184 let (at, mut ucmd) = at_and_ucmd!();
1185 at.mkdir("dir");
1186 at.touch("dir/f");
1187 at.set_mode("dir", 0o0333);
1188 ucmd.args(&["-d", "dir"])
1189 .fails()
1190 .stderr_only("rm: cannot remove 'dir': Directory not empty\n");
1191 assert!(at.file_exists("dir/f"));
1192 assert!(at.dir_exists("dir"));
1193 }
1194
1195 #[cfg(not(windows))]
1196 #[test]
1197 fn test_inaccessible_dir_interactive() {
1198 let (at, mut ucmd) = at_and_ucmd!();
1199 at.mkdir("dir");
1200 at.set_mode("dir", 0);
1201 ucmd.args(&["-i", "-d", "dir"])
1202 .pipe_in("y\n")
1203 .succeeds()
1204 .stderr_only("rm: attempt removal of inaccessible directory 'dir'? ");
1205 assert!(!at.dir_exists("dir"));
1206 }
1207
1208 #[cfg(not(windows))]
1209 #[test]
1210 fn test_inaccessible_dir_recursive() {
1211 let (at, mut ucmd) = at_and_ucmd!();
1212 at.mkdir("a");
1213 at.mkdir("a/unreadable");
1214 at.set_mode("a/unreadable", 0o0333);
1215 ucmd.args(&["-r", "-f", "a"]).succeeds().no_output();
1216 assert!(!at.dir_exists("a/unreadable"));
1217 assert!(!at.dir_exists("a"));
1218 }
1219
1220 #[test]
1221 #[cfg(any(target_os = "linux", target_os = "wasi"))]
1222 fn test_non_utf8_paths() {
1223 use std::ffi::OsStr;
1224 #[cfg(target_os = "linux")]
1225 use std::os::unix::ffi::OsStrExt;
1226 #[cfg(target_os = "wasi")]
1227 use std::os::wasi::ffi::OsStrExt;
1228
1229 let scene = TestScenario::new(util_name!());
1230 let at = &scene.fixtures;
1231
1232 // Create a test file with non-UTF-8 bytes in the name
1233 let non_utf8_bytes = b"test_\xFF\xFE.txt";
1234 let non_utf8_name = OsStr::from_bytes(non_utf8_bytes);
1235
1236 // Create the actual file
1237 at.touch(non_utf8_name);
1238 assert!(at.file_exists(non_utf8_name));
1239
1240 // Test that rm handles non-UTF-8 file names without crashing
1241 scene.ucmd().arg(non_utf8_name).succeeds();
1242
1243 // The file should be removed
1244 assert!(!at.file_exists(non_utf8_name));
1245
1246 // Test with directory
1247 let non_utf8_dir_bytes = b"test_dir_\xFF\xFE";
1248 let non_utf8_dir_name = OsStr::from_bytes(non_utf8_dir_bytes);
1249
1250 at.mkdir(non_utf8_dir_name);
1251 assert!(at.dir_exists(non_utf8_dir_name));
1252
1253 scene.ucmd().args(&["-r"]).arg(non_utf8_dir_name).succeeds();
1254
1255 assert!(!at.dir_exists(non_utf8_dir_name));
1256 }
1257
1258 #[test]
1259 #[cfg(target_os = "linux")]
1260 fn test_rm_recursive_long_path_safe_traversal() {
1261 let ts = TestScenario::new(util_name!());
1262 let at = &ts.fixtures;
1263
1264 let mut deep_path = String::from("rm_deep");
1265 at.mkdir(&deep_path);
1266
1267 for i in 0..12 {
1268 let long_dir_name = format!("{}{i}", "z".repeat(80));
1269 deep_path = format!("{deep_path}/{long_dir_name}");
1270 at.mkdir_all(&deep_path);
1271 }
1272
1273 at.write("rm_deep/test1.txt", "content1");
1274 at.write(&format!("{deep_path}/test2.txt"), "content2");
1275
1276 ts.ucmd().arg("-rf").arg("rm_deep").succeeds();
1277
1278 // Verify the directory is completely removed
1279 assert!(!at.dir_exists("rm_deep"));
1280 }
1281
1282 /// A hierarchy thousands of levels deep used to make `rm -r` recurse until the
1283 /// stack ran out, which killed it with SIGSEGV and left the tree in place.
1284 ///
1285 /// Linux only: building and removing 32768 levels is slow enough elsewhere to
1286 /// run out of patience before it runs out of stack, and should the removal
1287 /// fail, tearing the tree down again falls to `fs::remove_dir_all`, whose own
1288 /// recursion then overflows the test harness's stack.
1289 #[test]
1290 #[cfg(target_os = "linux")]
1291 fn test_rm_recursive_very_deep_hierarchy() {
1292 const DEPTH: u32 = 32 * 1024;
1293
1294 use std::time::Duration;
1295
1296 use nix::errno::Errno;
1297 use nix::fcntl::{OFlag, openat};
1298 use nix::sys::stat::{Mode, mkdirat};
1299
1300 let ts = TestScenario::new(util_name!());
1301 let at = &ts.fixtures;
1302
1303 // The path of the deepest directory is far longer than PATH_MAX, so it has
1304 // to be built one level at a time with openat/mkdirat.
1305 at.mkdir("deep");
1306 let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY;
1307 let mut fd = openat(nix::fcntl::AT_FDCWD, &at.plus("deep"), flags, Mode::empty()).unwrap();
1308 // The recursion only ran out of stack around 5000 levels unoptimized and
1309 // 20000 optimized, so a shallower tree would not test anything. Some
1310 // filesystems resolve the whole path internally and refuse to go past
1311 // PATH_MAX, which caps the depth near 2000: there is nothing to test on
1312 // those, so give up rather than pretend.
1313 let mut depth = 0;
1314 while depth < DEPTH {
1315 match mkdirat(&fd, "a", Mode::from_bits_truncate(0o755)) {
1316 Ok(()) => {}
1317 Err(Errno::ENAMETOOLONG) => break,
1318 Err(e) => panic!("mkdirat at depth {depth} failed: {e}"),
1319 }
1320 fd = match openat(&fd, "a", flags, Mode::empty()) {
1321 Ok(fd) => fd,
1322 Err(Errno::ENAMETOOLONG) => break,
1323 Err(e) => panic!("openat at depth {depth} failed: {e}"),
1324 };
1325 depth += 1;
1326 }
1327
1328 // Release the deepest descriptor, so nothing holds the tree open while rm
1329 // walks it.
1330 drop(fd);
1331
1332 if depth < DEPTH {
1333 println!("this filesystem stops nesting at {depth} levels; skipping");
1334 // Still tear the tree down here: the harness cleanup recurses too.
1335 ts.ucmd()
1336 .arg("-rf")
1337 .arg("deep")
1338 .timeout(Duration::from_secs(240))
1339 .succeeds();
1340 return;
1341 }
1342
1343 // 32768 levels are 65536 metadata operations; the default 30s is not much
1344 // once the binary under test is built with coverage instrumentation.
1345 ts.ucmd()
1346 .arg("-rf")
1347 .arg("deep")
1348 .timeout(Duration::from_secs(240))
1349 .succeeds()
1350 .no_output();
1351
1352 assert!(!at.dir_exists("deep"));
1353 }
1354
1355 #[cfg(all(not(windows), feature = "chmod"))]
1356 #[test]
1357 fn test_rm_directory_not_executable() {
1358 // Test removing files with specific permission scenarios
1359 // Exercise code paths when directories have no execute permission
1360 let scene = TestScenario::new(util_name!());
1361 let at = &scene.fixtures;
1362
1363 // Create directory structure: a/0, a/1/2, a/2, a/3, b/3
1364 at.mkdir_all("a/0");
1365 at.mkdir_all("a/1/2");
1366 at.mkdir("a/2");
1367 at.mkdir("a/3");
1368 at.mkdir_all("b/3");
1369
1370 // Remove execute permission from a/1 and b
1371 scene.ccmd("chmod").arg("u-x").arg("a/1").succeeds();
1372 scene.ccmd("chmod").arg("u-x").arg("b").succeeds();
1373
1374 // Try to remove both directories recursively - this should fail
1375 let result = scene.ucmd().args(&["-rf", "a", "b"]).fails();
1376
1377 // Check for expected error messages
1378 // When directories don't have execute permission, we get "Permission denied"
1379 // when trying to access subdirectories
1380 let stderr = result.stderr_str();
1381 assert!(stderr.contains("rm: cannot remove 'a/1/2': Permission denied"));
1382 assert!(stderr.contains("rm: cannot remove 'b/3': Permission denied"));
1383
1384 // Check which directories still exist
1385 assert!(!at.dir_exists("a/0")); // Should be removed
1386 assert!(at.dir_exists("a/1")); // Should still exist (no execute permission)
1387 assert!(!at.dir_exists("a/2")); // Should be removed
1388 assert!(!at.dir_exists("a/3")); // Should be removed
1389
1390 // Restore execute permission to check b/3
1391 scene.ccmd("chmod").arg("u+x").arg("b").succeeds();
1392 assert!(at.dir_exists("b/3")); // Should still exist
1393 }
1394
1395 #[cfg(all(not(windows), feature = "chmod"))]
1396 #[test]
1397 fn test_rm_directory_not_writable() {
1398 // Test basic recursive removal
1399 // Exercise code paths when directories have no write permission
1400 let scene = TestScenario::new(util_name!());
1401 let at = &scene.fixtures;
1402
1403 // Create directory structure: b/a/p, b/c, b/d
1404 at.mkdir_all("b/a/p");
1405 at.mkdir("b/c");
1406 at.mkdir("b/d");
1407
1408 // Remove write permission from b/a
1409 scene.ccmd("chmod").arg("ug-w").arg("b/a").succeeds();
1410
1411 // Try to remove b recursively - this should fail
1412 let result = scene.ucmd().args(&["-rf", "b"]).fails();
1413
1414 // Check for expected error message
1415 // When the parent directory (b/a) doesn't have write permission,
1416 // we get "Permission denied" when trying to remove the subdirectory.
1417 // The error tracking must be correct so we don't attempt to remove the parent
1418 // directory after child failure (which would produce extra "Directory not empty" errors).
1419 result.stderr_only("rm: cannot remove 'b/a/p': Permission denied\n");
1420
1421 // Check which directories still exist
1422 assert!(at.dir_exists("b/a/p")); // Should still exist (parent not writable)
1423 assert!(!at.dir_exists("b/c")); // Should be removed
1424 assert!(!at.dir_exists("b/d")); // Should be removed
1425 }
1426
1427 #[test]
1428 fn test_progress_flag_short() {
1429 let (at, mut ucmd) = at_and_ucmd!();
1430 let file = "test_rm_progress_file";
1431
1432 at.touch(file);
1433
1434 // Test that -g flag is accepted
1435 ucmd.arg("-g").arg(file).succeeds();
1436
1437 assert!(!at.file_exists(file));
1438 }
1439
1440 #[test]
1441 fn test_progress_flag_long() {
1442 let (at, mut ucmd) = at_and_ucmd!();
1443 let file = "test_rm_progress_file";
1444
1445 at.touch(file);
1446
1447 // Test that --progress flag is accepted
1448 ucmd.arg("--progress").arg(file).succeeds();
1449
1450 assert!(!at.file_exists(file));
1451 }
1452
1453 #[test]
1454 fn test_progress_with_recursive() {
1455 let (at, mut ucmd) = at_and_ucmd!();
1456
1457 at.mkdir("test_dir");
1458 at.touch("test_dir/file1");
1459 at.touch("test_dir/file2");
1460 at.mkdir("test_dir/subdir");
1461 at.touch("test_dir/subdir/file3");
1462
1463 // Test progress with recursive removal
1464 ucmd.arg("-rg").arg("test_dir").succeeds();
1465
1466 assert!(!at.dir_exists("test_dir"));
1467 }
1468
1469 #[test]
1470 fn test_progress_with_verbose() {
1471 let (at, mut ucmd) = at_and_ucmd!();
1472 let file = "test_rm_progress_verbose_file";
1473
1474 at.touch(file);
1475
1476 // Test that progress and verbose work together
1477 ucmd.arg("-gv").arg(file).succeeds().stdout_contains(file);
1478
1479 assert!(!at.file_exists(file));
1480 }
1481
1482 #[test]
1483 fn test_progress_no_output_on_error() {
1484 let nonexistent_file = "this_file_does_not_exist";
1485
1486 // Test that progress bar is not shown when file doesn't exist
1487 new_ucmd!()
1488 .arg("--progress")
1489 .arg(nonexistent_file)
1490 .fails()
1491 .stderr_contains("cannot remove")
1492 .stderr_contains("No such file or directory");
1493 }
1494
1495 #[test]
1496 fn no_preserve_root_may_not_be_abbreviated() {
1497 let (at, _ucmd) = at_and_ucmd!();
1498 let file = "test_file_123";
1499
1500 at.touch(file);
1501
1502 for arg in ["--n", "--no-pre", "--no-preserve-ro"] {
1503 new_ucmd!()
1504 .arg(arg)
1505 .arg(file)
1506 .fails()
1507 .stderr_contains("you may not abbreviate the --no-preserve-root option");
1508 }
1509
1510 assert!(at.file_exists(file));
1511 }
1512
1513 #[cfg(unix)]
1514 #[test]
1515 fn test_symlink_to_readonly_no_prompt() {
1516 let (at, mut ucmd) = at_and_ucmd!();
1517
1518 at.touch("foo");
1519 at.set_mode("foo", 0o444);
1520 at.symlink_file("foo", "bar");
1521
1522 ucmd.arg("---presume-input-tty")
1523 .arg("bar")
1524 .succeeds()
1525 .no_stderr();
1526
1527 assert!(!at.symlink_exists("bar"));
1528 }
1529
1530 /// Test that --preserve-root properly detects symlinks pointing to root.
1531 #[cfg(unix)]
1532 #[test]
1533 fn test_preserve_root_symlink_to_root() {
1534 let (at, mut ucmd) = at_and_ucmd!();
1535
1536 // Create a symlink pointing to the root directory
1537 at.symlink_dir("/", "rootlink");
1538
1539 // Attempting to recursively delete through this symlink should fail
1540 // because it resolves to the same device/inode as "/"
1541 ucmd.arg("-rf")
1542 .arg("--preserve-root")
1543 .arg("rootlink/")
1544 .fails()
1545 .stderr_contains("it is dangerous to operate recursively on")
1546 .stderr_contains("(same as '/')");
1547
1548 // The symlink itself should still exist (we didn't delete it)
1549 assert!(at.symlink_exists("rootlink"));
1550 }
1551
1552 /// Test that --preserve-root properly detects nested symlinks pointing to root.
1553 #[cfg(unix)]
1554 #[test]
1555 fn test_preserve_root_nested_symlink_to_root() {
1556 let (at, mut ucmd) = at_and_ucmd!();
1557
1558 // Create a symlink pointing to the root directory
1559 at.symlink_dir("/", "rootlink");
1560 // Create another symlink pointing to the first symlink
1561 at.symlink_dir("rootlink", "rootlink2");
1562
1563 // Attempting to recursively delete through nested symlinks should also fail
1564 ucmd.arg("-rf")
1565 .arg("--preserve-root")
1566 .arg("rootlink2/")
1567 .fails()
1568 .stderr_contains("it is dangerous to operate recursively on")
1569 .stderr_contains("(same as '/')");
1570 }
1571
1572 /// Test that removing the symlink itself (not the target) still works.
1573 #[cfg(unix)]
1574 #[test]
1575 fn test_preserve_root_symlink_removal_without_trailing_slash() {
1576 let (at, mut ucmd) = at_and_ucmd!();
1577
1578 // Create a symlink pointing to the root directory
1579 at.symlink_dir("/", "rootlink");
1580
1581 // Removing the symlink itself (without trailing slash) should succeed
1582 // because we're removing the link, not traversing through it
1583 ucmd.arg("--preserve-root").arg("rootlink").succeeds();
1584
1585 assert!(!at.symlink_exists("rootlink"));
1586 }
1587
1588 /// `--preserve-root` must refuse a bind mount of `/`.
1589 ///
1590 /// A bind mount of `/` is an ordinary directory - not a symlink, not a cycle -
1591 /// so `canonicalize()` yields the mountpoint and every name-based check waves it
1592 /// through. Only `(st_dev, st_ino)` identifies it, and that is what the failsafe
1593 /// compares.
1594 ///
1595 /// The mount is of the real root, so nothing here may be able to delete anything
1596 /// even with the guard gone: `-i` reads stdin at EOF and so answers "no" to the
1597 /// first "descend into directory?" prompt, before any unlink. **Never make this
1598 /// `-rf`.** The mount itself lives in a throwaway user + mount namespace.
1599 #[cfg(target_os = "linux")]
1600 #[test]
1601 fn test_preserve_root_bind_mount_of_root() {
1602 use std::process::Command;
1603
1604 let ts = TestScenario::new(util_name!());
1605
1606 // Unprivileged user namespaces are disabled in some kernels and sandboxes.
1607 let can_unshare = Command::new("unshare")
1608 .args(["--user", "--map-root-user", "--mount", "true"])
1609 .status()
1610 .is_ok_and(|status| status.success());
1611 if !can_unshare {
1612 println!("TEST SKIPPED: no unprivileged mount namespace available");
1613 return;
1614 }
1615
1616 // Mount point lives in this test's own temp dir, so parallel runs cannot
1617 // collide and it goes away with the scenario.
1618 let mount_point = ts.fixtures.plus_as_string("rootbind");
1619
1620 // `mount --bind /` is refused inside a user namespace because of locked
1621 // submounts; --make-rprivate + --rbind produces the same (st_dev, st_ino).
1622 // The mount setup can still be blocked (e.g. `mount(2)` denied in a cross
1623 // container even though `unshare` starts); if it fails, exit 99 so the test
1624 // skips instead of failing for the wrong reason.
1625 let script = format!(
1626 "mkdir -p {mp}
1627 {{ mount --make-rprivate / && mount --rbind / {mp}; }} \
1628 || {{ echo MOUNT_SETUP_FAILED >&2; exit 99; }}
1629 exec {bin} rm -ri --preserve-root {mp} < /dev/null",
1630 mp = shell_quote(&mount_point),
1631 bin = shell_quote(&ts.bin_path.to_string_lossy())
1632 );
1633 let output = Command::new("unshare")
1634 .args(["--user", "--map-root-user", "--mount", "sh", "-c", &script])
1635 .env("LC_ALL", "C")
1636 .env("LANG", "C")
1637 .env("LANGUAGE", "C")
1638 .output()
1639 .expect("failed to spawn unshare");
1640
1641 let stderr = String::from_utf8_lossy(&output.stderr);
1642 if output.status.code() == Some(99) || stderr.contains("MOUNT_SETUP_FAILED") {
1643 println!("TEST SKIPPED: could not set up a bind mount in the namespace: {stderr}");
1644 return;
1645 }
1646 assert!(
1647 stderr.contains("it is dangerous to operate recursively on")
1648 && stderr.contains("(same as '/')"),
1649 "--preserve-root did not refuse a bind mount of /: {stderr}"
1650 );
1651 assert!(!output.status.success());
1652 }
1653
1654 /// Wrap `s` in single quotes for `sh -c`, escaping any single quote in it.
1655 #[cfg(target_os = "linux")]
1656 fn shell_quote(s: &str) -> String {
1657 format!("'{}'", s.replace('\'', "'\\''"))
1658 }
1659
1660 /// Test that literal "/" is still properly protected.
1661 #[test]
1662 fn test_preserve_root_literal_root() {
1663 new_ucmd!()
1664 .arg("-rf")
1665 .arg("--preserve-root")
1666 .arg("/")
1667 .fails()
1668 .stderr_contains("it is dangerous to operate recursively on '/'")
1669 .stderr_contains("use --no-preserve-root to override this failsafe");
1670 }
1671
1672 // Regression tests for Issue #9749: rm -rf ./ and variants silently delete
1673 // current directory contents
1674
1675 /// Test edge cases for dot/dotdot protection with multiple slashes
1676 #[test]
1677 #[cfg(not(windows))]
1678 fn test_dot_protection_multiple_slashes() {
1679 // Test various patterns with multiple slashes - each in a fresh scenario
1680 let test_cases = ["./", ".//", ".///", ".//./", "../", "..//", "..//../"];
1681
1682 for case in &test_cases {
1683 let ts = TestScenario::new(util_name!());
1684 let at = &ts.fixtures;
1685
1686 at.mkdir("d");
1687 at.touch("file1");
1688 at.touch("d/file2");
1689
1690 let result = ts.ucmd().arg("-rf").arg(case).fails();
1691
1692 // Verify error message - either dot protection or root protection
1693 // depending on temp directory structure
1694 let stderr = result.stderr_str();
1695 assert!(
1696 stderr.contains("refusing to remove") || stderr.contains("dangerous to operate"),
1697 "Expected error message for rm -rf {case}, got: {stderr}"
1698 );
1699
1700 // CRITICAL: Verify no files were silently deleted (the #9749 bug)
1701 assert!(
1702 at.dir_exists("d"),
1703 "Directory 'd' should exist after rm -rf {case}"
1704 );
1705 assert!(
1706 at.file_exists("file1"),
1707 "file1 should exist after rm -rf {case}"
1708 );
1709 assert!(
1710 at.file_exists("d/file2"),
1711 "d/file2 should exist after rm -rf {case}"
1712 );
1713 }
1714 }
1715
1716 /// Test dot/dotdot protection in deeply nested paths
1717 #[test]
1718 #[cfg(not(windows))]
1719 fn test_dot_protection_nested_paths() {
1720 let test_cases = [
1721 "a/b/c/.",
1722 "a/b/c/./",
1723 "a/b/c/..",
1724 "a/b/c/../",
1725 "a/b/.",
1726 "a/b/../",
1727 ];
1728
1729 for case in &test_cases {
1730 let ts = TestScenario::new(util_name!());
1731 let at = &ts.fixtures;
1732
1733 at.mkdir_all("a/b/c");
1734 at.touch("a/b/c/file");
1735 at.touch("rootfile");
1736
1737 let result = ts.ucmd().arg("-rf").arg(case).fails();
1738 result.stderr_contains("refusing to remove");
1739
1740 // Verify structure is intact
1741 assert!(
1742 at.dir_exists("a/b/c"),
1743 "a/b/c should exist after rm -rf {case}"
1744 );
1745 assert!(
1746 at.file_exists("a/b/c/file"),
1747 "a/b/c/file should exist after rm -rf {case}"
1748 );
1749 assert!(
1750 at.file_exists("rootfile"),
1751 "rootfile should exist after rm -rf {case}"
1752 );
1753 }
1754 }
1755
1756 /// Test that normal files/directories with dots in names are NOT protected
1757 #[test]
1758 fn test_normal_files_with_dots_not_protected() {
1759 let ts = TestScenario::new(util_name!());
1760 let at = &ts.fixtures;
1761
1762 at.touch(".hidden");
1763 at.touch("..double_hidden");
1764 at.touch("file.txt");
1765 at.mkdir("dir.with.dots");
1766 at.touch("dir.with.dots/file");
1767
1768 // These should succeed (not be blocked)
1769 ts.ucmd().arg("-f").arg(".hidden").succeeds();
1770 ts.ucmd().arg("-f").arg("..double_hidden").succeeds();
1771 ts.ucmd().arg("-f").arg("file.txt").succeeds();
1772 ts.ucmd().arg("-rf").arg("dir.with.dots").succeeds();
1773
1774 assert!(!at.file_exists(".hidden"));
1775 assert!(!at.file_exists("..double_hidden"));
1776 assert!(!at.file_exists("file.txt"));
1777 assert!(!at.dir_exists("dir.with.dots"));
1778 }
1779
1780 /// Test mixed valid and invalid arguments
1781 ///
1782 /// When rm encounters a dot/directory protection error, it should:
1783 /// 1. Process arguments in order
1784 /// 2. Continue with remaining arguments after reporting the error
1785 /// 3. Report the error
1786 #[test]
1787 #[cfg(not(windows))]
1788 fn test_mixed_valid_and_dot_arguments() {
1789 let ts = TestScenario::new(util_name!());
1790 let at = &ts.fixtures;
1791
1792 at.mkdir("deleteme");
1793 at.touch("deleteme/file");
1794 at.mkdir("d"); // Create directory for dot test
1795 at.touch("keepme");
1796
1797 let result = ts
1798 .ucmd()
1799 .arg("-rf")
1800 .arg("deleteme")
1801 .arg("d/.") // This should be refused (in a subdir)
1802 .arg("keepme")
1803 .fails();
1804
1805 // Should have deleted deleteme
1806 assert!(!at.dir_exists("deleteme"));
1807
1808 // Should have refused to remove d/.
1809 result.stderr_contains("refusing to remove");
1810
1811 // keepme should also be deleted (rm continues after errors)
1812 assert!(!at.file_exists("keepme"));
1813 }
1814
1815 /// Test Windows-specific edge cases
1816 #[test]
1817 #[cfg(windows)]
1818 fn test_dot_protection_windows_edge_cases() {
1819 // Test Windows backslash patterns - each in a fresh scenario
1820 let test_cases = [".\\", ".\\\\", "..\\", "..\\\\", "d\\.\\", "d\\..\\"];
1821
1822 for case in &test_cases {
1823 let ts = TestScenario::new(util_name!());
1824 let at = &ts.fixtures;
1825
1826 at.mkdir("d");
1827 at.touch("file1");
1828 at.touch("d\\file2");
1829
1830 let result = ts.ucmd().arg("-rf").arg(case).fails();
1831 result.stderr_contains("refusing to remove");
1832
1833 // Verify no files were deleted
1834 assert!(
1835 at.dir_exists("d"),
1836 "Directory 'd' should exist after rm -rf {case}",
1837 );
1838 assert!(
1839 at.file_exists("file1"),
1840 "file1 should exist after rm -rf {case}",
1841 );
1842 }
1843 }
1844
1845 /// Test symlink targets that resolve to . or ..
1846 ///
1847 /// Note: Symlinks to . or .. are handled differently than direct paths.
1848 /// The symlink itself is removed, but the target (current/parent dir) is not.
1849 /// This test verifies symlinks can be removed without affecting the actual directories.
1850 #[cfg(unix)]
1851 #[test]
1852 fn test_symlink_to_dot_protection() {
1853 let ts = TestScenario::new(util_name!());
1854 let at = &ts.fixtures;
1855
1856 at.mkdir("subdir");
1857 at.touch("subdir/file");
1858 at.touch("topfile");
1859
1860 // Create symlinks pointing to . and ..
1861 at.symlink_dir(".", "subdir/dot_link");
1862 at.symlink_dir("..", "subdir/dotdot_link");
1863
1864 // Remove the symlinks themselves (without trailing slash they are just links)
1865 ts.ucmd().arg("-f").arg("subdir/dot_link").succeeds();
1866 ts.ucmd().arg("-f").arg("subdir/dotdot_link").succeeds();
1867
1868 // Verify symlinks are gone but directories still exist
1869 assert!(!at.symlink_exists("subdir/dot_link"));
1870 assert!(!at.symlink_exists("subdir/dotdot_link"));
1871 assert!(at.dir_exists("subdir"));
1872 assert!(at.file_exists("subdir/file"));
1873 assert!(at.file_exists("topfile"));
1874 }
1875
1876 #[test]
1877 fn test_dash_hint_shown_for_existing_dash_file() {
1878 // A dash-prefixed name that exists is parsed as an option; rm should point
1879 // the user at the `./` workaround instead of silently failing.
1880 let (at, mut ucmd) = at_and_ucmd!();
1881
1882 at.touch("-z");
1883 let result = ucmd.arg("-z").fails_with_code(1);
1884 result.stderr_contains("./-z' to remove the file '-z'.");
1885 result.stderr_contains("--help' for more information.");
1886 assert!(at.file_exists("-z"));
1887 }
1888
1889 #[test]
1890 fn test_dash_hint_absent_without_matching_file() {
1891 // When no such file is on disk there is nothing to suggest, so the hint
1892 // line must be omitted entirely.
1893 new_ucmd!()
1894 .arg("-q")
1895 .fails_with_code(1)
1896 .stderr_does_not_contain("to remove the file");
1897 }
1898
1899 #[cfg(unix)]
1900 #[test]
1901 fn test_dash_hint_is_shell_escaped() {
1902 // Awkward characters in the name (here a tab and a quote) must be escaped so
1903 // the printed command can be pasted into a shell verbatim.
1904 let (at, mut ucmd) = at_and_ucmd!();
1905
1906 let name = "-a\tb'c";
1907 at.touch(name);
1908 ucmd.arg(name)
1909 .fails_with_code(1)
1910 .stderr_contains("./'-a'$'\\t''b'\\''c'' to remove the file '-a'$'\\t''b'\\''c'.");
1911 }