Debian Codegraph @

tests/by-util/test_mv.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 //
7 // spell-checker:ignore mydir hardlinked tmpfs notty unwriteable myfolder SRCDATA DSTDATA REALDATA
8 // spell-checker:ignore dirattr dirvalue setfattr getfattr
9
10 use rstest::rstest;
11 use std::io::Write;
12 #[cfg(not(windows))]
13 use std::path::Path;
14 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
15 use uucore::selinux::get_getfattr_output;
16 use uutests::new_ucmd;
17 #[cfg(unix)]
18 use uutests::util::TerminalSimulation;
19 use uutests::util::TestScenario;
20 use uutests::{at_and_ucmd, util_name};
21
22 #[test]
23 fn test_mv_invalid_arg() {
24 new_ucmd!().arg("--definitely-invalid").fails_with_code(1);
25 }
26
27 #[test]
28 fn test_mv_missing_dest() {
29 let (at, mut ucmd) = at_and_ucmd!();
30 let dir = "dir";
31
32 at.mkdir(dir);
33
34 ucmd.arg(dir).fails();
35 }
36
37 #[test]
38 fn test_mv_rename_dir() {
39 let (at, mut ucmd) = at_and_ucmd!();
40 let dir1 = "test_mv_rename_dir";
41 let dir2 = "test_mv_rename_dir2";
42
43 at.mkdir(dir1);
44
45 ucmd.arg(dir1).arg(dir2).succeeds().no_stderr();
46
47 assert!(at.dir_exists(dir2));
48 }
49
50 #[test]
51 fn test_mv_rename_file() {
52 let (at, mut ucmd) = at_and_ucmd!();
53 let file1 = "test_mv_rename_file";
54 let file2 = "test_mv_rename_file2";
55
56 at.touch(file1);
57
58 ucmd.arg(file1).arg(file2).succeeds().no_stderr();
59 assert!(at.file_exists(file2));
60 }
61
62 #[test]
63 fn test_mv_with_source_file_opened_and_target_file_exists() {
64 let (at, mut ucmd) = at_and_ucmd!();
65
66 let src = "source_file_opened";
67 let dst = "target_file_exists";
68
69 let f = at.make_file(src);
70
71 at.touch(dst);
72
73 ucmd.arg(src).arg(dst).succeeds().no_output();
74
75 drop(f);
76 }
77
78 #[test]
79 fn test_mv_move_file_into_dir() {
80 let (at, mut ucmd) = at_and_ucmd!();
81 let dir = "test_mv_move_file_into_dir_dir";
82 let file = "test_mv_move_file_into_dir_file";
83
84 at.mkdir(dir);
85 at.touch(file);
86
87 ucmd.arg(file).arg(dir).succeeds().no_stderr();
88
89 assert!(at.file_exists(format!("{dir}/{file}")));
90 }
91
92 #[test]
93 fn test_mv_move_file_into_dir_with_target_arg() {
94 let (at, mut ucmd) = at_and_ucmd!();
95 let dir = "test_mv_move_file_into_dir_with_target_arg_dir";
96 let file = "test_mv_move_file_into_dir_with_target_arg_file";
97
98 at.mkdir(dir);
99 at.touch(file);
100
101 ucmd.arg("--target")
102 .arg(dir)
103 .arg(file)
104 .succeeds()
105 .no_stderr();
106
107 assert!(at.file_exists(format!("{dir}/{file}")));
108 }
109
110 #[test]
111 fn test_mv_move_file_into_file_with_target_arg() {
112 let (at, mut ucmd) = at_and_ucmd!();
113 let file1 = "test_mv_move_file_into_file_with_target_arg_file1";
114 let file2 = "test_mv_move_file_into_file_with_target_arg_file2";
115
116 at.touch(file1);
117 at.touch(file2);
118
119 ucmd.arg("--target")
120 .arg(file1)
121 .arg(file2)
122 .fails()
123 .stderr_only(format!("mv: target directory '{file1}': Not a directory\n"));
124
125 assert!(at.file_exists(file1));
126 }
127
128 #[test]
129 fn test_mv_move_multiple_files_into_file() {
130 let (at, mut ucmd) = at_and_ucmd!();
131 let file1 = "test_mv_move_multiple_files_into_file1";
132 let file2 = "test_mv_move_multiple_files_into_file2";
133 let file3 = "test_mv_move_multiple_files_into_file3";
134
135 at.touch(file1);
136 at.touch(file2);
137 at.touch(file3);
138
139 ucmd.arg(file1)
140 .arg(file2)
141 .arg(file3)
142 .fails()
143 .stderr_only(format!("mv: target '{file3}': Not a directory\n"));
144
145 assert!(at.file_exists(file1));
146 assert!(at.file_exists(file2));
147 }
148
149 #[test]
150 fn test_mv_move_file_between_dirs() {
151 let (at, mut ucmd) = at_and_ucmd!();
152 let dir1 = "test_mv_move_file_between_dirs_dir1";
153 let dir2 = "test_mv_move_file_between_dirs_dir2";
154 let file = "test_mv_move_file_between_dirs_file";
155
156 at.mkdir(dir1);
157 at.mkdir(dir2);
158 at.touch(format!("{dir1}/{file}"));
159
160 assert!(at.file_exists(format!("{dir1}/{file}")));
161
162 ucmd.arg(format!("{dir1}/{file}"))
163 .arg(dir2)
164 .succeeds()
165 .no_stderr();
166
167 assert!(!at.file_exists(format!("{dir1}/{file}")));
168 assert!(at.file_exists(format!("{dir2}/{file}")));
169 }
170
171 #[test]
172 fn test_mv_strip_slashes() {
173 let scene = TestScenario::new(util_name!());
174 let at = &scene.fixtures;
175 let dir = "test_mv_strip_slashes_dir";
176 let file = "test_mv_strip_slashes_file";
177 let mut source = file.to_owned();
178 source.push('/');
179
180 at.mkdir(dir);
181 at.touch(file);
182
183 scene.ucmd().arg(&source).arg(dir).fails();
184
185 assert!(!at.file_exists(format!("{dir}/{file}")));
186
187 scene
188 .ucmd()
189 .arg("--strip-trailing-slashes")
190 .arg(source)
191 .arg(dir)
192 .succeeds()
193 .no_stderr();
194
195 assert!(at.file_exists(format!("{dir}/{file}")));
196 }
197
198 #[test]
199 fn test_mv_multiple_files() {
200 let (at, mut ucmd) = at_and_ucmd!();
201 let target_dir = "test_mv_multiple_files_dir";
202 let file_a = "test_mv_multiple_file_a";
203 let file_b = "test_mv_multiple_file_b";
204
205 at.mkdir(target_dir);
206 at.touch(file_a);
207 at.touch(file_b);
208
209 ucmd.arg(file_a)
210 .arg(file_b)
211 .arg(target_dir)
212 .succeeds()
213 .no_stderr();
214
215 assert!(at.file_exists(format!("{target_dir}/{file_a}")));
216 assert!(at.file_exists(format!("{target_dir}/{file_b}")));
217 }
218
219 #[test]
220 fn test_mv_multiple_folders() {
221 let (at, mut ucmd) = at_and_ucmd!();
222 let target_dir = "test_mv_multiple_dirs_dir";
223 let dir_a = "test_mv_multiple_dir_a";
224 let dir_b = "test_mv_multiple_dir_b";
225
226 at.mkdir(target_dir);
227 at.mkdir(dir_a);
228 at.mkdir(dir_b);
229
230 ucmd.arg(dir_a)
231 .arg(dir_b)
232 .arg(target_dir)
233 .succeeds()
234 .no_stderr();
235
236 assert!(at.dir_exists(format!("{target_dir}/{dir_a}")));
237 assert!(at.dir_exists(format!("{target_dir}/{dir_b}")));
238 }
239
240 #[test]
241 fn test_mv_interactive() {
242 let scene = TestScenario::new(util_name!());
243 let at = &scene.fixtures;
244 let file_a = "test_mv_interactive_file_a";
245 let file_b = "test_mv_interactive_file_b";
246
247 at.touch(file_a);
248 at.touch(file_b);
249
250 scene
251 .ucmd()
252 .arg("-i")
253 .arg(file_a)
254 .arg(file_b)
255 .pipe_in("n")
256 .fails()
257 .no_stdout();
258
259 assert!(at.file_exists(file_a));
260 assert!(at.file_exists(file_b));
261
262 scene
263 .ucmd()
264 .arg("-i")
265 .arg(file_a)
266 .arg(file_b)
267 .pipe_in("Yesh") // spell-checker:disable-line
268 .succeeds()
269 .no_stdout();
270
271 assert!(!at.file_exists(file_a));
272 assert!(at.file_exists(file_b));
273 }
274
275 #[test]
276 fn test_mv_interactive_with_dir_as_target() {
277 let (at, mut ucmd) = at_and_ucmd!();
278
279 let file = "test_mv_interactive_file";
280 let target_dir = "target";
281
282 at.mkdir(target_dir);
283 at.touch(file);
284 at.touch(format!("{target_dir}/{file}"));
285
286 ucmd.arg(file)
287 .arg(target_dir)
288 .arg("-i")
289 .pipe_in("n")
290 .fails()
291 .stderr_does_not_contain("cannot move")
292 .no_stdout();
293 }
294
295 #[test]
296 fn test_mv_interactive_dir_to_file_not_affirmative() {
297 let (at, mut ucmd) = at_and_ucmd!();
298
299 let dir = "test_mv_interactive_dir_to_file_not_affirmative_dir";
300 let file = "test_mv_interactive_dir_to_file_not_affirmative_file";
301
302 at.mkdir(dir);
303 at.touch(file);
304
305 ucmd.arg(dir)
306 .arg(file)
307 .arg("-i")
308 .pipe_in("n")
309 .fails()
310 .no_stdout();
311
312 assert!(at.dir_exists(dir));
313 }
314
315 #[test]
316 fn test_mv_interactive_no_clobber_force_last_arg_wins() {
317 let scene = TestScenario::new(util_name!());
318 let at = &scene.fixtures;
319
320 let file_a = "a.txt";
321 let file_b = "b.txt";
322
323 at.touch(file_a);
324 at.touch(file_b);
325
326 scene
327 .ucmd()
328 .args(&[file_a, file_b, "-f", "-i", "-n", "--debug"])
329 .succeeds()
330 .stdout_contains("skipped 'b.txt'");
331
332 scene
333 .ucmd()
334 .args(&[file_a, file_b, "-n", "-f", "-i"])
335 .fails()
336 .stderr_only(format!("mv: overwrite '{file_b}'? "));
337
338 at.write(file_a, "aa");
339
340 scene
341 .ucmd()
342 .args(&[file_a, file_b, "-i", "-n", "-f"])
343 .succeeds()
344 .no_output();
345
346 assert!(!at.file_exists(file_a));
347 assert_eq!("aa", at.read(file_b));
348 }
349
350 #[test]
351 fn test_mv_arg_update_interactive() {
352 let (at, mut ucmd) = at_and_ucmd!();
353
354 let file_a = "test_mv_replace_file_a";
355 let file_b = "test_mv_replace_file_b";
356
357 at.touch(file_a);
358 at.touch(file_b);
359
360 ucmd.arg(file_a)
361 .arg(file_b)
362 .arg("-i")
363 .arg("--update")
364 .succeeds()
365 .no_output();
366 }
367
368 #[test]
369 fn test_mv_no_clobber() {
370 let (at, mut ucmd) = at_and_ucmd!();
371 let file_a = "test_mv_no_clobber_file_a";
372 let file_b = "test_mv_no_clobber_file_b";
373
374 at.touch(file_a);
375 at.touch(file_b);
376
377 ucmd.arg("-n")
378 .arg(file_a)
379 .arg(file_b)
380 .arg("--debug")
381 .succeeds()
382 .stdout_contains("skipped 'test_mv_no_clobber_file_b");
383
384 assert!(at.file_exists(file_a));
385 assert!(at.file_exists(file_b));
386 }
387
388 #[test]
389 fn test_mv_replace_file() {
390 let (at, mut ucmd) = at_and_ucmd!();
391 let file_a = "test_mv_replace_file_a";
392 let file_b = "test_mv_replace_file_b";
393
394 at.touch(file_a);
395 at.touch(file_b);
396
397 ucmd.arg(file_a).arg(file_b).succeeds().no_stderr();
398
399 assert!(!at.file_exists(file_a));
400 assert!(at.file_exists(file_b));
401 }
402
403 #[test]
404 #[cfg(all(unix, not(target_os = "android")))]
405 fn test_mv_replace_symlink_with_symlink() {
406 let (at, mut ucmd) = at_and_ucmd!();
407
408 at.mkdir("a");
409 at.mkdir("b");
410 at.touch("a/empty_file_a");
411 at.touch("b/empty_file_b");
412
413 at.symlink_dir("a", "symlink_a");
414 at.symlink_dir("b", "symlink_b");
415
416 assert_eq!(at.read("symlink_a/empty_file_a"), "");
417
418 ucmd.arg("-T")
419 .arg("symlink_b")
420 .arg("symlink_a")
421 .succeeds()
422 .no_stderr();
423
424 assert!(at.file_exists("symlink_a/empty_file_b"));
425 assert!(!at.file_exists("symlink_a/empty_file_a"));
426 assert!(!at.symlink_exists("symlink_b"));
427 }
428
429 #[test]
430 #[cfg(all(unix, not(target_os = "android")))]
431 fn test_mv_replace_symlink_with_directory() {
432 let (at, mut ucmd) = at_and_ucmd!();
433
434 at.touch("a");
435 at.mkdir("b");
436 at.touch("b/empty_file_b");
437
438 at.symlink_file("a", "symlink");
439
440 ucmd.arg("-T")
441 .arg("b")
442 .arg("symlink")
443 .fails()
444 .stderr_contains("cannot overwrite non-directory")
445 .stderr_contains("with directory");
446 }
447
448 #[test]
449 #[cfg(all(unix, not(target_os = "android")))]
450 fn test_mv_replace_symlink_with_file() {
451 let (at, mut ucmd) = at_and_ucmd!();
452
453 at.touch("a");
454 at.touch("b");
455
456 at.symlink_file("a", "symlink");
457
458 ucmd.arg("-T")
459 .arg("b")
460 .arg("symlink")
461 .succeeds()
462 .no_stderr();
463
464 assert!(at.file_exists("symlink"));
465 assert!(!at.is_symlink("symlink"));
466 assert!(!at.file_exists("b"));
467 assert!(at.file_exists("a"));
468 }
469
470 #[test]
471 #[cfg(all(unix, not(target_os = "android")))]
472 fn test_mv_file_to_broken_symlink_file() {
473 let (at, mut ucmd) = at_and_ucmd!();
474
475 at.touch("file");
476 at.symlink_file("missing-target", "broken");
477
478 ucmd.arg("file").arg("broken").succeeds().no_stderr();
479
480 assert!(at.file_exists("broken"));
481 assert!(!at.is_symlink("broken"));
482 assert!(!at.file_exists("file"));
483 }
484
485 #[test]
486 #[cfg(all(unix, not(target_os = "android")))]
487 fn test_mv_file_to_broken_symlink_directory() {
488 let (at, mut ucmd) = at_and_ucmd!();
489
490 at.touch("file");
491 at.symlink_dir("missing-target", "broken");
492
493 ucmd.arg("file").arg("broken").succeeds().no_stderr();
494
495 assert!(at.file_exists("broken"));
496 assert!(!at.is_symlink("broken"));
497 assert!(!at.file_exists("file"));
498 }
499
500 #[test]
501 #[cfg(all(unix, not(target_os = "android")))]
502 fn test_mv_file_to_symlink_directory() {
503 let (at, mut ucmd) = at_and_ucmd!();
504
505 at.mkdir("a");
506 at.touch("a/empty_file_a");
507 at.touch("b");
508
509 at.symlink_dir("a", "symlink");
510
511 assert!(at.file_exists("symlink/empty_file_a"));
512
513 ucmd.arg("b").arg("symlink").succeeds().no_stderr();
514
515 assert!(at.dir_exists("symlink"));
516 assert!(at.is_symlink("symlink"));
517 assert!(at.file_exists("symlink/b"));
518 assert!(!at.file_exists("b"));
519 assert!(at.dir_exists("a"));
520 assert!(at.file_exists("a/b"));
521 }
522
523 #[test]
524 fn test_mv_force_replace_file() {
525 let (at, mut ucmd) = at_and_ucmd!();
526 let file_a = "test_mv_force_replace_file_a";
527 let file_b = "test_mv_force_replace_file_b";
528
529 at.touch(file_a);
530 at.touch(file_b);
531
532 ucmd.arg("--force")
533 .arg(file_a)
534 .arg(file_b)
535 .succeeds()
536 .no_stderr();
537
538 assert!(!at.file_exists(file_a));
539 assert!(at.file_exists(file_b));
540 }
541
542 #[test]
543 fn test_mv_same_file() {
544 let (at, mut ucmd) = at_and_ucmd!();
545 let file_a = "test_mv_same_file_a";
546
547 at.touch(file_a);
548 ucmd.arg(file_a)
549 .arg(file_a)
550 .fails()
551 .stderr_only(format!("mv: '{file_a}' and '{file_a}' are the same file\n"));
552 }
553
554 #[test]
555 #[cfg(all(unix, not(target_os = "android")))]
556 fn test_mv_same_hardlink() {
557 let (at, mut ucmd) = at_and_ucmd!();
558 let file_a = "test_mv_same_file_a";
559 let file_b = "test_mv_same_file_b";
560 at.touch(file_a);
561
562 at.hard_link(file_a, file_b);
563
564 at.touch(file_a);
565 ucmd.arg(file_a)
566 .arg(file_b)
567 .fails()
568 .stderr_only(format!("mv: '{file_a}' and '{file_b}' are the same file\n"));
569 }
570
571 #[test]
572 #[cfg(all(unix, not(target_os = "android")))]
573 fn test_mv_dangling_symlink_to_folder() {
574 let (at, mut ucmd) = at_and_ucmd!();
575
576 at.symlink_file("404", "abc");
577 at.mkdir("x");
578
579 ucmd.arg("abc").arg("x").succeeds();
580
581 assert!(at.symlink_exists("x/abc"));
582 }
583
584 #[test]
585 #[cfg(all(unix, not(target_os = "android")))]
586 fn test_mv_same_symlink() {
587 let (at, mut ucmd) = at_and_ucmd!();
588 let file_a = "test_mv_same_file_a";
589 let file_b = "test_mv_same_file_b";
590 let file_c = "test_mv_same_file_c";
591
592 at.touch(file_a);
593
594 at.symlink_file(file_a, file_b);
595
596 ucmd.arg(file_b)
597 .arg(file_a)
598 .fails()
599 .stderr_only(format!("mv: '{file_b}' and '{file_a}' are the same file\n"));
600
601 let (at2, mut ucmd2) = at_and_ucmd!();
602 at2.touch(file_a);
603
604 at2.symlink_file(file_a, file_b);
605 ucmd2.arg(file_a).arg(file_b).succeeds();
606 assert!(at2.file_exists(file_b));
607 assert!(!at2.file_exists(file_a));
608
609 let (at3, mut ucmd3) = at_and_ucmd!();
610 at3.touch(file_a);
611
612 at3.symlink_file(file_a, file_b);
613 at3.symlink_file(file_b, file_c);
614
615 ucmd3.arg(file_c).arg(file_b).succeeds();
616 assert!(!at3.symlink_exists(file_c));
617 assert!(at3.symlink_exists(file_b));
618
619 let (at4, mut ucmd4) = at_and_ucmd!();
620 at4.touch(file_a);
621
622 at4.symlink_file(file_a, file_b);
623 at4.symlink_file(file_b, file_c);
624
625 ucmd4
626 .arg(file_c)
627 .arg(file_a)
628 .fails()
629 .stderr_only(format!("mv: '{file_c}' and '{file_a}' are the same file\n"));
630 }
631
632 #[test]
633 #[cfg(all(unix, not(target_os = "android")))]
634 fn test_mv_same_broken_symlink() {
635 let (at, mut ucmd) = at_and_ucmd!();
636
637 at.symlink_file("missing-target", "broken");
638
639 ucmd.arg("broken")
640 .arg("broken")
641 .fails()
642 .stderr_only("mv: 'broken' and 'broken' are the same file\n");
643 }
644
645 #[test]
646 #[cfg(all(unix, not(target_os = "android")))]
647 fn test_mv_symlink_into_target() {
648 let (at, mut ucmd) = at_and_ucmd!();
649
650 at.mkdir("dir");
651 at.symlink_file("dir", "dir-link");
652
653 ucmd.arg("dir-link").arg("dir").succeeds();
654 }
655
656 #[cfg(target_os = "linux")]
657 #[test]
658 fn test_mv_broken_symlink_to_another_fs() {
659 use tempfile::TempDir;
660
661 let scene = TestScenario::new(util_name!());
662
663 scene.fixtures.mkdir("foo");
664 scene.fixtures.symlink_file("missing", "foo/dangling");
665
666 let other_fs_tempdir =
667 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
668 let dest = other_fs_tempdir.path().join("foo");
669
670 scene.ucmd().arg("foo").arg(dest).succeeds().no_output();
671 }
672
673 #[test]
674 #[cfg(all(unix, not(target_os = "android")))]
675 fn test_mv_hardlink_to_symlink() {
676 let (at, mut ucmd) = at_and_ucmd!();
677 let file = "file";
678 let symlink_file = "symlink";
679 let hardlink_to_symlink_file = "hardlink_to_symlink";
680
681 at.touch(file);
682 at.symlink_file(file, symlink_file);
683 at.hard_link(symlink_file, hardlink_to_symlink_file);
684
685 ucmd.arg(symlink_file).arg(hardlink_to_symlink_file).fails();
686
687 let (at2, mut ucmd2) = at_and_ucmd!();
688
689 at2.touch(file);
690 at2.symlink_file(file, symlink_file);
691 at2.hard_link(symlink_file, hardlink_to_symlink_file);
692
693 ucmd2
694 .arg("--backup")
695 .arg(symlink_file)
696 .arg(hardlink_to_symlink_file)
697 .succeeds();
698 assert!(!at2.symlink_exists(symlink_file));
699 assert!(at2.symlink_exists(format!("{hardlink_to_symlink_file}~")));
700 }
701
702 #[test]
703 #[cfg(all(unix, not(target_os = "android")))]
704 fn test_mv_same_hardlink_backup_simple() {
705 let (at, mut ucmd) = at_and_ucmd!();
706 let file_a = "test_mv_same_file_a";
707 let file_b = "test_mv_same_file_b";
708 at.touch(file_a);
709
710 at.hard_link(file_a, file_b);
711
712 ucmd.arg(file_a)
713 .arg(file_b)
714 .arg("--backup=simple")
715 .succeeds();
716 }
717
718 #[test]
719 #[cfg(all(unix, not(target_os = "android")))]
720 fn test_mv_same_hardlink_backup_simple_destroy() {
721 let (at, mut ucmd) = at_and_ucmd!();
722 let file_a = "test_mv_same_file_a~";
723 let file_b = "test_mv_same_file_a";
724 at.touch(file_a);
725 at.touch(file_b);
726
727 ucmd.arg(file_a)
728 .arg(file_b)
729 .arg("--b=simple")
730 .fails()
731 .stderr_contains("backing up 'test_mv_same_file_a' might destroy source");
732 }
733
734 /// The guard must compare the files, not how the operands were spelled.
735 /// Comparing strings let `'a~'` versus `'./a'` slip through, and mv then
736 /// destroyed the source and exited 0 with no diagnostic.
737 #[test]
738 #[cfg(all(unix, not(target_os = "android")))]
739 fn test_mv_backup_simple_guard_ignores_spelling() {
740 for target in ["./test_mv_spell_a", "test_mv_spell_a"] {
741 let (at, mut ucmd) = at_and_ucmd!();
742 let source = "test_mv_spell_a~";
743 at.write(source, "SRCDATA");
744 at.write("test_mv_spell_a", "DSTDATA");
745
746 ucmd.arg(source)
747 .arg(target)
748 .arg("--backup=simple")
749 .fails()
750 .stderr_contains("might destroy source");
751
752 assert_eq!(
753 at.read(source),
754 "SRCDATA",
755 "mv destroyed the source when the target was spelled {target}"
756 );
757 }
758 }
759
760 /// ...but it must not fire for unrelated operands that merely look similar.
761 #[test]
762 #[cfg(all(unix, not(target_os = "android")))]
763 fn test_mv_backup_simple_guard_allows_unrelated_source() {
764 let (at, mut ucmd) = at_and_ucmd!();
765 at.write("test_mv_spell_src", "SRCDATA");
766 at.write("test_mv_spell_dst", "DSTDATA");
767
768 ucmd.arg("test_mv_spell_src")
769 .arg("test_mv_spell_dst")
770 .arg("--backup=simple")
771 .succeeds();
772
773 assert_eq!(at.read("test_mv_spell_dst"), "SRCDATA");
774 assert_eq!(at.read("test_mv_spell_dst~"), "DSTDATA");
775 }
776
777 /// A symlink source is a distinct file from the backup it points at, so the
778 /// backup rename cannot destroy it. GNU allows this.
779 #[test]
780 #[cfg(all(unix, not(target_os = "android")))]
781 fn test_mv_backup_simple_guard_allows_symlink_source() {
782 let (at, mut ucmd) = at_and_ucmd!();
783 at.write("test_mv_sym_a", "DSTDATA");
784 at.write("test_mv_sym_real", "REALDATA");
785 at.symlink_file("test_mv_sym_real", "test_mv_sym_a~");
786
787 ucmd.arg("test_mv_sym_a~")
788 .arg("test_mv_sym_a")
789 .arg("--backup=simple")
790 .succeeds();
791 }
792
793 /// A hard link under another name shares the backup's inode but keeps the data
794 /// alive after the rename, so the guard must not fire. GNU allows this.
795 #[test]
796 #[cfg(all(unix, not(target_os = "android")))]
797 fn test_mv_backup_simple_guard_allows_hardlink_source() {
798 let (at, mut ucmd) = at_and_ucmd!();
799 at.write("test_mv_hl_a", "DSTDATA");
800 at.write("test_mv_hl_a~", "SRCDATA");
801 at.hard_link("test_mv_hl_a~", "test_mv_hl_b");
802
803 ucmd.arg("test_mv_hl_b")
804 .arg("test_mv_hl_a")
805 .arg("--backup=simple")
806 .succeeds();
807
808 assert_eq!(at.read("test_mv_hl_a"), "SRCDATA");
809 assert_eq!(at.read("test_mv_hl_a~"), "DSTDATA");
810 }
811
812 #[test]
813 fn test_mv_same_file_not_dot_dir() {
814 let (at, mut ucmd) = at_and_ucmd!();
815 let dir = "test_mv_errors_dir";
816
817 at.mkdir(dir);
818 ucmd.arg(dir).arg(dir).fails().stderr_only(format!(
819 "mv: cannot move '{dir}' to a subdirectory of itself, '{dir}/{dir}'\n",
820 ));
821 }
822
823 #[test]
824 fn test_mv_same_file_dot_dir() {
825 let (_at, mut ucmd) = at_and_ucmd!();
826
827 ucmd.arg(".")
828 .arg(".")
829 .fails()
830 .stderr_only("mv: '.' and '.' are the same file\n");
831 }
832
833 #[test]
834 fn test_mv_simple_backup() {
835 let (at, mut ucmd) = at_and_ucmd!();
836 let file_a = "test_mv_simple_backup_file_a";
837 let file_b = "test_mv_simple_backup_file_b";
838
839 at.touch(file_a);
840 at.touch(file_b);
841 ucmd.arg("-b")
842 .arg(file_a)
843 .arg(file_b)
844 .succeeds()
845 .no_stderr();
846
847 assert!(!at.file_exists(file_a));
848 assert!(at.file_exists(file_b));
849 assert!(at.file_exists(format!("{file_b}~")));
850 }
851
852 #[test]
853 fn test_mv_simple_backup_for_directory() {
854 let (at, mut ucmd) = at_and_ucmd!();
855 let dir_a = "test_mv_simple_backup_dir_a";
856 let dir_b = "test_mv_simple_backup_dir_b";
857
858 at.mkdir(dir_a);
859 at.mkdir(dir_b);
860 at.touch(format!("{dir_a}/file_a"));
861 at.touch(format!("{dir_b}/file_b"));
862 ucmd.arg("-T")
863 .arg("-b")
864 .arg(dir_a)
865 .arg(dir_b)
866 .succeeds()
867 .no_stderr();
868
869 assert!(!at.dir_exists(dir_a));
870 assert!(at.dir_exists(dir_b));
871 assert!(at.dir_exists(format!("{dir_b}~")));
872 assert!(at.file_exists(format!("{dir_b}/file_a")));
873 assert!(at.file_exists(format!("{dir_b}~/file_b")));
874 }
875
876 #[test]
877 fn test_mv_simple_backup_with_file_extension() {
878 let (at, mut ucmd) = at_and_ucmd!();
879 let file_a = "test_mv_simple_backup_file_a.txt";
880 let file_b = "test_mv_simple_backup_file_b.txt";
881
882 at.touch(file_a);
883 at.touch(file_b);
884 ucmd.arg("-b")
885 .arg(file_a)
886 .arg(file_b)
887 .succeeds()
888 .no_stderr();
889
890 assert!(!at.file_exists(file_a));
891 assert!(at.file_exists(file_b));
892 assert!(at.file_exists(format!("{file_b}~")));
893 }
894
895 #[test]
896 fn test_mv_arg_backup_arg_first() {
897 let (at, mut ucmd) = at_and_ucmd!();
898 let file_a = "test_mv_simple_backup_file_a";
899 let file_b = "test_mv_simple_backup_file_b";
900
901 at.touch(file_a);
902 at.touch(file_b);
903 ucmd.arg("--backup").arg(file_a).arg(file_b).succeeds();
904
905 assert!(!at.file_exists(file_a));
906 assert!(at.file_exists(file_b));
907 assert!(at.file_exists(format!("{file_b}~")));
908 }
909
910 #[test]
911 fn test_mv_custom_backup_suffix() {
912 let (at, mut ucmd) = at_and_ucmd!();
913 let file_a = "test_mv_custom_backup_suffix_file_a";
914 let file_b = "test_mv_custom_backup_suffix_file_b";
915 let suffix = "super-suffix-of-the-century";
916
917 at.touch(file_a);
918 at.touch(file_b);
919 ucmd.arg("-b")
920 .arg(format!("--suffix={suffix}"))
921 .arg(file_a)
922 .arg(file_b)
923 .succeeds()
924 .no_stderr();
925
926 assert!(!at.file_exists(file_a));
927 assert!(at.file_exists(file_b));
928 assert!(at.file_exists(format!("{file_b}{suffix}")));
929 }
930
931 #[test]
932 fn test_suffix_without_backup_option() {
933 let (at, mut ucmd) = at_and_ucmd!();
934 let file_a = "test_mv_custom_backup_suffix_file_a";
935 let file_b = "test_mv_custom_backup_suffix_file_b";
936 let suffix = "super-suffix-of-the-century";
937
938 at.touch(file_a);
939 at.touch(file_b);
940 ucmd.arg(format!("--suffix={suffix}"))
941 .arg(file_a)
942 .arg(file_b)
943 .succeeds()
944 .no_stderr();
945
946 assert!(!at.file_exists(file_a));
947 assert!(at.file_exists(file_b));
948 assert!(at.file_exists(format!("{file_b}{suffix}")));
949 }
950
951 #[test]
952 fn test_mv_custom_backup_suffix_hyphen_value() {
953 let (at, mut ucmd) = at_and_ucmd!();
954 let file_a = "test_mv_custom_backup_suffix_file_a";
955 let file_b = "test_mv_custom_backup_suffix_file_b";
956 let suffix = "-v";
957
958 at.touch(file_a);
959 at.touch(file_b);
960 ucmd.arg("-b")
961 .arg(format!("--suffix={suffix}"))
962 .arg(file_a)
963 .arg(file_b)
964 .succeeds()
965 .no_stderr();
966
967 assert!(!at.file_exists(file_a));
968 assert!(at.file_exists(file_b));
969 assert!(at.file_exists(format!("{file_b}{suffix}")));
970 }
971
972 #[test]
973 fn test_mv_custom_backup_suffix_via_env() {
974 let (at, mut ucmd) = at_and_ucmd!();
975 let file_a = "test_mv_custom_backup_suffix_file_a";
976 let file_b = "test_mv_custom_backup_suffix_file_b";
977 let suffix = "super-suffix-of-the-century";
978 at.touch(file_a);
979 at.touch(file_b);
980 ucmd.arg("-b")
981 .env("SIMPLE_BACKUP_SUFFIX", suffix)
982 .arg(file_a)
983 .arg(file_b)
984 .succeeds()
985 .no_stderr();
986
987 assert!(!at.file_exists(file_a));
988 assert!(at.file_exists(file_b));
989 assert!(at.file_exists(format!("{file_b}{suffix}")));
990 }
991
992 #[test]
993 fn test_mv_backup_numbered_with_t() {
994 let (at, mut ucmd) = at_and_ucmd!();
995 let file_a = "test_mv_backup_numbering_file_a";
996 let file_b = "test_mv_backup_numbering_file_b";
997
998 at.touch(file_a);
999 at.touch(file_b);
1000 ucmd.arg("--backup=t")
1001 .arg(file_a)
1002 .arg(file_b)
1003 .succeeds()
1004 .no_stderr();
1005
1006 assert!(!at.file_exists(file_a));
1007 assert!(at.file_exists(file_b));
1008 assert!(at.file_exists(format!("{file_b}.~1~")));
1009 }
1010
1011 #[test]
1012 fn test_mv_backup_numbered() {
1013 let (at, mut ucmd) = at_and_ucmd!();
1014 let file_a = "test_mv_backup_numbering_file_a";
1015 let file_b = "test_mv_backup_numbering_file_b";
1016
1017 at.touch(file_a);
1018 at.touch(file_b);
1019 ucmd.arg("--backup=numbered")
1020 .arg(file_a)
1021 .arg(file_b)
1022 .succeeds()
1023 .no_stderr();
1024
1025 assert!(!at.file_exists(file_a));
1026 assert!(at.file_exists(file_b));
1027 assert!(at.file_exists(format!("{file_b}.~1~")));
1028 }
1029
1030 #[test]
1031 fn test_mv_backup_existing() {
1032 let (at, mut ucmd) = at_and_ucmd!();
1033 let file_a = "test_mv_backup_numbering_file_a";
1034 let file_b = "test_mv_backup_numbering_file_b";
1035
1036 at.touch(file_a);
1037 at.touch(file_b);
1038 ucmd.arg("--backup=existing")
1039 .arg(file_a)
1040 .arg(file_b)
1041 .succeeds()
1042 .no_stderr();
1043
1044 assert!(!at.file_exists(file_a));
1045 assert!(at.file_exists(file_b));
1046 assert!(at.file_exists(format!("{file_b}~")));
1047 }
1048
1049 #[test]
1050 fn test_mv_backup_nil() {
1051 let (at, mut ucmd) = at_and_ucmd!();
1052 let file_a = "test_mv_backup_numbering_file_a";
1053 let file_b = "test_mv_backup_numbering_file_b";
1054
1055 at.touch(file_a);
1056 at.touch(file_b);
1057 ucmd.arg("--backup=nil")
1058 .arg(file_a)
1059 .arg(file_b)
1060 .succeeds()
1061 .no_stderr();
1062
1063 assert!(!at.file_exists(file_a));
1064 assert!(at.file_exists(file_b));
1065 assert!(at.file_exists(format!("{file_b}~")));
1066 }
1067
1068 #[test]
1069 fn test_mv_numbered_if_existing_backup_existing() {
1070 let (at, mut ucmd) = at_and_ucmd!();
1071 let file_a = "test_mv_backup_numbering_file_a";
1072 let file_b = "test_mv_backup_numbering_file_b";
1073 let file_b_backup = "test_mv_backup_numbering_file_b.~1~";
1074
1075 at.touch(file_a);
1076 at.touch(file_b);
1077 at.touch(file_b_backup);
1078 ucmd.arg("--backup=existing")
1079 .arg(file_a)
1080 .arg(file_b)
1081 .succeeds()
1082 .no_stderr();
1083
1084 assert!(at.file_exists(file_b));
1085 assert!(at.file_exists(file_b_backup));
1086 assert!(at.file_exists(format!("{file_b}.~2~")));
1087 }
1088
1089 #[test]
1090 fn test_mv_numbered_if_existing_backup_nil() {
1091 let (at, mut ucmd) = at_and_ucmd!();
1092 let file_a = "test_mv_backup_numbering_file_a";
1093 let file_b = "test_mv_backup_numbering_file_b";
1094 let file_b_backup = "test_mv_backup_numbering_file_b.~1~";
1095
1096 at.touch(file_a);
1097 at.touch(file_b);
1098 at.touch(file_b_backup);
1099 ucmd.arg("--backup=nil")
1100 .arg(file_a)
1101 .arg(file_b)
1102 .succeeds()
1103 .no_stderr();
1104
1105 assert!(at.file_exists(file_b));
1106 assert!(at.file_exists(file_b_backup));
1107 assert!(at.file_exists(format!("{file_b}.~2~")));
1108 }
1109
1110 #[test]
1111 fn test_mv_backup_simple() {
1112 let (at, mut ucmd) = at_and_ucmd!();
1113 let file_a = "test_mv_backup_numbering_file_a";
1114 let file_b = "test_mv_backup_numbering_file_b";
1115
1116 at.touch(file_a);
1117 at.touch(file_b);
1118 ucmd.arg("--backup=simple")
1119 .arg(file_a)
1120 .arg(file_b)
1121 .succeeds()
1122 .no_stderr();
1123
1124 assert!(!at.file_exists(file_a));
1125 assert!(at.file_exists(file_b));
1126 assert!(at.file_exists(format!("{file_b}~")));
1127 }
1128
1129 #[test]
1130 fn test_mv_backup_never() {
1131 let (at, mut ucmd) = at_and_ucmd!();
1132 let file_a = "test_mv_backup_numbering_file_a";
1133 let file_b = "test_mv_backup_numbering_file_b";
1134
1135 at.touch(file_a);
1136 at.touch(file_b);
1137 ucmd.arg("--backup=never")
1138 .arg(file_a)
1139 .arg(file_b)
1140 .succeeds()
1141 .no_stderr();
1142
1143 assert!(!at.file_exists(file_a));
1144 assert!(at.file_exists(file_b));
1145 assert!(at.file_exists(format!("{file_b}~")));
1146 }
1147
1148 #[test]
1149 fn test_mv_backup_none() {
1150 let (at, mut ucmd) = at_and_ucmd!();
1151 let file_a = "test_mv_backup_numbering_file_a";
1152 let file_b = "test_mv_backup_numbering_file_b";
1153
1154 at.touch(file_a);
1155 at.touch(file_b);
1156 ucmd.arg("--backup=none")
1157 .arg(file_a)
1158 .arg(file_b)
1159 .succeeds()
1160 .no_stderr();
1161
1162 assert!(!at.file_exists(file_a));
1163 assert!(at.file_exists(file_b));
1164 assert!(!at.file_exists(format!("{file_b}~")));
1165 }
1166
1167 #[test]
1168 fn test_mv_backup_off() {
1169 let (at, mut ucmd) = at_and_ucmd!();
1170 let file_a = "test_mv_backup_numbering_file_a";
1171 let file_b = "test_mv_backup_numbering_file_b";
1172
1173 at.touch(file_a);
1174 at.touch(file_b);
1175 ucmd.arg("--backup=off")
1176 .arg(file_a)
1177 .arg(file_b)
1178 .succeeds()
1179 .no_stderr();
1180
1181 assert!(!at.file_exists(file_a));
1182 assert!(at.file_exists(file_b));
1183 assert!(!at.file_exists(format!("{file_b}~")));
1184 }
1185
1186 #[test]
1187 fn test_mv_backup_conflicting_options() {
1188 for conflicting_opt in ["--no-clobber", "--update=none-fail", "--update=none"] {
1189 new_ucmd!()
1190 .arg("--backup")
1191 .arg(conflicting_opt)
1192 .arg("file1")
1193 .arg("file2")
1194 .fails()
1195 .usage_error("cannot combine --backup with -n/--no-clobber or --update=none-fail");
1196 }
1197 }
1198
1199 #[test]
1200 fn test_mv_update_option() {
1201 use std::fs::{File, FileTimes};
1202 let scene = TestScenario::new(util_name!());
1203 let at = &scene.fixtures;
1204 let file_a = "test_mv_update_option_file_a";
1205 let file_b = "test_mv_update_option_file_b";
1206
1207 at.touch(file_a);
1208 at.touch(file_b);
1209 let ts = time::OffsetDateTime::now_utc();
1210 let now = ts.into();
1211 let later = (ts + time::Duration::seconds(3600)).into();
1212 let times_now = FileTimes::new().set_accessed(now).set_modified(now);
1213 let times_later = FileTimes::new().set_accessed(now).set_modified(later);
1214 File::options()
1215 .write(true)
1216 .open(at.plus_as_string(file_a))
1217 .unwrap()
1218 .set_times(times_now)
1219 .unwrap();
1220 File::options()
1221 .write(true)
1222 .open(at.plus_as_string(file_b))
1223 .unwrap()
1224 .set_times(times_later)
1225 .unwrap();
1226
1227 scene
1228 .ucmd()
1229 .arg("--update")
1230 .arg(file_a)
1231 .arg(file_b)
1232 .succeeds();
1233
1234 assert!(at.file_exists(file_a));
1235 assert!(at.file_exists(file_b));
1236
1237 scene
1238 .ucmd()
1239 .arg("--update")
1240 .arg(file_b)
1241 .arg(file_a)
1242 .succeeds()
1243 .no_stderr();
1244
1245 assert!(at.file_exists(file_a));
1246 assert!(!at.file_exists(file_b));
1247 }
1248
1249 #[test]
1250 fn test_mv_update_with_dest_ending_with_slash() {
1251 let (at, mut ucmd) = at_and_ucmd!();
1252 let source = "source";
1253 let dest = "destination/";
1254
1255 at.mkdir("source");
1256
1257 ucmd.arg("--update").arg(source).arg(dest).succeeds();
1258
1259 assert!(!at.dir_exists(source));
1260 assert!(at.dir_exists(dest));
1261 }
1262
1263 #[test]
1264 fn test_mv_arg_update_none() {
1265 let (at, mut ucmd) = at_and_ucmd!();
1266
1267 let file1 = "test_mv_arg_update_none_file1";
1268 let file2 = "test_mv_arg_update_none_file2";
1269 let file1_content = "file1 content\n";
1270 let file2_content = "file2 content\n";
1271
1272 at.write(file1, file1_content);
1273 at.write(file2, file2_content);
1274
1275 ucmd.arg(file1)
1276 .arg(file2)
1277 .arg("--update=none")
1278 .succeeds()
1279 .no_output();
1280
1281 assert_eq!(at.read(file2), file2_content);
1282 }
1283
1284 #[test]
1285 fn test_mv_arg_update_all() {
1286 let (at, mut ucmd) = at_and_ucmd!();
1287
1288 let file1 = "test_mv_arg_update_none_file1";
1289 let file2 = "test_mv_arg_update_none_file2";
1290 let file1_content = "file1 content\n";
1291 let file2_content = "file2 content\n";
1292
1293 at.write(file1, file1_content);
1294 at.write(file2, file2_content);
1295
1296 ucmd.arg(file1)
1297 .arg(file2)
1298 .arg("--update=all")
1299 .succeeds()
1300 .no_output();
1301
1302 assert_eq!(at.read(file2), file1_content);
1303 }
1304
1305 #[test]
1306 fn test_mv_arg_update_older_dest_not_older() {
1307 let (at, mut ucmd) = at_and_ucmd!();
1308
1309 let old = "test_mv_arg_update_none_file1";
1310 let new = "test_mv_arg_update_none_file2";
1311 let old_content = "file1 content\n";
1312 let new_content = "file2 content\n";
1313
1314 let mut f = at.make_file(old);
1315 f.write_all(old_content.as_bytes()).unwrap();
1316 f.set_modified(std::time::UNIX_EPOCH).unwrap();
1317
1318 at.write(new, new_content);
1319
1320 ucmd.arg(old)
1321 .arg(new)
1322 .arg("--update=older")
1323 .succeeds()
1324 .no_output();
1325
1326 assert_eq!(at.read(new), new_content);
1327 }
1328
1329 #[test]
1330 fn test_mv_arg_update_none_then_all() {
1331 // take last if multiple update args are supplied,
1332 // update=all wins in this case
1333 let (at, mut ucmd) = at_and_ucmd!();
1334
1335 let old = "test_mv_arg_update_none_then_all_file1";
1336 let new = "test_mv_arg_update_none_then_all_file2";
1337 let old_content = "old content\n";
1338 let new_content = "new content\n";
1339
1340 let mut f = at.make_file(old);
1341 f.write_all(old_content.as_bytes()).unwrap();
1342 f.set_modified(std::time::UNIX_EPOCH).unwrap();
1343
1344 at.write(new, new_content);
1345
1346 ucmd.arg(old)
1347 .arg(new)
1348 .arg("--update=none")
1349 .arg("--update=all")
1350 .succeeds()
1351 .no_output();
1352
1353 assert_eq!(at.read(new), "old content\n");
1354 }
1355
1356 #[test]
1357 fn test_mv_arg_update_all_then_none() {
1358 // take last if multiple update args are supplied,
1359 // update=none wins in this case
1360 let (at, mut ucmd) = at_and_ucmd!();
1361
1362 let old = "test_mv_arg_update_all_then_none_file1";
1363 let new = "test_mv_arg_update_all_then_none_file2";
1364 let old_content = "old content\n";
1365 let new_content = "new content\n";
1366
1367 let mut f = at.make_file(old);
1368 f.write_all(old_content.as_bytes()).unwrap();
1369 f.set_modified(std::time::UNIX_EPOCH).unwrap();
1370
1371 at.write(new, new_content);
1372
1373 ucmd.arg(old)
1374 .arg(new)
1375 .arg("--update=all")
1376 .arg("--update=none")
1377 .succeeds()
1378 .no_output();
1379
1380 assert_eq!(at.read(new), "new content\n");
1381 }
1382
1383 #[test]
1384 fn test_mv_arg_update_older_dest_older() {
1385 let (at, mut ucmd) = at_and_ucmd!();
1386
1387 let old = "test_mv_arg_update_none_file1";
1388 let new = "test_mv_arg_update_none_file2";
1389 let old_content = "file1 content\n";
1390 let new_content = "file2 content\n";
1391
1392 let mut f = at.make_file(old);
1393 f.write_all(old_content.as_bytes()).unwrap();
1394 f.set_modified(std::time::UNIX_EPOCH).unwrap();
1395
1396 at.write(new, new_content);
1397
1398 ucmd.arg(new)
1399 .arg(old)
1400 .arg("--update=all")
1401 .succeeds()
1402 .no_output();
1403
1404 assert_eq!(at.read(old), new_content);
1405 }
1406
1407 #[test]
1408 fn test_mv_arg_update_older_dest_older_interactive() {
1409 let (at, mut ucmd) = at_and_ucmd!();
1410
1411 let old = "old";
1412 let new = "new";
1413 let old_content = "file1 content\n";
1414 let new_content = "file2 content\n";
1415
1416 let mut f = at.make_file(old);
1417 f.write_all(old_content.as_bytes()).unwrap();
1418 f.set_modified(std::time::UNIX_EPOCH).unwrap();
1419
1420 at.write(new, new_content);
1421
1422 ucmd.arg(new)
1423 .arg(old)
1424 .arg("--interactive")
1425 .arg("--update=older")
1426 .fails()
1427 .stderr_contains("overwrite 'old'?")
1428 .no_stdout();
1429 }
1430
1431 #[test]
1432 fn test_mv_arg_update_short_overwrite() {
1433 // same as --update=older
1434 let (at, mut ucmd) = at_and_ucmd!();
1435
1436 let old = "test_mv_arg_update_none_file1";
1437 let new = "test_mv_arg_update_none_file2";
1438 let old_content = "file1 content\n";
1439 let new_content = "file2 content\n";
1440
1441 let mut f = at.make_file(old);
1442 f.write_all(old_content.as_bytes()).unwrap();
1443 f.set_modified(std::time::UNIX_EPOCH).unwrap();
1444
1445 at.write(new, new_content);
1446
1447 ucmd.arg(new).arg(old).arg("-u").succeeds().no_output();
1448
1449 assert_eq!(at.read(old), new_content);
1450 }
1451
1452 #[test]
1453 fn test_mv_arg_update_short_no_overwrite() {
1454 // same as --update=older
1455 let (at, mut ucmd) = at_and_ucmd!();
1456
1457 let old = "test_mv_arg_update_none_file1";
1458 let new = "test_mv_arg_update_none_file2";
1459 let old_content = "file1 content\n";
1460 let new_content = "file2 content\n";
1461
1462 let mut f = at.make_file(old);
1463 f.write_all(old_content.as_bytes()).unwrap();
1464 f.set_modified(std::time::UNIX_EPOCH).unwrap();
1465
1466 at.write(new, new_content);
1467
1468 ucmd.arg(old).arg(new).arg("-u").succeeds().no_output();
1469
1470 assert_eq!(at.read(new), new_content);
1471 }
1472
1473 #[test]
1474 fn test_mv_target_dir() {
1475 let (at, mut ucmd) = at_and_ucmd!();
1476 let dir = "test_mv_target_dir_dir";
1477 let file_a = "test_mv_target_dir_file_a";
1478 let file_b = "test_mv_target_dir_file_b";
1479
1480 at.touch(file_a);
1481 at.touch(file_b);
1482 at.mkdir(dir);
1483 ucmd.arg("-t")
1484 .arg(dir)
1485 .arg(file_a)
1486 .arg(file_b)
1487 .succeeds()
1488 .no_stderr();
1489
1490 assert!(!at.file_exists(file_a));
1491 assert!(!at.file_exists(file_b));
1492 assert!(at.file_exists(format!("{dir}/{file_a}")));
1493 assert!(at.file_exists(format!("{dir}/{file_b}")));
1494 }
1495
1496 #[test]
1497 fn test_mv_target_dir_single_source() {
1498 let (at, mut ucmd) = at_and_ucmd!();
1499 let dir = "test_mv_target_dir_single_source_dir";
1500 let file = "test_mv_target_dir_single_source_file";
1501
1502 at.touch(file);
1503 at.mkdir(dir);
1504 ucmd.arg("-t").arg(dir).arg(file).succeeds().no_stderr();
1505
1506 assert!(!at.file_exists(file));
1507 assert!(at.file_exists(format!("{dir}/{file}")));
1508 }
1509
1510 #[test]
1511 fn test_mv_overwrite_dir() {
1512 let (at, mut ucmd) = at_and_ucmd!();
1513 let dir_a = "test_mv_overwrite_dir_a";
1514 let dir_b = "test_mv_overwrite_dir_b";
1515
1516 at.mkdir(dir_a);
1517 at.mkdir(dir_b);
1518 ucmd.arg("-T").arg(dir_a).arg(dir_b).succeeds().no_stderr();
1519
1520 assert!(!at.dir_exists(dir_a));
1521 assert!(at.dir_exists(dir_b));
1522 }
1523
1524 #[test]
1525 fn test_mv_no_target_dir_with_dest_not_existing() {
1526 let (at, mut ucmd) = at_and_ucmd!();
1527 let dir_a = "a";
1528 let dir_b = "b";
1529
1530 at.mkdir(dir_a);
1531 ucmd.arg("-T").arg(dir_a).arg(dir_b).succeeds().no_output();
1532
1533 assert!(!at.dir_exists(dir_a));
1534 assert!(at.dir_exists(dir_b));
1535 }
1536
1537 #[test]
1538 fn test_mv_no_target_dir_with_dest_not_existing_and_ending_with_slash() {
1539 let (at, mut ucmd) = at_and_ucmd!();
1540 let dir_a = "a";
1541 let dir_b = "b/";
1542
1543 at.mkdir(dir_a);
1544 ucmd.arg("-T").arg(dir_a).arg(dir_b).succeeds().no_output();
1545
1546 assert!(!at.dir_exists(dir_a));
1547 assert!(at.dir_exists(dir_b));
1548 }
1549
1550 #[test]
1551 fn test_mv_overwrite_nonempty_dir() {
1552 let (at, mut ucmd) = at_and_ucmd!();
1553 let dir_a = "test_mv_overwrite_nonempty_dir_a";
1554 let dir_b = "test_mv_overwrite_nonempty_dir_b";
1555 let dummy = "test_mv_overwrite_nonempty_dir_b/file";
1556
1557 at.mkdir(dir_a);
1558 at.mkdir(dir_b);
1559 at.touch(dummy);
1560 // Verbose output for the move should not be shown on failure
1561 ucmd.arg("-vT")
1562 .arg(dir_a)
1563 .arg(dir_b)
1564 .fails()
1565 .stderr_contains("cannot overwrite");
1566
1567 assert!(at.dir_exists(dir_a));
1568 assert!(at.dir_exists(dir_b));
1569 }
1570
1571 #[test]
1572 fn test_mv_overwrite_nonempty_dir_into_dir() {
1573 let (at, mut ucmd) = at_and_ucmd!();
1574 let dir_a = "test_mv_overwrite_nonempty_dir_into_dir_a";
1575 let dir_b = "test_mv_overwrite_nonempty_dir_into_dir_b";
1576 let target_dir = format!("{dir_b}/{dir_a}");
1577 let dummy = format!("{target_dir}/file");
1578
1579 at.mkdir(dir_a);
1580 at.mkdir(dir_b);
1581 at.mkdir(&target_dir);
1582 at.touch(&dummy);
1583
1584 ucmd.arg(dir_a)
1585 .arg(dir_b)
1586 .fails()
1587 .stderr_contains("cannot overwrite");
1588
1589 assert!(at.dir_exists(dir_a));
1590 assert!(at.dir_exists(dir_b));
1591 }
1592
1593 #[test]
1594 fn test_mv_backup_dir() {
1595 let (at, mut ucmd) = at_and_ucmd!();
1596 let dir_a = "test_mv_backup_dir_dir_a";
1597 let dir_b = "test_mv_backup_dir_dir_b";
1598
1599 at.mkdir(dir_a);
1600 at.mkdir(dir_b);
1601 ucmd.arg("-vbT")
1602 .arg(dir_a)
1603 .arg(dir_b)
1604 .succeeds()
1605 .stdout_only(format!(
1606 "renamed '{dir_a}' -> '{dir_b}' (backup: '{dir_b}~')\n"
1607 ));
1608
1609 assert!(!at.dir_exists(dir_a));
1610 assert!(at.dir_exists(dir_b));
1611 assert!(at.dir_exists(format!("{dir_b}~")));
1612 }
1613
1614 #[test]
1615 fn test_mv_errors() {
1616 let scene = TestScenario::new(util_name!());
1617 let at = &scene.fixtures;
1618 let dir = "test_mv_errors_dir";
1619 let file_a = "test_mv_errors_file_a";
1620 let file_b = "test_mv_errors_file_b";
1621 at.mkdir(dir);
1622 at.touch(file_a);
1623 at.touch(file_b);
1624
1625 // $ mv -T -t a b
1626 scene
1627 .ucmd()
1628 .arg("-T")
1629 .arg("-t")
1630 .arg(dir)
1631 .arg(file_a)
1632 .arg(file_b)
1633 .fails()
1634 .stderr_contains("cannot be used with");
1635
1636 // $ at.touch file && at.mkdir dir
1637 // $ mv -T file dir
1638 scene
1639 .ucmd()
1640 .arg("-T")
1641 .arg(file_a)
1642 .arg(dir)
1643 .fails()
1644 .stderr_only(format!(
1645 "mv: cannot overwrite directory '{dir}' with non-directory\n"
1646 ));
1647
1648 // $ at.mkdir dir && at.touch file
1649 // $ mv dir file
1650 scene
1651 .ucmd()
1652 .arg(dir)
1653 .arg(file_a)
1654 .fails()
1655 .stderr_only(format!(
1656 "mv: cannot overwrite non-directory '{file_a}' with directory '{dir}'\n"
1657 ));
1658 }
1659
1660 #[test]
1661 fn test_mv_verbose() {
1662 let scene = TestScenario::new(util_name!());
1663 let at = &scene.fixtures;
1664 let dir = "test_mv_verbose_dir";
1665 let file_a = "test_mv_verbose_file_a";
1666 let file_b = "test_mv_verbose_file_b";
1667 at.mkdir(dir);
1668 at.touch(file_a);
1669 at.touch(file_b);
1670
1671 scene
1672 .ucmd()
1673 .arg("-v")
1674 .arg(file_a)
1675 .arg(file_b)
1676 .succeeds()
1677 .stdout_only(format!("renamed '{file_a}' -> '{file_b}'\n"));
1678
1679 at.touch(file_a);
1680 scene
1681 .ucmd()
1682 .arg("-vb")
1683 .arg(file_a)
1684 .arg(file_b)
1685 .succeeds()
1686 .stdout_only(format!(
1687 "renamed '{file_a}' -> '{file_b}' (backup: '{file_b}~')\n"
1688 ));
1689 }
1690
1691 #[test]
1692 #[cfg(any(target_os = "linux", target_os = "android"))] // mkdir does not support -m on windows. Freebsd doesn't return a permission error either.
1693 #[cfg(feature = "mkdir")]
1694 fn test_mv_permission_error() {
1695 let scene = TestScenario::new("mkdir");
1696 let folder1 = "bar";
1697 let folder2 = "foo";
1698 let folder_to_move = "bar/foo";
1699 scene.ucmd().arg("-m444").arg(folder1).succeeds();
1700 scene.ucmd().arg("-m777").arg(folder2).succeeds();
1701
1702 scene
1703 .ccmd("mv")
1704 .arg(folder2)
1705 .arg(folder_to_move)
1706 .fails()
1707 .stderr_contains("Permission denied");
1708 }
1709
1710 #[test]
1711 fn test_mv_interactive_error() {
1712 let scene = TestScenario::new(util_name!());
1713 let at = &scene.fixtures;
1714 let dir = "test_mv_errors_dir";
1715 let file_a = "test_mv_errors_file_a";
1716 at.mkdir(dir);
1717 at.touch(file_a);
1718
1719 // $ at.mkdir dir && at.touch file
1720 // $ mv -i dir file
1721 // err == mv: cannot overwrite non-directory 'file' with directory 'dir'
1722 assert!(
1723 !scene
1724 .ucmd()
1725 .arg("-i")
1726 .arg(dir)
1727 .arg(file_a)
1728 .pipe_in("y")
1729 .fails()
1730 .stderr_str()
1731 .is_empty()
1732 );
1733 }
1734
1735 #[test]
1736 fn test_mv_arg_interactive_skipped() {
1737 let (at, mut ucmd) = at_and_ucmd!();
1738 at.touch("a");
1739 at.touch("b");
1740 ucmd.args(&["-vi", "a", "b"])
1741 .pipe_in("N\n")
1742 .ignore_stdin_write_error()
1743 .fails()
1744 .stderr_only("mv: overwrite 'b'? ");
1745 }
1746
1747 #[test]
1748 fn test_mv_arg_interactive_skipped_vin() {
1749 let (at, mut ucmd) = at_and_ucmd!();
1750 at.touch("a");
1751 at.touch("b");
1752 ucmd.args(&["-vin", "a", "b", "--debug"])
1753 .succeeds()
1754 .stdout_contains("skipped 'b'");
1755 }
1756
1757 #[test]
1758 fn test_mv_into_self_data() {
1759 let scene = TestScenario::new(util_name!());
1760
1761 let at = &scene.fixtures;
1762 let sub_dir = "sub_folder";
1763 let file1 = "t1.test";
1764 let file2 = "sub_folder/t2.test";
1765
1766 let file1_result_location = "sub_folder/t1.test";
1767
1768 at.mkdir(sub_dir);
1769 at.touch(file1);
1770 at.touch(file2);
1771
1772 scene
1773 .ucmd()
1774 .arg(file1)
1775 .arg(sub_dir)
1776 .arg(sub_dir)
1777 .fails_with_code(1);
1778
1779 // sub_dir exists, file1 has been moved, file2 still exists.
1780 assert!(at.dir_exists(sub_dir));
1781 assert!(at.file_exists(file1_result_location));
1782 assert!(at.file_exists(file2));
1783 assert!(!at.file_exists(file1));
1784 }
1785
1786 #[rstest]
1787 #[case(vec!["mydir"], vec!["mydir", "mydir"], "mv: cannot move 'mydir' to a subdirectory of itself, 'mydir/mydir'")]
1788 #[case(vec!["mydir"], vec!["mydir/", "mydir/"], "mv: cannot move 'mydir/' to a subdirectory of itself, 'mydir/mydir'")]
1789 #[case(vec!["mydir"], vec!["./mydir", "mydir", "mydir/"], "mv: cannot move './mydir' to a subdirectory of itself, 'mydir/mydir'")]
1790 #[case(vec!["mydir"], vec!["mydir/", "mydir/mydir_2/"], "mv: cannot move 'mydir/' to a subdirectory of itself, 'mydir/mydir_2/'")]
1791 #[case(vec!["mydir/mydir_2"], vec!["mydir", "mydir/mydir_2"], "mv: cannot move 'mydir' to a subdirectory of itself, 'mydir/mydir_2/mydir'\n")]
1792 #[case(vec!["mydir/mydir_2"], vec!["mydir/", "mydir/mydir_2/"], "mv: cannot move 'mydir/' to a subdirectory of itself, 'mydir/mydir_2/mydir'\n")]
1793 #[case(vec!["mydir", "mydir_2"], vec!["mydir/", "mydir_2/", "mydir_2/"], "mv: cannot move 'mydir_2/' to a subdirectory of itself, 'mydir_2/mydir_2'")]
1794 #[case(vec!["mydir"], vec!["mydir/", "mydir"], "mv: cannot move 'mydir/' to a subdirectory of itself, 'mydir/mydir'")]
1795 #[case(vec!["mydir"], vec!["-T", "mydir", "mydir"], "mv: 'mydir' and 'mydir' are the same file")]
1796 #[case(vec!["mydir"], vec!["mydir/", "mydir/../"], "mv: 'mydir/' and 'mydir/../mydir' are the same file")]
1797 fn test_mv_directory_self(
1798 #[case] dirs: Vec<&str>,
1799 #[case] args: Vec<&str>,
1800 #[case] expected_error: &str,
1801 ) {
1802 let scene = TestScenario::new(util_name!());
1803 let at = &scene.fixtures;
1804 for dir in dirs {
1805 at.mkdir_all(dir);
1806 }
1807 scene
1808 .ucmd()
1809 .args(&args)
1810 .fails()
1811 .stderr_contains(expected_error);
1812 }
1813
1814 #[test]
1815 fn test_mv_dir_into_dir_with_source_name_a_prefix_of_target_name() {
1816 let (at, mut ucmd) = at_and_ucmd!();
1817 let source = "test";
1818 let target = "test2";
1819
1820 at.mkdir(source);
1821 at.mkdir(target);
1822
1823 ucmd.arg(source).arg(target).succeeds().no_output();
1824
1825 assert!(at.dir_exists(format!("{target}/{source}")));
1826 }
1827
1828 #[test]
1829 fn test_mv_file_into_dir_where_both_are_files() {
1830 let scene = TestScenario::new(util_name!());
1831 let at = &scene.fixtures;
1832 at.touch("a");
1833 at.touch("b");
1834 scene
1835 .ucmd()
1836 .arg("a")
1837 .arg("b/")
1838 .fails()
1839 .stderr_contains("mv: failed to access 'b/': Not a directory");
1840 }
1841
1842 #[test]
1843 fn test_mv_seen_file() {
1844 let ts = TestScenario::new(util_name!());
1845 let at = &ts.fixtures;
1846
1847 at.mkdir("a");
1848 at.mkdir("b");
1849 at.mkdir("c");
1850 at.write("a/f", "a");
1851 at.write("b/f", "b");
1852
1853 let result = ts.ucmd().arg("a/f").arg("b/f").arg("c").fails();
1854
1855 #[cfg(not(unix))]
1856 assert!(
1857 result
1858 .stderr_str()
1859 .contains("will not overwrite just-created 'c\\f' with 'b/f'")
1860 );
1861 #[cfg(unix)]
1862 assert!(
1863 result
1864 .stderr_str()
1865 .contains("will not overwrite just-created 'c/f' with 'b/f'")
1866 );
1867
1868 // a/f has been moved into c/f
1869 assert!(at.plus("c").join("f").exists());
1870 // b/f still exists
1871 assert!(at.plus("b").join("f").exists());
1872 // a/f no longer exists
1873 assert!(!at.plus("a").join("f").exists());
1874 }
1875
1876 #[test]
1877 fn test_mv_seen_multiple_files_to_directory() {
1878 let ts = TestScenario::new(util_name!());
1879 let at = &ts.fixtures;
1880
1881 at.mkdir("a");
1882 at.mkdir("b");
1883 at.mkdir("c");
1884 at.write("a/f", "a");
1885 at.write("b/f", "b");
1886 at.write("b/g", "g");
1887
1888 let result = ts.ucmd().arg("a/f").arg("b/f").arg("b/g").arg("c").fails();
1889 #[cfg(not(unix))]
1890 assert!(
1891 result
1892 .stderr_str()
1893 .contains("will not overwrite just-created 'c\\f' with 'b/f'")
1894 );
1895 #[cfg(unix)]
1896 assert!(
1897 result
1898 .stderr_str()
1899 .contains("will not overwrite just-created 'c/f' with 'b/f'")
1900 );
1901
1902 assert!(!at.plus("a").join("f").exists());
1903 assert!(at.plus("b").join("f").exists());
1904 assert!(!at.plus("b").join("g").exists());
1905 assert!(at.plus("c").join("f").exists());
1906 assert!(at.plus("c").join("g").exists());
1907 }
1908
1909 #[test]
1910 fn test_mv_dir_into_file_where_both_are_files() {
1911 let scene = TestScenario::new(util_name!());
1912 let at = &scene.fixtures;
1913 at.touch("a");
1914 at.touch("b");
1915 scene
1916 .ucmd()
1917 .arg("a/")
1918 .arg("b")
1919 .fails()
1920 .stderr_contains("mv: cannot stat 'a/': Not a directory");
1921 }
1922
1923 #[test]
1924 fn test_mv_dir_into_path_slash() {
1925 let scene = TestScenario::new(util_name!());
1926 let at = &scene.fixtures;
1927 at.mkdir("a");
1928 scene.ucmd().arg("a").arg("e/").succeeds();
1929 assert!(at.dir_exists("e"));
1930 at.mkdir("b");
1931 at.mkdir("f");
1932 scene.ucmd().arg("b").arg("f/").succeeds();
1933 assert!(at.dir_exists("f/b"));
1934 }
1935
1936 #[cfg(all(unix, not(any(target_vendor = "apple", target_os = "openbsd"))))]
1937 #[test]
1938 fn test_acl() {
1939 use std::process::Command;
1940
1941 use uutests::util::compare_xattrs;
1942
1943 let scene = TestScenario::new(util_name!());
1944 let at = &scene.fixtures;
1945 let path1 = "a";
1946 let path2 = "b";
1947 let file = "a/file";
1948 let file_target = "b/file";
1949 at.mkdir(path1);
1950 at.mkdir(path2);
1951 at.touch(file);
1952
1953 let path = at.plus_as_string(file);
1954 // calling the command directly. xattr requires some dev packages to be installed
1955 // and it adds a complex dependency just for a test
1956 match Command::new("setfacl")
1957 .args(["-m", "group::rwx", path1])
1958 .status()
1959 .map(|status| status.code())
1960 {
1961 Ok(Some(0)) => {}
1962 Ok(_) => {
1963 println!("test skipped: setfacl failed");
1964 return;
1965 }
1966 Err(e) => {
1967 println!("test skipped: setfacl failed with {e}");
1968 return;
1969 }
1970 }
1971
1972 scene.ucmd().arg(&path).arg(path2).succeeds();
1973
1974 assert!(compare_xattrs(&file, &file_target));
1975 }
1976
1977 #[test]
1978 #[cfg(windows)]
1979 fn test_move_should_not_fallback_to_copy() {
1980 use std::os::windows::fs::OpenOptionsExt;
1981
1982 let (at, mut ucmd) = at_and_ucmd!();
1983
1984 let locked_file = "a_file_is_locked";
1985 let locked_file_path = at.plus(locked_file);
1986 let file = std::fs::OpenOptions::new()
1987 .create(true)
1988 .write(true)
1989 .share_mode(
1990 uucore::windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ
1991 | uucore::windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE,
1992 )
1993 .open(locked_file_path);
1994
1995 let target_file = "target_file";
1996 ucmd.arg(locked_file).arg(target_file).fails();
1997
1998 assert!(at.file_exists(locked_file));
1999 assert!(!at.file_exists(target_file));
2000
2001 drop(file);
2002 }
2003
2004 #[test]
2005 #[cfg(unix)]
2006 fn test_move_should_not_fallback_to_copy() {
2007 let (at, mut ucmd) = at_and_ucmd!();
2008
2009 let readonly_dir = "readonly_dir";
2010 let locked_file = "readonly_dir/a_file_is_locked";
2011 at.mkdir(readonly_dir);
2012 at.touch(locked_file);
2013 at.set_mode(readonly_dir, 0o555);
2014
2015 let target_file = "target_file";
2016 ucmd.arg(locked_file).arg(target_file).fails();
2017
2018 assert!(at.file_exists(locked_file));
2019 assert!(!at.file_exists(target_file));
2020 }
2021
2022 // Todo:
2023
2024 // $ at.touch a b
2025 // $ chmod -w b
2026 // $ ll
2027 // total 0
2028 // -rw-rw-r-- 1 user user 0 okt 25 11:21 a
2029 // -r--r--r-- 1 user user 0 okt 25 11:21 b
2030 // $
2031 // $ mv -v a b
2032 // mv: try to overwrite 'b', overriding mode 0444 (r--r--r--)? y
2033 // 'a' -> 'b'
2034
2035 #[cfg(target_os = "linux")]
2036 mod inter_partition_copying {
2037 use std::fs::{self, set_permissions, write};
2038 use std::os::unix::fs::{PermissionsExt, symlink};
2039 use tempfile::TempDir;
2040 use uutests::util::TestScenario;
2041 use uutests::util_name;
2042
2043 // setuid/setgid must survive a cross-device move when ownership is
2044 // preserved. The mover owns the file here, so the chown is a no-op and the
2045 // bits are legitimate; only a failed chown justifies stripping them, and
2046 // that needs a second uid, so it is exercised out of band rather than here.
2047 #[test]
2048 pub(crate) fn test_mv_inter_partition_keeps_setuid_when_ownership_preserved() {
2049 let scene = TestScenario::new(util_name!());
2050 let at = &scene.fixtures;
2051
2052 at.write("src", "src contents");
2053 set_permissions(at.plus("src"), PermissionsExt::from_mode(0o6755))
2054 .expect("Unable to set setuid/setgid on src");
2055
2056 let other_fs_tempdir =
2057 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory");
2058 let dest = other_fs_tempdir.path().join("dest");
2059
2060 scene
2061 .ucmd()
2062 .arg("src")
2063 .arg(dest.to_str().unwrap())
2064 .succeeds();
2065
2066 let mode = fs::metadata(&dest)
2067 .expect("destination should exist")
2068 .permissions()
2069 .mode()
2070 & 0o7777;
2071 assert_eq!(
2072 mode, 0o6755,
2073 "setuid/setgid must be kept when ownership was preserved, got {mode:o}"
2074 );
2075 }
2076
2077 // Ensure that the copying code used in an inter-partition move unlinks the destination symlink.
2078 #[test]
2079 pub(crate) fn test_mv_unlinks_dest_symlink() {
2080 let scene = TestScenario::new(util_name!());
2081 let at = &scene.fixtures;
2082
2083 // create a file in the current partition.
2084 at.write("src", "src contents");
2085
2086 // create a folder in another partition.
2087 let other_fs_tempdir =
2088 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory");
2089
2090 // create a file inside that folder.
2091 let other_fs_file_path = other_fs_tempdir.path().join("other_fs_file");
2092 write(&other_fs_file_path, "other fs file contents")
2093 .expect("Unable to write to other_fs_file");
2094
2095 // create a symlink to the file inside the same directory.
2096 let symlink_path = other_fs_tempdir.path().join("symlink_to_file");
2097 symlink(&other_fs_file_path, &symlink_path).expect("Unable to create symlink_to_file");
2098
2099 // mv src to symlink in another partition
2100 scene
2101 .ucmd()
2102 .arg("src")
2103 .arg(symlink_path.to_str().unwrap())
2104 .succeeds();
2105
2106 // make sure that src got removed.
2107 assert!(!at.file_exists("src"));
2108
2109 // make sure symlink got unlinked
2110 assert!(!symlink_path.is_symlink());
2111
2112 // make sure that file contents in other_fs_file didn't change.
2113 assert_eq!(
2114 fs::read_to_string(&other_fs_file_path).expect("Unable to read other_fs_file"),
2115 "other fs file contents"
2116 );
2117
2118 // make sure that src file contents got copied into new file created in symlink_path
2119 assert_eq!(
2120 fs::read_to_string(&symlink_path).expect("Unable to read other_fs_file"),
2121 "src contents"
2122 );
2123 }
2124
2125 // In an inter-partition move if unlinking the destination symlink fails, ensure
2126 // that it would output the proper error message.
2127 #[test]
2128 pub(crate) fn test_mv_unlinks_dest_symlink_error_message() {
2129 use uutests::util::TestScenario;
2130 let scene = TestScenario::new(util_name!());
2131 let at = &scene.fixtures;
2132
2133 at.write("src", "src contents");
2134
2135 let other_fs_tempdir =
2136 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory");
2137 let other_fs_file_path = other_fs_tempdir.path().join("other_fs_file");
2138 write(&other_fs_file_path, "other fs file contents")
2139 .expect("Unable to write to other_fs_file");
2140
2141 let symlink_path = other_fs_tempdir.path().join("symlink_to_file");
2142 symlink(&other_fs_file_path, &symlink_path).expect("Unable to create symlink_to_file");
2143
2144 set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o555))
2145 .expect("Unable to set permissions for temp directory");
2146
2147 // mv src to symlink in another partition
2148 scene
2149 .ucmd()
2150 .arg("src")
2151 .arg(symlink_path.to_str().unwrap())
2152 .fails()
2153 .stderr_contains("inter-device move failed:")
2154 .stderr_contains("Permission denied");
2155 }
2156
2157 // Test that hardlinks are preserved when moving files across partitions
2158 #[test]
2159 #[cfg(unix)]
2160 pub(crate) fn test_mv_preserves_hardlinks_across_partitions() {
2161 use std::fs;
2162 use std::os::unix::fs::MetadataExt;
2163 use tempfile::TempDir;
2164 use uutests::util::TestScenario;
2165
2166 let scene = TestScenario::new(util_name!());
2167 let at = &scene.fixtures;
2168
2169 at.write("file1", "test content");
2170 at.hard_link("file1", "file2");
2171
2172 let metadata1 = fs::metadata(at.plus("file1")).expect("Failed to get metadata for file1");
2173 let metadata2 = fs::metadata(at.plus("file2")).expect("Failed to get metadata for file2");
2174 assert_eq!(
2175 metadata1.ino(),
2176 metadata2.ino(),
2177 "Files should have same inode before move"
2178 );
2179 assert_eq!(
2180 metadata1.nlink(),
2181 2,
2182 "Files should have nlink=2 before move"
2183 );
2184
2185 // Create a target directory in another partition (using /dev/shm which is typically tmpfs)
2186 let other_fs_tempdir = TempDir::new_in("/dev/shm/")
2187 .expect("Unable to create temp directory in /dev/shm - test requires tmpfs");
2188
2189 scene
2190 .ucmd()
2191 .arg("file1")
2192 .arg("file2")
2193 .arg(other_fs_tempdir.path().to_str().unwrap())
2194 .succeeds();
2195
2196 assert!(!at.file_exists("file1"), "file1 should not exist in source");
2197 assert!(!at.file_exists("file2"), "file2 should not exist in source");
2198
2199 let moved_file1 = other_fs_tempdir.path().join("file1");
2200 let moved_file2 = other_fs_tempdir.path().join("file2");
2201 assert!(moved_file1.exists(), "file1 should exist in destination");
2202 assert!(moved_file2.exists(), "file2 should exist in destination");
2203
2204 let moved_metadata1 =
2205 fs::metadata(&moved_file1).expect("Failed to get metadata for moved file1");
2206 let moved_metadata2 =
2207 fs::metadata(&moved_file2).expect("Failed to get metadata for moved file2");
2208
2209 assert_eq!(
2210 moved_metadata1.ino(),
2211 moved_metadata2.ino(),
2212 "Files should have same inode after cross-partition move (hardlinks preserved)"
2213 );
2214 assert_eq!(
2215 moved_metadata1.nlink(),
2216 2,
2217 "Files should have nlink=2 after cross-partition move"
2218 );
2219
2220 // Verify content is preserved
2221 assert_eq!(
2222 fs::read_to_string(&moved_file1).expect("Failed to read moved file1"),
2223 "test content"
2224 );
2225 assert_eq!(
2226 fs::read_to_string(&moved_file2).expect("Failed to read moved file2"),
2227 "test content"
2228 );
2229 }
2230
2231 // Test that hardlinks are preserved even with multiple sets of hardlinked files
2232 #[test]
2233 #[cfg(unix)]
2234 #[allow(clippy::too_many_lines)]
2235 #[allow(clippy::similar_names)]
2236 pub(crate) fn test_mv_preserves_multiple_hardlink_groups_across_partitions() {
2237 use std::fs::metadata;
2238 use std::os::unix::fs::MetadataExt;
2239 use tempfile::TempDir;
2240 use uutests::util::TestScenario;
2241
2242 let scene = TestScenario::new(util_name!());
2243 let at = &scene.fixtures;
2244
2245 at.write("group1_file1", "content group 1");
2246 at.hard_link("group1_file1", "group1_file2");
2247
2248 at.write("group2_file1", "content group 2");
2249 at.hard_link("group2_file1", "group2_file2");
2250
2251 at.write("single_file", "single file content");
2252
2253 let g1f1_meta = metadata(at.plus("group1_file1")).unwrap();
2254 let g1f2_meta = metadata(at.plus("group1_file2")).unwrap();
2255 let g2f1_meta = metadata(at.plus("group2_file1")).unwrap();
2256 let g2f2_meta = metadata(at.plus("group2_file2")).unwrap();
2257 let single_meta = metadata(at.plus("single_file")).unwrap();
2258
2259 assert_eq!(
2260 g1f1_meta.ino(),
2261 g1f2_meta.ino(),
2262 "Group 1 files should have same inode"
2263 );
2264 assert_eq!(
2265 g2f1_meta.ino(),
2266 g2f2_meta.ino(),
2267 "Group 2 files should have same inode"
2268 );
2269 assert_ne!(
2270 g1f1_meta.ino(),
2271 g2f1_meta.ino(),
2272 "Different groups should have different inodes"
2273 );
2274 assert_eq!(single_meta.nlink(), 1, "Single file should have nlink=1");
2275
2276 let other_fs_tempdir =
2277 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
2278
2279 scene
2280 .ucmd()
2281 .arg("group1_file1")
2282 .arg("group1_file2")
2283 .arg("group2_file1")
2284 .arg("group2_file2")
2285 .arg("single_file")
2286 .arg(other_fs_tempdir.path().to_str().unwrap())
2287 .succeeds();
2288
2289 // Verify hardlinks are preserved for both groups
2290 let moved_g1f1 = other_fs_tempdir.path().join("group1_file1");
2291 let moved_g1f2 = other_fs_tempdir.path().join("group1_file2");
2292 let moved_g2f1 = other_fs_tempdir.path().join("group2_file1");
2293 let moved_g2f2 = other_fs_tempdir.path().join("group2_file2");
2294 let moved_single = other_fs_tempdir.path().join("single_file");
2295
2296 let moved_g1f1_meta = metadata(&moved_g1f1).unwrap();
2297 let moved_g1f2_meta = metadata(&moved_g1f2).unwrap();
2298 let moved_g2f1_meta = metadata(&moved_g2f1).unwrap();
2299 let moved_g2f2_meta = metadata(&moved_g2f2).unwrap();
2300 let moved_single_meta = metadata(&moved_single).unwrap();
2301
2302 assert_eq!(
2303 moved_g1f1_meta.ino(),
2304 moved_g1f2_meta.ino(),
2305 "Group 1 files should still be hardlinked after move"
2306 );
2307 assert_eq!(
2308 moved_g1f1_meta.nlink(),
2309 2,
2310 "Group 1 files should have nlink=2"
2311 );
2312
2313 assert_eq!(
2314 moved_g2f1_meta.ino(),
2315 moved_g2f2_meta.ino(),
2316 "Group 2 files should still be hardlinked after move"
2317 );
2318 assert_eq!(
2319 moved_g2f1_meta.nlink(),
2320 2,
2321 "Group 2 files should have nlink=2"
2322 );
2323
2324 assert_ne!(
2325 moved_g1f1_meta.ino(),
2326 moved_g2f1_meta.ino(),
2327 "Different groups should still have different inodes"
2328 );
2329
2330 assert_eq!(
2331 moved_single_meta.nlink(),
2332 1,
2333 "Single file should still have nlink=1"
2334 );
2335
2336 assert_eq!(fs::read_to_string(&moved_g1f1).unwrap(), "content group 1");
2337 assert_eq!(fs::read_to_string(&moved_g1f2).unwrap(), "content group 1");
2338 assert_eq!(fs::read_to_string(&moved_g2f1).unwrap(), "content group 2");
2339 assert_eq!(fs::read_to_string(&moved_g2f2).unwrap(), "content group 2");
2340 assert_eq!(
2341 fs::read_to_string(&moved_single).unwrap(),
2342 "single file content"
2343 );
2344 }
2345
2346 // Test hardlinks within directories being moved
2347 #[test]
2348 #[cfg(unix)]
2349 pub(crate) fn test_mv_preserves_hardlinks_in_directories_across_partitions() {
2350 use std::fs::metadata;
2351 use std::os::unix::fs::MetadataExt;
2352 use tempfile::TempDir;
2353 use uutests::util::TestScenario;
2354
2355 let scene = TestScenario::new(util_name!());
2356 let at = &scene.fixtures;
2357
2358 at.write("f", "file content");
2359 at.hard_link("f", "g");
2360
2361 at.mkdir("a");
2362 at.mkdir("b");
2363 at.write("a/1", "directory file content");
2364 at.hard_link("a/1", "b/1");
2365
2366 let f_meta = metadata(at.plus("f")).unwrap();
2367 let g_meta = metadata(at.plus("g")).unwrap();
2368 let a1_meta = metadata(at.plus("a/1")).unwrap();
2369 let b1_meta = metadata(at.plus("b/1")).unwrap();
2370
2371 assert_eq!(
2372 f_meta.ino(),
2373 g_meta.ino(),
2374 "f and g should have same inode before move"
2375 );
2376 assert_eq!(f_meta.nlink(), 2, "f should have nlink=2 before move");
2377 assert_eq!(
2378 a1_meta.ino(),
2379 b1_meta.ino(),
2380 "a/1 and b/1 should have same inode before move"
2381 );
2382 assert_eq!(a1_meta.nlink(), 2, "a/1 should have nlink=2 before move");
2383
2384 let other_fs_tempdir =
2385 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
2386
2387 scene
2388 .ucmd()
2389 .arg("f")
2390 .arg("g")
2391 .arg(other_fs_tempdir.path().to_str().unwrap())
2392 .succeeds();
2393
2394 scene
2395 .ucmd()
2396 .arg("a")
2397 .arg("b")
2398 .arg(other_fs_tempdir.path().to_str().unwrap())
2399 .succeeds();
2400
2401 let moved_f = other_fs_tempdir.path().join("f");
2402 let moved_g = other_fs_tempdir.path().join("g");
2403 let moved_f_metadata = metadata(&moved_f).unwrap();
2404 let moved_second_file_metadata = metadata(&moved_g).unwrap();
2405
2406 assert_eq!(
2407 moved_f_metadata.ino(),
2408 moved_second_file_metadata.ino(),
2409 "f and g should have same inode after cross-partition move"
2410 );
2411 assert_eq!(
2412 moved_f_metadata.nlink(),
2413 2,
2414 "f should have nlink=2 after move"
2415 );
2416
2417 // Verify directory files' hardlinks are preserved (the main test)
2418 let moved_dir_a_file = other_fs_tempdir.path().join("a/1");
2419 let moved_dir_second_file = other_fs_tempdir.path().join("b/1");
2420 let moved_dir_a_file_metadata = metadata(&moved_dir_a_file).unwrap();
2421 let moved_dir_second_file_metadata = metadata(&moved_dir_second_file).unwrap();
2422
2423 assert_eq!(
2424 moved_dir_a_file_metadata.ino(),
2425 moved_dir_second_file_metadata.ino(),
2426 "a/1 and b/1 should have same inode after cross-partition directory move (hardlinks preserved)"
2427 );
2428 assert_eq!(
2429 moved_dir_a_file_metadata.nlink(),
2430 2,
2431 "a/1 should have nlink=2 after move"
2432 );
2433
2434 assert_eq!(fs::read_to_string(&moved_f).unwrap(), "file content");
2435 assert_eq!(fs::read_to_string(&moved_g).unwrap(), "file content");
2436 assert_eq!(
2437 fs::read_to_string(&moved_dir_a_file).unwrap(),
2438 "directory file content"
2439 );
2440 assert_eq!(
2441 fs::read_to_string(&moved_dir_second_file).unwrap(),
2442 "directory file content"
2443 );
2444 }
2445
2446 // Test complex scenario with multiple hardlink groups across nested directories
2447 #[test]
2448 #[cfg(unix)]
2449 #[allow(clippy::too_many_lines)]
2450 #[allow(clippy::similar_names)]
2451 pub(crate) fn test_mv_preserves_complex_hardlinks_across_nested_directories() {
2452 use std::fs::metadata;
2453 use std::os::unix::fs::MetadataExt;
2454 use tempfile::TempDir;
2455 use uutests::util::TestScenario;
2456
2457 let scene = TestScenario::new(util_name!());
2458 let at = &scene.fixtures;
2459
2460 at.mkdir("dir1");
2461 at.mkdir("dir1/subdir1");
2462 at.mkdir("dir1/subdir2");
2463 at.mkdir("dir2");
2464 at.mkdir("dir2/subdir1");
2465
2466 at.write("dir1/subdir1/file_a", "content A");
2467 at.hard_link("dir1/subdir1/file_a", "dir1/subdir2/file_a_link1");
2468 at.hard_link("dir1/subdir1/file_a", "dir2/subdir1/file_a_link2");
2469
2470 at.write("dir1/file_b", "content B");
2471 at.hard_link("dir1/file_b", "dir2/file_b_link");
2472
2473 at.write("dir1/subdir1/nested_file", "nested content");
2474 at.hard_link("dir1/subdir1/nested_file", "dir1/subdir2/nested_file_link");
2475
2476 let orig_file_a_metadata = metadata(at.plus("dir1/subdir1/file_a")).unwrap();
2477 let orig_file_a_link1_metadata = metadata(at.plus("dir1/subdir2/file_a_link1")).unwrap();
2478 let orig_file_a_link2_metadata = metadata(at.plus("dir2/subdir1/file_a_link2")).unwrap();
2479
2480 assert_eq!(orig_file_a_metadata.ino(), orig_file_a_link1_metadata.ino());
2481 assert_eq!(orig_file_a_metadata.ino(), orig_file_a_link2_metadata.ino());
2482 assert_eq!(
2483 orig_file_a_metadata.nlink(),
2484 3,
2485 "file_a group should have nlink=3"
2486 );
2487
2488 let orig_file_b_metadata = metadata(at.plus("dir1/file_b")).unwrap();
2489 let orig_file_b_link_metadata = metadata(at.plus("dir2/file_b_link")).unwrap();
2490 assert_eq!(orig_file_b_metadata.ino(), orig_file_b_link_metadata.ino());
2491 assert_eq!(
2492 orig_file_b_metadata.nlink(),
2493 2,
2494 "file_b group should have nlink=2"
2495 );
2496
2497 let nested_meta = metadata(at.plus("dir1/subdir1/nested_file")).unwrap();
2498 let nested_link_meta = metadata(at.plus("dir1/subdir2/nested_file_link")).unwrap();
2499 assert_eq!(nested_meta.ino(), nested_link_meta.ino());
2500 assert_eq!(
2501 nested_meta.nlink(),
2502 2,
2503 "nested file group should have nlink=2"
2504 );
2505
2506 let other_fs_tempdir =
2507 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
2508
2509 scene
2510 .ucmd()
2511 .arg("dir1")
2512 .arg("dir2")
2513 .arg(other_fs_tempdir.path().to_str().unwrap())
2514 .succeeds();
2515
2516 let moved_file_a = other_fs_tempdir.path().join("dir1/subdir1/file_a");
2517 let moved_file_a_link1 = other_fs_tempdir.path().join("dir1/subdir2/file_a_link1");
2518 let moved_file_a_link2 = other_fs_tempdir.path().join("dir2/subdir1/file_a_link2");
2519
2520 let final_file_a_metadata = metadata(&moved_file_a).unwrap();
2521 let final_file_a_link1_metadata = metadata(&moved_file_a_link1).unwrap();
2522 let final_file_a_link2_metadata = metadata(&moved_file_a_link2).unwrap();
2523
2524 assert_eq!(
2525 final_file_a_metadata.ino(),
2526 final_file_a_link1_metadata.ino(),
2527 "file_a hardlinks should be preserved"
2528 );
2529 assert_eq!(
2530 final_file_a_metadata.ino(),
2531 final_file_a_link2_metadata.ino(),
2532 "file_a hardlinks should be preserved across directories"
2533 );
2534 assert_eq!(
2535 final_file_a_metadata.nlink(),
2536 3,
2537 "file_a group should still have nlink=3"
2538 );
2539
2540 let moved_file_b = other_fs_tempdir.path().join("dir1/file_b");
2541 let moved_file_b_hardlink = other_fs_tempdir.path().join("dir2/file_b_link");
2542 let final_file_b_metadata = metadata(&moved_file_b).unwrap();
2543 let final_file_b_hardlink_metadata = metadata(&moved_file_b_hardlink).unwrap();
2544
2545 assert_eq!(
2546 final_file_b_metadata.ino(),
2547 final_file_b_hardlink_metadata.ino(),
2548 "file_b hardlinks should be preserved"
2549 );
2550 assert_eq!(
2551 final_file_b_metadata.nlink(),
2552 2,
2553 "file_b group should still have nlink=2"
2554 );
2555
2556 let moved_nested = other_fs_tempdir.path().join("dir1/subdir1/nested_file");
2557 let moved_nested_link = other_fs_tempdir
2558 .path()
2559 .join("dir1/subdir2/nested_file_link");
2560 let moved_nested_meta = metadata(&moved_nested).unwrap();
2561 let moved_nested_link_meta = metadata(&moved_nested_link).unwrap();
2562
2563 assert_eq!(
2564 moved_nested_meta.ino(),
2565 moved_nested_link_meta.ino(),
2566 "nested file hardlinks should be preserved"
2567 );
2568 assert_eq!(
2569 moved_nested_meta.nlink(),
2570 2,
2571 "nested file group should still have nlink=2"
2572 );
2573
2574 assert_eq!(fs::read_to_string(&moved_file_a).unwrap(), "content A");
2575 assert_eq!(
2576 fs::read_to_string(&moved_file_a_link1).unwrap(),
2577 "content A"
2578 );
2579 assert_eq!(
2580 fs::read_to_string(&moved_file_a_link2).unwrap(),
2581 "content A"
2582 );
2583 assert_eq!(fs::read_to_string(&moved_file_b).unwrap(), "content B");
2584 assert_eq!(
2585 fs::read_to_string(&moved_file_b_hardlink).unwrap(),
2586 "content B"
2587 );
2588 assert_eq!(fs::read_to_string(&moved_nested).unwrap(), "nested content");
2589 assert_eq!(
2590 fs::read_to_string(&moved_nested_link).unwrap(),
2591 "nested content"
2592 );
2593 }
2594
2595 #[test]
2596 #[cfg(unix)]
2597 pub(crate) fn test_mv_dir_with_fifo_across_partitions() {
2598 use std::os::unix::fs::FileTypeExt;
2599 use tempfile::TempDir;
2600 use uutests::util::TestScenario;
2601
2602 let scene = TestScenario::new(util_name!());
2603 let at = &scene.fixtures;
2604
2605 at.mkdir("dir");
2606 at.mkfifo("dir/fifo");
2607
2608 let other_fs_tempdir =
2609 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
2610
2611 scene
2612 .ucmd()
2613 .arg("dir")
2614 .arg(other_fs_tempdir.path().to_str().unwrap())
2615 .succeeds()
2616 .no_output();
2617
2618 assert!(!at.dir_exists("dir"));
2619 let moved_fifo = other_fs_tempdir.path().join("dir/fifo");
2620 assert!(moved_fifo.symlink_metadata().unwrap().file_type().is_fifo());
2621 }
2622
2623 // A symlink pointing at a hardlinked sibling must not be mistaken for a
2624 // member of that hardlink group. Keying the inode map on metadata() (which
2625 // follows symlinks) instead of symlink_metadata() made mv "preserve" the
2626 // hardlink by linking the regular files to the copied *symlink*, leaving
2627 // self-referential symlinks and destroying the content.
2628 #[test]
2629 #[cfg(unix)]
2630 pub(crate) fn test_mv_symlink_to_hardlinked_sibling_across_partitions() {
2631 use std::os::unix::fs::MetadataExt;
2632
2633 let scene = TestScenario::new(util_name!());
2634 let at = &scene.fixtures;
2635
2636 at.mkdir("dir");
2637 at.write("dir/realfile", "important data");
2638 at.hard_link("dir/realfile", "dir/realfile2");
2639 // Two symlinks so the test does not depend on readdir order: one sorts
2640 // before the hardlink group, one after.
2641 at.relative_symlink_file("realfile", "dir/aaa_link");
2642 at.relative_symlink_file("realfile", "dir/zzz_link");
2643
2644 let other_fs_tempdir =
2645 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
2646
2647 scene
2648 .ucmd()
2649 .arg("dir")
2650 .arg(other_fs_tempdir.path().to_str().unwrap())
2651 .succeeds()
2652 .no_output();
2653
2654 let moved_dir = other_fs_tempdir.path().join("dir");
2655 let moved_realfile = moved_dir.join("realfile");
2656 let moved_realfile2 = moved_dir.join("realfile2");
2657
2658 for file in [&moved_realfile, &moved_realfile2] {
2659 assert!(
2660 file.symlink_metadata().unwrap().file_type().is_file(),
2661 "{} should still be a regular file, not a symlink",
2662 file.display()
2663 );
2664 assert_eq!(
2665 fs::read_to_string(file).unwrap(),
2666 "important data",
2667 "{} lost its content",
2668 file.display()
2669 );
2670 }
2671
2672 let realfile_metadata = fs::metadata(&moved_realfile).unwrap();
2673 assert_eq!(
2674 realfile_metadata.ino(),
2675 fs::metadata(&moved_realfile2).unwrap().ino(),
2676 "realfile and realfile2 should still be hardlinked"
2677 );
2678 assert_eq!(
2679 realfile_metadata.nlink(),
2680 2,
2681 "the hardlink group should not have gained the symlinks"
2682 );
2683
2684 for link in ["aaa_link", "zzz_link"] {
2685 let moved_link = moved_dir.join(link);
2686 assert!(
2687 moved_link
2688 .symlink_metadata()
2689 .unwrap()
2690 .file_type()
2691 .is_symlink(),
2692 "{link} should still be a symlink"
2693 );
2694 assert_eq!(
2695 fs::read_link(&moved_link).unwrap(),
2696 std::path::Path::new("realfile"),
2697 "{link} should still point at realfile"
2698 );
2699 }
2700 }
2701 }
2702
2703 #[test]
2704 fn test_mv_error_msg_with_multiple_sources_that_does_not_exist() {
2705 let scene = TestScenario::new(util_name!());
2706 let at = &scene.fixtures;
2707 at.mkdir("d");
2708 scene
2709 .ucmd()
2710 .arg("a")
2711 .arg("b/")
2712 .arg("d")
2713 .fails()
2714 .stderr_contains("mv: cannot stat 'a': No such file or directory")
2715 .stderr_contains("mv: cannot stat 'b/': No such file or directory");
2716 }
2717
2718 // Tests for hardlink preservation (now always enabled)
2719 #[test]
2720 #[cfg(all(unix, not(target_os = "android")))]
2721 fn test_mv_hardlink_preservation() {
2722 let (at, mut ucmd) = at_and_ucmd!();
2723
2724 at.write("file1", "test content");
2725 at.hard_link("file1", "file2");
2726 at.mkdir("target");
2727
2728 ucmd.arg("file1")
2729 .arg("file2")
2730 .arg("target")
2731 .succeeds()
2732 .no_stderr();
2733
2734 assert!(at.file_exists("target/file1"));
2735 assert!(at.file_exists("target/file2"));
2736 }
2737
2738 #[test]
2739 #[cfg(all(unix, not(target_os = "android")))]
2740 fn test_mv_hardlink_progress_indication() {
2741 let (at, mut ucmd) = at_and_ucmd!();
2742
2743 at.write("file1", "content1");
2744 at.write("file2", "content2");
2745 at.hard_link("file1", "file1_link");
2746
2747 at.mkdir("target");
2748
2749 // Test with progress bar and verbose mode
2750 ucmd.arg("--progress")
2751 .arg("--verbose")
2752 .arg("file1")
2753 .arg("file1_link")
2754 .arg("file2")
2755 .arg("target")
2756 .succeeds();
2757
2758 // Verify all files were moved
2759 assert!(at.file_exists("target/file1"));
2760 assert!(at.file_exists("target/file1_link"));
2761 assert!(at.file_exists("target/file2"));
2762 }
2763
2764 #[test]
2765 #[cfg(all(unix, not(target_os = "android")))]
2766 fn test_mv_mixed_hardlinks_and_regular_files() {
2767 use std::fs::metadata;
2768 use std::os::unix::fs::MetadataExt;
2769
2770 let (at, mut ucmd) = at_and_ucmd!();
2771
2772 // Create a mix of hardlinked and regular files
2773 at.write("hardlink1", "hardlink content");
2774 at.hard_link("hardlink1", "hardlink2");
2775 at.write("regular1", "regular content");
2776 at.write("regular2", "regular content 2");
2777
2778 at.mkdir("target");
2779
2780 // Move all files (hardlinks automatically preserved)
2781 ucmd.arg("hardlink1")
2782 .arg("hardlink2")
2783 .arg("regular1")
2784 .arg("regular2")
2785 .arg("target")
2786 .succeeds();
2787
2788 // Verify all files moved
2789 assert!(at.file_exists("target/hardlink1"));
2790 assert!(at.file_exists("target/hardlink2"));
2791 assert!(at.file_exists("target/regular1"));
2792 assert!(at.file_exists("target/regular2"));
2793
2794 // Verify hardlinks are preserved (on same filesystem)
2795 let h1_meta = metadata(at.plus("target/hardlink1")).unwrap();
2796 let h2_meta = metadata(at.plus("target/hardlink2")).unwrap();
2797 let r1_meta = metadata(at.plus("target/regular1")).unwrap();
2798 let r2_meta = metadata(at.plus("target/regular2")).unwrap();
2799
2800 // Hardlinked files should have same inode if on same filesystem
2801 if h1_meta.dev() == h2_meta.dev() {
2802 assert_eq!(h1_meta.ino(), h2_meta.ino());
2803 }
2804
2805 // Regular files should have different inodes
2806 assert_ne!(r1_meta.ino(), r2_meta.ino());
2807 }
2808
2809 #[cfg(not(windows))]
2810 #[ignore = "requires access to a different filesystem"]
2811 #[test]
2812 fn test_special_file_different_filesystem() {
2813 let (at, mut ucmd) = at_and_ucmd!();
2814 at.mkfifo("f");
2815 // TODO Use `TestScenario::mount_temp_fs()` for this purpose and
2816 // un-ignore this test.
2817 std::fs::create_dir("/dev/shm/tmp").unwrap();
2818 ucmd.args(&["f", "/dev/shm/tmp"]).succeeds().no_output();
2819 assert!(!at.file_exists("f"));
2820 assert!(Path::new("/dev/shm/tmp/f").exists());
2821 std::fs::remove_dir_all("/dev/shm/tmp").unwrap();
2822 }
2823
2824 /// Test cross-device move with permission denied error
2825 /// Test partial failure handling where
2826 /// a cross-device move fails due to permission errors when removing the target file
2827 #[test]
2828 #[cfg(target_os = "linux")]
2829 fn test_mv_cross_device_permission_denied() {
2830 use std::fs::{set_permissions, write};
2831 use std::os::unix::fs::PermissionsExt;
2832 use tempfile::TempDir;
2833 use uutests::util::TestScenario;
2834
2835 let scene = TestScenario::new(util_name!());
2836 let at = &scene.fixtures;
2837
2838 at.write("k", "source content");
2839
2840 let other_fs_tempdir =
2841 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
2842
2843 let target_file_path = other_fs_tempdir.path().join("k");
2844 write(&target_file_path, "target content").expect("Unable to write target file");
2845
2846 // Remove write permissions from the directory to cause permission denied
2847 set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o555))
2848 .expect("Unable to set directory permissions");
2849
2850 // Attempt to move file to the other filesystem
2851 // This should fail with a permission denied error
2852 let result = scene
2853 .ucmd()
2854 .arg("-f")
2855 .arg("k")
2856 .arg(target_file_path.to_str().unwrap())
2857 .fails();
2858
2859 // Check that it contains permission denied and references the file
2860 // The exact format may vary but should contain these key elements
2861 let stderr = result.stderr_str();
2862 assert!(stderr.contains("Permission denied") || stderr.contains("permission denied"));
2863
2864 set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o755))
2865 .expect("Unable to restore directory permissions");
2866 }
2867
2868 /// Regression for #10015. The cross-device fallback unlinks the destination
2869 /// and then creates a new file at the same path. An attacker who can write
2870 /// to the destination directory could race to plant a symlink in that
2871 /// window; without `O_NOFOLLOW` on the create, the copy would write through
2872 /// the symlink. The deterministic stand-in here pre-plants the symlink:
2873 /// `safe_copy::create_dest_restrictive` must refuse it with `ELOOP` rather
2874 /// than truncate `victim`.
2875 #[test]
2876 #[cfg(target_os = "linux")]
2877 fn test_mv_cross_device_refuses_planted_symlink_dest() {
2878 use std::os::unix::fs::symlink;
2879 use tempfile::TempDir;
2880 use uutests::util::TestScenario;
2881
2882 let scene = TestScenario::new(util_name!());
2883 let at = &scene.fixtures;
2884 at.write("payload", "PAYLOAD_FROM_SRC");
2885
2886 let dst_dir =
2887 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
2888 let victim = dst_dir.path().join("victim");
2889 std::fs::write(&victim, "PROTECTED_DATA").expect("write victim");
2890 let target = dst_dir.path().join("target");
2891 symlink(&victim, &target).expect("plant symlink");
2892
2893 // mv replaces the symlink at `target` with a fresh regular file. The
2894 // important invariant is that `victim` is never opened for write.
2895 scene
2896 .ucmd()
2897 .arg("-f")
2898 .arg("payload")
2899 .arg(target.to_str().unwrap())
2900 .succeeds();
2901
2902 assert_eq!(
2903 std::fs::read_to_string(&victim).expect("victim still readable"),
2904 "PROTECTED_DATA",
2905 "cross-device mv must not write through a planted symlink at dest"
2906 );
2907 }
2908
2909 /// Directory counterpart of `test_mv_cross_device_refuses_planted_symlink_dest`.
2910 ///
2911 /// The cross-device directory fallback removes the destination and recreates it.
2912 /// Recreation must fail closed: `create_dir_all` would accept a symlink-to-directory
2913 /// left at the path and move the whole source tree through it, outside the destination.
2914 #[test]
2915 #[cfg(target_os = "linux")]
2916 fn test_mv_cross_device_dir_refuses_symlink_at_recreated_dest() {
2917 use tempfile::TempDir;
2918 use uutests::util::TestScenario;
2919
2920 let scene = TestScenario::new(util_name!());
2921 let at = &scene.fixtures;
2922
2923 let src_dir =
2924 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
2925 let src = src_dir.path().join("srcdir");
2926 std::fs::create_dir(&src).expect("create src");
2927 std::fs::write(src.join("payload"), "PAYLOAD_FROM_SRC").expect("write payload");
2928
2929 at.mkdir("victim");
2930 at.write("victim/guard", "PROTECTED_DATA");
2931 at.symlink_dir("victim", "target");
2932
2933 // Whether this succeeds or fails, the invariant is that nothing from the
2934 // source is written inside `victim`.
2935 scene
2936 .ucmd()
2937 .arg("-T")
2938 .arg(src.to_str().unwrap())
2939 .arg("target")
2940 .run();
2941
2942 assert!(
2943 !at.file_exists("victim/payload"),
2944 "cross-device dir move escaped the destination through a symlink"
2945 );
2946 assert_eq!(at.read("victim/guard"), "PROTECTED_DATA");
2947 }
2948
2949 #[test]
2950 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
2951 fn test_mv_selinux_context() {
2952 let test_cases = [
2953 ("-Z", None),
2954 (
2955 "--context=unconfined_u:object_r:user_tmp_t:s0",
2956 Some("unconfined_u"),
2957 ),
2958 ];
2959
2960 for (arg, expected_context) in test_cases {
2961 let scene = TestScenario::new(util_name!());
2962 let at = &scene.fixtures;
2963 let src = "source.txt";
2964 let dest = "dest.txt";
2965
2966 at.touch(src);
2967
2968 let mut cmd = scene.ucmd();
2969 cmd.arg(arg);
2970
2971 let result = cmd
2972 .arg(at.plus_as_string(src))
2973 .arg(at.plus_as_string(dest))
2974 .run();
2975
2976 // Skip test if SELinux is not enabled
2977 if result
2978 .stderr_str()
2979 .contains("SELinux is not enabled on this system")
2980 {
2981 println!("Skipping SELinux test: SELinux is not enabled");
2982 return;
2983 }
2984
2985 result.success();
2986 assert!(at.file_exists(dest));
2987 assert!(!at.file_exists(src));
2988
2989 // Verify SELinux context was set using getfattr
2990 let context_value = get_getfattr_output(&at.plus_as_string(dest));
2991 if !context_value.is_empty()
2992 && let Some(expected) = expected_context
2993 {
2994 assert!(
2995 context_value.contains(expected),
2996 "Expected context to contain '{expected}', got: {context_value}"
2997 );
2998 }
2999
3000 // Clean up files
3001 let _ = std::fs::remove_file(at.plus_as_string(dest));
3002 let _ = std::fs::remove_file(at.plus_as_string(src));
3003 }
3004 }
3005
3006 #[test]
3007 fn test_mv_error_usage_display_missing_arg() {
3008 new_ucmd!()
3009 .arg("--target-directory=.")
3010 .fails()
3011 .code_is(1)
3012 .stderr_contains("error: the following required arguments were not provided:")
3013 .stderr_contains("<files>...")
3014 .stderr_contains("Usage: mv [OPTION]... [-T] SOURCE DEST")
3015 .stderr_contains("For more information, try '--help'.");
3016 }
3017
3018 #[test]
3019 fn test_mv_error_usage_display_too_few() {
3020 new_ucmd!()
3021 .arg("file1")
3022 .fails()
3023 .code_is(1)
3024 .stderr_contains("requires at least 2 values, but only 1 was provided")
3025 .stderr_contains("Usage: mv [OPTION]... [-T] SOURCE DEST")
3026 .stderr_contains("For more information, try '--help'.");
3027 }
3028
3029 #[test]
3030 #[cfg(target_os = "linux")]
3031 fn test_mv_verbose_directory_recursive() {
3032 use tempfile::TempDir;
3033
3034 let scene = TestScenario::new(util_name!());
3035 let at = &scene.fixtures;
3036
3037 at.mkdir("mv-dir");
3038 at.mkdir("mv-dir/a");
3039 at.mkdir("mv-dir/a/b");
3040 at.mkdir("mv-dir/a/b/c");
3041 at.mkdir("mv-dir/d");
3042 at.mkdir("mv-dir/d/e");
3043 at.mkdir("mv-dir/d/e/f");
3044 at.touch("mv-dir/a/b/c/file1");
3045 at.touch("mv-dir/d/e/f/file2");
3046
3047 // Force cross-filesystem move using /dev/shm (tmpfs)
3048 let target_dir =
3049 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3050 let target_path = target_dir.path().to_str().unwrap();
3051
3052 let result = scene
3053 .ucmd()
3054 .arg("--verbose")
3055 .arg("mv-dir")
3056 .arg(target_path)
3057 .succeeds();
3058
3059 // Check that the directory structure was moved
3060 assert!(!at.dir_exists("mv-dir"));
3061 assert!(target_dir.path().join("mv-dir").exists());
3062 assert!(target_dir.path().join("mv-dir/a").exists());
3063 assert!(target_dir.path().join("mv-dir/a/b").exists());
3064 assert!(target_dir.path().join("mv-dir/a/b/c").exists());
3065 assert!(target_dir.path().join("mv-dir/d").exists());
3066 assert!(target_dir.path().join("mv-dir/d/e").exists());
3067 assert!(target_dir.path().join("mv-dir/d/e/f").exists());
3068 assert!(target_dir.path().join("mv-dir/a/b/c/file1").exists());
3069 assert!(target_dir.path().join("mv-dir/d/e/f/file2").exists());
3070
3071 let stdout = result.stdout_str();
3072
3073 // With cross-filesystem move, we MUST see recursive verbose output
3074 assert!(stdout.contains("'mv-dir/a' -> "));
3075 assert!(stdout.contains("'mv-dir/a/b' -> "));
3076 assert!(stdout.contains("'mv-dir/a/b/c' -> "));
3077 assert!(stdout.contains("'mv-dir/a/b/c/file1' -> "));
3078 assert!(stdout.contains("'mv-dir/d' -> "));
3079 assert!(stdout.contains("'mv-dir/d/e' -> "));
3080 assert!(stdout.contains("'mv-dir/d/e/f' -> "));
3081 assert!(stdout.contains("'mv-dir/d/e/f/file2' -> "));
3082 }
3083
3084 #[cfg(unix)]
3085 #[test]
3086 fn test_mv_prompt_unwriteable_file_when_using_tty() {
3087 let (at, mut ucmd) = at_and_ucmd!();
3088
3089 at.touch("source");
3090 at.touch("target");
3091 at.set_mode("target", 0o000);
3092
3093 ucmd.arg("source")
3094 .arg("target")
3095 .terminal_sim_stdio(TerminalSimulation {
3096 stdin: true,
3097 stdout: false,
3098 stderr: false,
3099 ..Default::default()
3100 })
3101 .pipe_in("n\n")
3102 .fails()
3103 .stderr_contains("replace 'target', overriding mode 0000");
3104
3105 assert!(at.file_exists("source"));
3106 }
3107
3108 #[cfg(unix)]
3109 #[test]
3110 fn test_mv_force_no_prompt_unwriteable_file() {
3111 let (at, mut ucmd) = at_and_ucmd!();
3112
3113 at.touch("source_f");
3114 at.touch("target_f");
3115 at.set_mode("target_f", 0o000);
3116
3117 ucmd.arg("-f")
3118 .arg("source_f")
3119 .arg("target_f")
3120 .terminal_sim_stdio(TerminalSimulation {
3121 stdin: true,
3122 stdout: false,
3123 stderr: false,
3124 ..Default::default()
3125 })
3126 .succeeds()
3127 .no_stderr();
3128
3129 assert!(!at.file_exists("source_f"));
3130 assert!(at.file_exists("target_f"));
3131 }
3132
3133 #[cfg(unix)]
3134 #[test]
3135 fn test_mv_no_prompt_unwriteable_file_with_no_tty() {
3136 let (at, mut ucmd) = at_and_ucmd!();
3137
3138 at.touch("source_notty");
3139 at.touch("target_notty");
3140 at.set_mode("target_notty", 0o000);
3141
3142 ucmd.arg("source_notty")
3143 .arg("target_notty")
3144 .succeeds()
3145 .no_stderr();
3146
3147 assert!(!at.file_exists("source_notty"));
3148 assert!(at.file_exists("target_notty"));
3149 }
3150
3151 /// Test mv silently succeeds when dest filesystem doesn't support xattrs (ENOTSUP)
3152 #[test]
3153 #[cfg(target_os = "linux")]
3154 fn test_mv_xattr_enotsup_silent() {
3155 use std::process::Command;
3156 let scene = TestScenario::new(util_name!());
3157 let at = &scene.fixtures;
3158 at.write("src", "x");
3159
3160 if Command::new("setfattr")
3161 .args(["-n", "user.t", "-v", "v", &at.plus_as_string("src")])
3162 .status()
3163 .is_ok_and(|s| s.success())
3164 {
3165 scene
3166 .ucmd()
3167 .arg(at.plus_as_string("src"))
3168 .arg("/dev/shm/mv_test")
3169 .succeeds()
3170 .no_stderr();
3171 std::fs::remove_file("/dev/shm/mv_test").ok();
3172 }
3173 }
3174
3175 /// Cross-device mv of a directory must preserve the directory's own xattrs.
3176 /// The fd-based xattr path has to open the destination read-only: a directory
3177 /// cannot be opened for writing, so a write-mode open would silently drop them.
3178 #[test]
3179 #[cfg(target_os = "linux")]
3180 fn test_mv_cross_device_dir_xattr_preserved() {
3181 use std::process::Command;
3182 use tempfile::TempDir;
3183
3184 let scene = TestScenario::new(util_name!());
3185 let at = &scene.fixtures;
3186
3187 at.mkdir("src_dir");
3188 at.write("src_dir/file.txt", "content");
3189
3190 if !Command::new("setfattr")
3191 .args([
3192 "-n",
3193 "user.dirattr",
3194 "-v",
3195 "dirvalue",
3196 &at.plus_as_string("src_dir"),
3197 ])
3198 .status()
3199 .is_ok_and(|s| s.success())
3200 {
3201 println!("test skipped: setfattr failed");
3202 return;
3203 }
3204
3205 let other_fs_tempdir =
3206 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3207 let dst_path = other_fs_tempdir.path().join("dst_dir");
3208
3209 scene
3210 .ucmd()
3211 .arg(at.plus_as_string("src_dir"))
3212 .arg(dst_path.to_str().unwrap())
3213 .succeeds()
3214 .no_stderr();
3215
3216 let out = Command::new("getfattr")
3217 .args([
3218 "-n",
3219 "user.dirattr",
3220 "--only-values",
3221 dst_path.to_str().unwrap(),
3222 ])
3223 .output()
3224 .expect("failed to run getfattr on the moved directory");
3225 assert!(
3226 out.status.success(),
3227 "directory xattr was not preserved across devices: {}",
3228 String::from_utf8_lossy(&out.stderr)
3229 );
3230 assert_eq!(out.stdout, b"dirvalue");
3231 }
3232
3233 /// Cross-device mv of a symlink onto an existing file must replace the
3234 /// destination atomically, matching GNU.
3235 #[test]
3236 #[cfg(target_os = "linux")]
3237 fn test_mv_cross_device_symlink_onto_existing() {
3238 use std::fs;
3239 use std::os::unix::fs::symlink;
3240 use tempfile::TempDir;
3241
3242 let scene = TestScenario::new(util_name!());
3243 let at = &scene.fixtures;
3244
3245 symlink("/etc/passwd", at.plus("src_link")).expect("Failed to create source symlink");
3246
3247 let other_fs_tempdir =
3248 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3249 let dst_path = other_fs_tempdir.path().join("dst_exists");
3250 fs::write(&dst_path, "placeholder").expect("Failed to write placeholder dst");
3251
3252 scene
3253 .ucmd()
3254 .arg(at.plus_as_string("src_link"))
3255 .arg(dst_path.to_str().unwrap())
3256 .succeeds()
3257 .no_stderr();
3258
3259 assert!(
3260 dst_path.is_symlink(),
3261 "dst_exists should now be a symlink after the cross-device move"
3262 );
3263 assert_eq!(
3264 fs::read_link(&dst_path).expect("read_link failed"),
3265 Path::new("/etc/passwd"),
3266 );
3267 assert!(
3268 !at.symlink_exists("src_link"),
3269 "source symlink should be gone"
3270 );
3271 }
3272
3273 /// Cross-device mv of a symlink onto an existing directory (`-T`) must
3274 /// fail without destroying the directory or its contents.
3275 #[test]
3276 #[cfg(target_os = "linux")]
3277 fn test_mv_cross_device_symlink_onto_existing_dir() {
3278 use std::fs;
3279 use std::os::unix::fs::symlink;
3280 use tempfile::TempDir;
3281
3282 let scene = TestScenario::new(util_name!());
3283 let at = &scene.fixtures;
3284
3285 symlink("/etc/passwd", at.plus("src_link")).expect("Failed to create source symlink");
3286
3287 let other_fs_tempdir =
3288 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3289 let dst_dir = other_fs_tempdir.path().join("dst_dir");
3290 fs::create_dir(&dst_dir).expect("Failed to create destination directory");
3291 fs::write(dst_dir.join("guard"), "preserved").expect("Failed to write guard file");
3292
3293 scene
3294 .ucmd()
3295 .arg("-T")
3296 .arg(at.plus_as_string("src_link"))
3297 .arg(dst_dir.to_str().unwrap())
3298 .fails();
3299
3300 assert!(
3301 dst_dir.is_dir(),
3302 "destination directory must still exist after failed mv"
3303 );
3304 assert!(
3305 dst_dir.join("guard").is_file(),
3306 "destination directory contents must be untouched"
3307 );
3308 assert!(
3309 at.symlink_exists("src_link"),
3310 "source symlink must not be removed when mv fails"
3311 );
3312 }
3313
3314 /// Test that symlinks inside directories are preserved during cross-device moves
3315 /// (not expanded into full copies of their targets)
3316 #[test]
3317 #[cfg(target_os = "linux")]
3318 fn test_mv_cross_device_symlink_preserved() {
3319 use std::fs;
3320 use std::os::unix::fs::symlink;
3321 use tempfile::TempDir;
3322
3323 let scene = TestScenario::new(util_name!());
3324 let at = &scene.fixtures;
3325
3326 // Create a directory with a symlink to /etc inside
3327 at.mkdir("src_dir");
3328 at.write("src_dir/local.txt", "local content");
3329 symlink("/etc", at.plus("src_dir/etc_link")).expect("Failed to create symlink");
3330
3331 assert!(at.is_symlink("src_dir/etc_link"));
3332
3333 // Force cross-filesystem move using /dev/shm (tmpfs)
3334 let target_dir =
3335 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3336 let target_path = target_dir.path().join("dst_dir");
3337
3338 scene
3339 .ucmd()
3340 .arg("src_dir")
3341 .arg(target_path.to_str().unwrap())
3342 .succeeds()
3343 .no_stderr();
3344
3345 assert!(!at.dir_exists("src_dir"));
3346
3347 // Verify the symlink was preserved (not expanded)
3348 let moved_symlink = target_path.join("etc_link");
3349 assert!(
3350 moved_symlink.is_symlink(),
3351 "etc_link should still be a symlink after cross-device move"
3352 );
3353 assert_eq!(
3354 fs::read_link(&moved_symlink).expect("Failed to read symlink"),
3355 Path::new("/etc"),
3356 "symlink should still point to /etc"
3357 );
3358
3359 assert!(target_path.join("local.txt").exists());
3360 }
3361
3362 /// Test that broken/dangling symlinks are preserved during cross-device moves
3363 #[test]
3364 #[cfg(target_os = "linux")]
3365 fn test_mv_cross_device_broken_symlink_preserved() {
3366 use std::fs;
3367 use std::os::unix::fs::symlink;
3368 use tempfile::TempDir;
3369
3370 let scene = TestScenario::new(util_name!());
3371 let at = &scene.fixtures;
3372
3373 // Create a directory with a broken symlink inside
3374 at.mkdir("src_dir");
3375 symlink("/nonexistent/path", at.plus("src_dir/broken_link"))
3376 .expect("Failed to create broken symlink");
3377
3378 assert!(at.is_symlink("src_dir/broken_link"));
3379 assert!(!at.file_exists("src_dir/broken_link"));
3380
3381 // Force cross-filesystem move using /dev/shm (tmpfs)
3382 let target_dir =
3383 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3384 let target_path = target_dir.path().join("dst_dir");
3385
3386 scene
3387 .ucmd()
3388 .arg("src_dir")
3389 .arg(target_path.to_str().unwrap())
3390 .succeeds()
3391 .no_stderr();
3392
3393 assert!(!at.dir_exists("src_dir"));
3394
3395 let moved_symlink = target_path.join("broken_link");
3396 assert!(
3397 moved_symlink.is_symlink(),
3398 "broken_link should still be a symlink after cross-device move"
3399 );
3400 assert_eq!(
3401 fs::read_link(&moved_symlink).expect("Failed to read broken symlink"),
3402 Path::new("/nonexistent/path"),
3403 "broken symlink should still point to its original (nonexistent) target"
3404 );
3405 }
3406
3407 /// Test that symlinks to regular files are preserved during cross-device moves
3408 #[test]
3409 #[cfg(target_os = "linux")]
3410 fn test_mv_cross_device_file_symlink_preserved() {
3411 use std::fs;
3412 use std::os::unix::fs::symlink;
3413 use tempfile::TempDir;
3414
3415 let scene = TestScenario::new(util_name!());
3416 let at = &scene.fixtures;
3417
3418 // Create a directory with a file and a symlink to it
3419 at.mkdir("src_dir");
3420 at.write("src_dir/target.txt", "target content");
3421 symlink(at.plus("src_dir/target.txt"), at.plus("src_dir/file_link"))
3422 .expect("Failed to create file symlink");
3423
3424 assert!(at.is_symlink("src_dir/file_link"));
3425
3426 // Force cross-filesystem move using /dev/shm (tmpfs)
3427 let target_dir =
3428 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3429 let target_path = target_dir.path().join("dst_dir");
3430
3431 scene
3432 .ucmd()
3433 .arg("src_dir")
3434 .arg(target_path.to_str().unwrap())
3435 .succeeds()
3436 .no_stderr();
3437
3438 assert!(!at.dir_exists("src_dir"));
3439
3440 // Verify the symlink was preserved (not expanded)
3441 let moved_symlink = target_path.join("file_link");
3442 assert!(
3443 moved_symlink.is_symlink(),
3444 "file_link should still be a symlink after cross-device move"
3445 );
3446
3447 // Verify the target file was also moved
3448 let moved_target = target_path.join("target.txt");
3449 assert!(moved_target.exists());
3450 assert_eq!(
3451 fs::read_to_string(&moved_target).expect("Failed to read target file"),
3452 "target content"
3453 );
3454 }
3455
3456 /// Find a supplementary group that differs from `current`.
3457 /// Non-root users can chgrp to any group they belong to.
3458 #[cfg(target_os = "linux")]
3459 fn find_other_group(current: u32) -> Option<u32> {
3460 rustix::process::getgroups().ok()?.iter().find_map(|group| {
3461 let gid = group.as_raw();
3462 (gid != current).then_some(gid)
3463 })
3464 }
3465
3466 /// Test that group ownership is preserved during cross-device file moves.
3467 /// Uses chgrp to a supplementary group (no root needed).
3468 /// See https://github.com/uutils/coreutils/issues/9714
3469 #[test]
3470 #[cfg(target_os = "linux")]
3471 fn test_mv_cross_device_preserves_ownership() {
3472 use std::fs;
3473 use std::os::unix::fs::MetadataExt;
3474 use tempfile::TempDir;
3475
3476 let scene = TestScenario::new(util_name!());
3477 let at = &scene.fixtures;
3478
3479 at.write("owned_file", "owned content");
3480 let file_path = at.plus("owned_file");
3481
3482 let original_meta = fs::metadata(&file_path).expect("Failed to get metadata");
3483 let Some(other_gid) = find_other_group(original_meta.gid()) else {
3484 println!("SKIPPED: no supplementary group available for chgrp");
3485 return;
3486 };
3487
3488 // chgrp to a different group (non-root users can do this for their own groups)
3489 uucore::perms::wrap_chown(
3490 &file_path,
3491 &original_meta,
3492 None,
3493 Some(other_gid),
3494 false,
3495 uucore::perms::Verbosity::default(),
3496 )
3497 .expect("Failed to chgrp file");
3498
3499 let meta = fs::metadata(&file_path).expect("Failed to get metadata");
3500 assert_eq!(meta.gid(), other_gid, "chgrp should have changed the gid");
3501
3502 // Force cross-filesystem move using /dev/shm (tmpfs)
3503 let target_dir =
3504 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3505 let target_file = target_dir.path().join("owned_file");
3506
3507 scene
3508 .ucmd()
3509 .arg("owned_file")
3510 .arg(target_file.to_str().unwrap())
3511 .succeeds()
3512 .no_stderr();
3513
3514 let moved_meta = fs::metadata(&target_file).expect("Failed to get metadata of moved file");
3515 assert_eq!(
3516 moved_meta.gid(),
3517 other_gid,
3518 "gid should be preserved after cross-device move (expected {other_gid}, got {})",
3519 moved_meta.gid()
3520 );
3521 assert_eq!(
3522 moved_meta.uid(),
3523 meta.uid(),
3524 "uid should be preserved after cross-device move"
3525 );
3526 }
3527
3528 /// Test that group ownership is preserved for files inside directories during cross-device moves.
3529 /// Uses chgrp to a supplementary group (no root needed).
3530 /// See https://github.com/uutils/coreutils/issues/9714
3531 #[test]
3532 #[cfg(target_os = "linux")]
3533 fn test_mv_cross_device_preserves_ownership_recursive() {
3534 use std::fs;
3535 use std::os::unix::fs::MetadataExt;
3536 use tempfile::TempDir;
3537
3538 let scene = TestScenario::new(util_name!());
3539 let at = &scene.fixtures;
3540
3541 at.mkdir("owned_dir");
3542 at.mkdir("owned_dir/sub");
3543 at.write("owned_dir/file1", "content1");
3544 at.write("owned_dir/sub/file2", "content2");
3545
3546 let dir_meta = fs::metadata(at.plus("owned_dir")).expect("Failed to get metadata");
3547 let Some(other_gid) = find_other_group(dir_meta.gid()) else {
3548 println!("SKIPPED: no supplementary group available for chgrp");
3549 return;
3550 };
3551
3552 // chgrp all entries to a different group
3553 for path in &[
3554 "owned_dir",
3555 "owned_dir/sub",
3556 "owned_dir/file1",
3557 "owned_dir/sub/file2",
3558 ] {
3559 let p = at.plus(path);
3560 let m = fs::metadata(&p).expect("Failed to get metadata");
3561 uucore::perms::wrap_chown(
3562 &p,
3563 &m,
3564 None,
3565 Some(other_gid),
3566 false,
3567 uucore::perms::Verbosity::default(),
3568 )
3569 .expect("Failed to chgrp");
3570 }
3571
3572 // Force cross-filesystem move using /dev/shm (tmpfs)
3573 let target_dir =
3574 TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm");
3575 let target_path = target_dir.path().join("owned_dir");
3576
3577 scene
3578 .ucmd()
3579 .arg("owned_dir")
3580 .arg(target_path.to_str().unwrap())
3581 .succeeds()
3582 .no_stderr();
3583
3584 // Check ownership of the directory itself
3585 let moved_dir_meta = fs::metadata(&target_path).expect("Failed to get dir metadata");
3586 assert_eq!(
3587 moved_dir_meta.gid(),
3588 other_gid,
3589 "directory gid should be preserved after cross-device move"
3590 );
3591
3592 // Check ownership of a file inside the directory
3593 let file1_meta = fs::metadata(target_path.join("file1")).expect("Failed to get file1 metadata");
3594 assert_eq!(
3595 file1_meta.gid(),
3596 other_gid,
3597 "file gid should be preserved after cross-device move"
3598 );
3599
3600 // Check ownership of a file in a subdirectory
3601 let file2_meta =
3602 fs::metadata(target_path.join("sub/file2")).expect("Failed to get file2 metadata");
3603 assert_eq!(
3604 file2_meta.gid(),
3605 other_gid,
3606 "nested file gid should be preserved after cross-device move"
3607 );
3608 }
3609
3610 #[test]
3611 fn test_mv_backup_existing_mode_protects_source() {
3612 // `--backup=existing` falls back to a simple backup when no numbered
3613 // backup is present, so it can destroy the source just as `simple` does.
3614 // GNU refuses in every mode but `numbered`.
3615 for mode in ["simple", "existing"] {
3616 let (at, mut ucmd) = at_and_ucmd!();
3617 at.touch("a");
3618 at.write("a~", "source content");
3619
3620 ucmd.arg(format!("--backup={mode}"))
3621 .arg("a~")
3622 .arg("a")
3623 .fails()
3624 .stderr_contains("might destroy source");
3625
3626 assert_eq!(at.read("a~"), "source content");
3627 }
3628 }
3629
3630 #[test]
3631 fn test_mv_backup_existing_mode_protects_source_even_with_numbered_present() {
3632 // GNU's check always uses the simple suffix once the mode is not
3633 // `numbered`, so an existing `a.~1~` does not make this safe.
3634 let (at, mut ucmd) = at_and_ucmd!();
3635 at.touch("a");
3636 at.write("a~", "source content");
3637 at.write("a.~1~", "old numbered backup");
3638
3639 ucmd.arg("--backup=existing")
3640 .arg("a~")
3641 .arg("a")
3642 .fails()
3643 .stderr_contains("might destroy source");
3644
3645 assert_eq!(at.read("a~"), "source content");
3646 }
3647
3648 #[test]
3649 fn test_mv_backup_numbered_allows_source_named_like_backup() {
3650 let (at, mut ucmd) = at_and_ucmd!();
3651 at.touch("a");
3652 at.write("a~", "source content");
3653
3654 ucmd.arg("--backup=numbered").arg("a~").arg("a").succeeds();
3655 assert_eq!(at.read("a"), "source content");
3656 }
3657
3658 #[cfg(any(target_os = "linux", target_os = "android"))]
3659 #[test]
3660 fn test_mv_exchange_file_and_dir() {
3661 let (at, mut ucmd) = at_and_ucmd!();
3662 at.write("leaf", "payload");
3663 at.mkdir("branch");
3664
3665 ucmd.arg("-T")
3666 .arg("--exchange")
3667 .arg("leaf")
3668 .arg("branch")
3669 .succeeds()
3670 .no_output();
3671
3672 // After the swap the names trade places.
3673 assert!(at.dir_exists("leaf"));
3674 assert!(at.file_exists("branch"));
3675 assert_eq!(at.read("branch"), "payload");
3676 }
3677
3678 #[cfg(any(target_os = "linux", target_os = "android"))]
3679 #[test]
3680 fn test_mv_exchange_verbose() {
3681 let (at, mut ucmd) = at_and_ucmd!();
3682 at.write("first", "1");
3683 at.write("second", "2");
3684
3685 ucmd.arg("--exchange")
3686 .arg("-v")
3687 .arg("first")
3688 .arg("second")
3689 .succeeds()
3690 .stdout_contains("exchanged");
3691
3692 assert_eq!(at.read("first"), "2");
3693 assert_eq!(at.read("second"), "1");
3694 }
3695
3696 #[cfg(any(target_os = "linux", target_os = "android"))]
3697 #[test]
3698 fn test_mv_exchange_wrong_operand_count() {
3699 let scene = TestScenario::new(util_name!());
3700 scene.fixtures.write("only", "x");
3701
3702 // A single operand is rejected (clap itself requires at least 2 <files> values).
3703 scene
3704 .ucmd()
3705 .arg("--exchange")
3706 .arg("only")
3707 .fails()
3708 .code_is(1)
3709 .stderr_contains("requires at least 2 values");
3710
3711 // Three or more operands are rejected when the last one isn't a directory.
3712 scene.fixtures.write("two", "y");
3713 scene.fixtures.write("three", "z");
3714 scene
3715 .ucmd()
3716 .arg("--exchange")
3717 .arg("only")
3718 .arg("two")
3719 .arg("three")
3720 .fails()
3721 .code_is(1)
3722 .stderr_contains("target directory")
3723 .stderr_contains("Not a directory");
3724 }
3725
3726 #[cfg(any(target_os = "linux", target_os = "android"))]
3727 #[test]
3728 fn test_mv_exchange_multiple_operands_into_directory() {
3729 let (at, mut ucmd) = at_and_ucmd!();
3730 at.write("a", "src-a");
3731 at.write("b", "src-b");
3732 at.write("c", "src-c");
3733 at.mkdir("myfolder");
3734 at.write("myfolder/a", "dst-a");
3735 at.write("myfolder/b", "dst-b");
3736 at.write("myfolder/c", "dst-c");
3737
3738 ucmd.arg("--exchange")
3739 .arg("-v")
3740 .arg("a")
3741 .arg("b")
3742 .arg("c")
3743 .arg("myfolder/")
3744 .succeeds()
3745 .stdout_contains("exchanged 'a' <-> 'myfolder/a'")
3746 .stdout_contains("exchanged 'b' <-> 'myfolder/b'")
3747 .stdout_contains("exchanged 'c' <-> 'myfolder/c'");
3748
3749 assert_eq!(at.read("a"), "dst-a");
3750 assert_eq!(at.read("b"), "dst-b");
3751 assert_eq!(at.read("c"), "dst-c");
3752 assert_eq!(at.read("myfolder/a"), "src-a");
3753 assert_eq!(at.read("myfolder/b"), "src-b");
3754 assert_eq!(at.read("myfolder/c"), "src-c");
3755 }
3756
3757 #[cfg(any(target_os = "linux", target_os = "android"))]
3758 #[test]
3759 fn test_mv_exchange_same_file() {
3760 let (at, mut ucmd) = at_and_ucmd!();
3761 at.write("only", "data");
3762
3763 ucmd.arg("--exchange")
3764 .arg("only")
3765 .arg("only")
3766 .fails()
3767 .code_is(1)
3768 .stderr_contains("are the same file");
3769
3770 assert_eq!(at.read("only"), "data");
3771 }
3772
3773 #[cfg(not(any(target_os = "linux", target_os = "android")))]
3774 #[test]
3775 fn test_mv_exchange_not_supported() {
3776 let (at, mut ucmd) = at_and_ucmd!();
3777 at.write("left", "L");
3778 at.write("right", "R");
3779
3780 ucmd.arg("--exchange")
3781 .arg("left")
3782 .arg("right")
3783 .fails()
3784 .code_is(1)
3785 .stderr_contains("not supported");
3786
3787 assert_eq!(at.read("left"), "L");
3788 assert_eq!(at.read("right"), "R");
3789 }
3790
3791 #[cfg(any(target_os = "linux", target_os = "android"))]
3792 #[test]
3793 fn test_mv_exchange_missing_target() {
3794 let (at, mut ucmd) = at_and_ucmd!();
3795 at.write("present", "data");
3796
3797 ucmd.arg("--exchange")
3798 .arg("present")
3799 .arg("absent")
3800 .fails()
3801 .code_is(1)
3802 .stderr_contains("cannot move")
3803 .stderr_contains("present")
3804 .stderr_contains("absent");
3805 }