Debian Codegraph @

tests/by-util/test_ls.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore (words) READMECAREFULLY birthtime doesntexist oneline somebackup lrwx somefile somegroup somehiddenbackup somehiddenfile tabsize aaaaaaaa bbbb cccc dddddddd ncccc neee naaaaa nbcdef nfffff dired subdired tmpfs mdir COLORTERM mexe bcdef mfoo timefile
7 // spell-checker:ignore (words) fakeroot setcap drwxr bcdlps mdangling mentry awith acolons NOFILE NOTCAPABLE
8 #![allow(
9 clippy::similar_names,
10 clippy::too_many_lines,
11 clippy::cast_possible_truncation
12 )]
13
14 use regex::Regex;
15 #[cfg(unix)]
16 use rlimit::Resource;
17 #[cfg(not(target_os = "openbsd"))]
18 use std::collections::HashMap;
19 #[cfg(target_os = "linux")]
20 use std::ffi::OsStr;
21 #[cfg(target_os = "linux")]
22 use std::os::unix::ffi::OsStrExt;
23 #[cfg(not(windows))]
24 use std::path::PathBuf;
25 use std::thread::sleep;
26 use std::time::Duration;
27 use std::{path::Path, time::SystemTime};
28 use uutests::new_ucmd;
29 #[cfg(unix)]
30 use uutests::unwrap_or_return;
31 use uutests::util::TestScenario;
32 #[cfg(any(unix, feature = "selinux"))]
33 use uutests::util::expected_result;
34 use uutests::{at_and_ucmd, util_name};
35
36 const LONG_ARGS: &[&str] = &[
37 "-l",
38 "--long",
39 "--format=long",
40 "--format=lon",
41 "--for=long",
42 "--format=verbose",
43 "--for=verbose",
44 ];
45
46 const ACROSS_ARGS: &[&str] = &[
47 "-x",
48 "--format=across",
49 "--format=acr",
50 "--format=horizontal",
51 "--for=across",
52 "--for=horizontal",
53 ];
54
55 const COMMA_ARGS: &[&str] = &["-m", "--format=commas", "--for=commas"];
56
57 const COLUMN_ARGS: &[&str] = &["-C", "--format=columns", "--for=columns"];
58
59 #[test]
60 #[cfg(unix)]
61 fn test_directory_in_file() {
62 let scene = TestScenario::new(util_name!());
63 let at = &scene.fixtures;
64 at.touch("file");
65
66 scene
67 .ucmd()
68 .arg("file/missing")
69 .fails_with_code(2)
70 .stderr_is("ls: cannot access 'file/missing': Not a directory\n");
71 }
72
73 #[test]
74 fn test_invalid_flag() {
75 new_ucmd!()
76 .arg("--invalid-argument")
77 .fails_with_code(2)
78 .no_stdout();
79 }
80
81 #[test]
82 fn test_invalid_value_returns_1() {
83 // Invalid values to flags *sometimes* result in error code 1:
84 for flag in [
85 "--classify",
86 "--color",
87 "--format",
88 "--hyperlink",
89 "--indicator-style",
90 "--quoting-style",
91 "--sort",
92 "--time",
93 ] {
94 new_ucmd!()
95 .arg(format!("{flag}=definitely_invalid_value"))
96 .fails_with_code(1)
97 .no_stdout();
98 }
99 }
100
101 /* spellchecker: disable */
102 #[test]
103 fn test_localized_possible_values() {
104 let test_cases = vec![
105 (
106 "en_US.UTF-8",
107 vec![
108 "error: invalid value 'invalid_test_value' for '--color",
109 "[possible values:",
110 ],
111 ),
112 (
113 "fr_FR.UTF-8",
114 vec![
115 "erreur : valeur invalide 'invalid_test_value' pour '--color",
116 "[valeurs possibles:",
117 ],
118 ),
119 ];
120
121 for (locale, expected_strings) in test_cases {
122 let result = new_ucmd!()
123 .env("LANG", locale)
124 .env("LC_ALL", locale)
125 .arg("--color=invalid_test_value")
126 .fails();
127
128 result.code_is(1);
129 let stderr = result.stderr_str();
130 for expected in expected_strings {
131 assert!(stderr.contains(expected));
132 }
133 }
134 }
135 /* spellchecker: enable */
136
137 #[test]
138 fn test_invalid_value_returns_2() {
139 // Invalid values to flags *sometimes* result in error code 2:
140 for flag in ["--block-size", "--width", "--tab-size"] {
141 new_ucmd!()
142 .arg(format!("{flag}=definitely_invalid_value"))
143 .fails_with_code(2)
144 .no_stdout();
145 }
146 }
147
148 #[test]
149 fn test_invalid_value_time_style() {
150 // This is the only flag which does not raise an error if it is invalid but not actually used:
151 new_ucmd!()
152 .arg("--time-style=definitely_invalid_value")
153 .succeeds()
154 .no_stderr();
155 // If it is used, error:
156 new_ucmd!()
157 .arg("-g")
158 .arg("--time-style=definitely_invalid_value")
159 .fails_with_code(2)
160 .stderr_contains("time-style argument 'definitely_invalid_value'")
161 .no_stdout();
162 // If it only looks temporarily like it might be used, no error:
163 new_ucmd!()
164 .arg("-l")
165 .arg("--time-style=definitely_invalid_value")
166 .arg("--format=single-column")
167 .succeeds()
168 .no_stderr();
169 }
170
171 #[test]
172 fn test_time_style_empty_after_posix_prefix() {
173 new_ucmd!()
174 .arg("-l")
175 .arg("--time-style=posix-")
176 .fails_with_code(2)
177 .stderr_contains("ls: invalid --time-style argument ''");
178 }
179
180 #[test]
181 fn test_ls_ls() {
182 new_ucmd!().succeeds();
183 }
184
185 #[test]
186 fn test_ls_help() {
187 // Because we have to work around a lot of clap's error handling and
188 // modify the exit-code, this is actually non-trivial.
189 new_ucmd!()
190 .arg("--help")
191 .succeeds()
192 .stdout_contains("--version")
193 .no_stderr();
194 }
195
196 #[test]
197 fn test_ls_i() {
198 new_ucmd!().arg("-i").succeeds();
199 new_ucmd!().arg("-il").succeeds();
200 }
201
202 #[test]
203 fn test_ls_ordering() {
204 let scene = TestScenario::new(util_name!());
205 let at = &scene.fixtures;
206 at.mkdir("some-dir1");
207 at.mkdir("some-dir2");
208 at.mkdir("some-dir3");
209 at.mkdir("some-dir4");
210 at.mkdir("some-dir5");
211 at.mkdir("some-dir6");
212
213 scene
214 .ucmd()
215 .arg("-Rl")
216 .succeeds()
217 .stdout_matches(&Regex::new("some-dir1:\\ntotal 0").unwrap());
218 }
219
220 #[cfg(all(
221 unix,
222 feature = "df",
223 not(any(target_os = "freebsd", target_os = "openbsd"))
224 ))]
225 fn get_filesystem_type(scene: &TestScenario, path: &Path) -> String {
226 let mut cmd = scene.ccmd("df");
227 cmd.args(&["-PT"]).arg(path);
228 let output = cmd.succeeds();
229 let stdout_str = String::from_utf8_lossy(output.stdout());
230 println!("output of stat call ({cmd:?}):\n{stdout_str}");
231 let regex_str = r"Filesystem\s+Type\s+.+[\r\n]+([^\s]+)\s+(?<fstype>[^\s]+)\s+";
232 let regex = Regex::new(regex_str).unwrap();
233 let m = regex.captures(&stdout_str).unwrap();
234 let fstype = m["fstype"].to_owned();
235 println!("detected fstype: {fstype}");
236 fstype
237 }
238
239 #[cfg(all(feature = "truncate", feature = "dd"))]
240 #[test] // FIXME: fix this test for FreeBSD and OpenBSD
241 #[cfg(not(target_os = "openbsd"))]
242 fn test_ls_allocation_size() {
243 let scene = TestScenario::new(util_name!());
244 let at = &scene.fixtures;
245 at.mkdir("some-dir1");
246 at.touch("some-dir1/empty-file");
247
248 #[cfg(all(unix, feature = "df"))]
249 {
250 scene
251 .ccmd("truncate")
252 .arg("-s")
253 .arg("4M")
254 .arg("some-dir1/file-with-holes")
255 .succeeds();
256
257 // fill empty file with zeros
258 scene
259 .ccmd("dd")
260 .arg("if=/dev/zero")
261 .arg("of=some-dir1/zero-file")
262 .arg("bs=1024")
263 .arg("count=4096")
264 .succeeds();
265
266 scene
267 .ccmd("dd")
268 .arg("if=/dev/zero")
269 .arg("of=irregular-file")
270 .arg("bs=1")
271 .arg("count=777")
272 .succeeds();
273
274 scene
275 .ucmd()
276 .arg("-l")
277 .arg("--block-size=512")
278 .arg("irregular-file")
279 .succeeds()
280 .stdout_matches(&Regex::new("[^ ] 2 [^ ]").unwrap());
281
282 #[cfg(not(target_os = "freebsd"))]
283 let (zero_file_size_4k, zero_file_size_1k, zero_file_size_8k, zero_file_size_4m) =
284 match get_filesystem_type(&scene, &scene.fixtures.subdir).as_str() {
285 // apparently f2fs (flash friendly fs) accepts small overhead for better performance
286 "f2fs" => (4100, 1025, 8200, "4.1M"),
287 _ => (4096, 1024, 8192, "4.0M"),
288 };
289
290 #[cfg(not(target_os = "freebsd"))]
291 scene
292 .ucmd()
293 .arg("-s1")
294 .arg("some-dir1")
295 .succeeds()
296 .stdout_is(format!(
297 "total {zero_file_size_4k}\n 0 empty-file\n 0 file-with-holes\n\
298 {zero_file_size_4k} zero-file\n"
299 ));
300
301 scene
302 .ucmd()
303 .arg("-sl")
304 .arg("some-dir1")
305 .succeeds()
306 // block size is 0 whereas size/len is 4194304
307 .stdout_contains("4194304");
308
309 #[cfg(not(target_os = "freebsd"))]
310 scene
311 .ucmd()
312 .arg("-s1")
313 .arg("some-dir1")
314 .succeeds()
315 .stdout_contains("0 empty-file")
316 .stdout_contains(format!("{zero_file_size_4k} zero-file"));
317
318 // Test alignment of different block sized files
319 let res = scene.ucmd().arg("-si1").arg("some-dir1").succeeds();
320
321 let empty_file_len = String::from_utf8(res.stdout().to_owned())
322 .ok()
323 .unwrap()
324 .lines()
325 .nth(1)
326 .unwrap()
327 .strip_suffix("empty-file")
328 .unwrap()
329 .len();
330
331 let file_with_holes_len = String::from_utf8(res.stdout().to_owned())
332 .ok()
333 .unwrap()
334 .lines()
335 .nth(2)
336 .unwrap()
337 .strip_suffix("file-with-holes")
338 .unwrap()
339 .len();
340
341 assert_eq!(empty_file_len, file_with_holes_len);
342
343 #[cfg(not(target_os = "freebsd"))]
344 scene
345 .ucmd()
346 .env("LS_BLOCK_SIZE", "8K")
347 .env("BLOCK_SIZE", "4K")
348 .arg("-s1")
349 .arg("some-dir1")
350 .succeeds()
351 .stdout_contains("total 512")
352 .stdout_contains("0 empty-file")
353 .stdout_contains("0 file-with-holes")
354 .stdout_contains("512 zero-file");
355
356 #[cfg(not(target_os = "freebsd"))]
357 scene
358 .ucmd()
359 .env("BLOCK_SIZE", "4K")
360 .arg("-s1")
361 .arg("some-dir1")
362 .succeeds()
363 .stdout_contains(format!("total {zero_file_size_1k}"))
364 .stdout_contains("0 empty-file")
365 .stdout_contains("0 file-with-holes")
366 .stdout_contains(format!("{zero_file_size_1k} zero-file"));
367
368 #[cfg(not(target_os = "freebsd"))]
369 scene
370 .ucmd()
371 .env("BLOCK_SIZE", "4K")
372 .arg("-s1")
373 .arg("--si")
374 .arg("some-dir1")
375 .succeeds()
376 .stdout_contains("total 4.2M")
377 .stdout_contains("0 empty-file")
378 .stdout_contains("0 file-with-holes")
379 .stdout_contains("4.2M zero-file");
380
381 #[cfg(not(target_os = "freebsd"))]
382 scene
383 .ucmd()
384 .env("BLOCK_SIZE", "4096")
385 .arg("-s1")
386 .arg("some-dir1")
387 .succeeds()
388 .stdout_contains(format!("total {zero_file_size_1k}"))
389 .stdout_contains("0 empty-file")
390 .stdout_contains("0 file-with-holes")
391 .stdout_contains(format!("{zero_file_size_1k} zero-file"));
392
393 #[cfg(not(target_os = "freebsd"))]
394 scene
395 .ucmd()
396 .env("POSIXLY_CORRECT", "true")
397 .arg("-s1")
398 .arg("some-dir1")
399 .succeeds()
400 .stdout_contains(format!("total {zero_file_size_8k}"))
401 .stdout_contains("0 empty-file")
402 .stdout_contains("0 file-with-holes")
403 .stdout_contains(format!("{zero_file_size_8k} zero-file"));
404
405 // -k should make 'ls' ignore the env var
406 #[cfg(not(target_os = "freebsd"))]
407 scene
408 .ucmd()
409 .env("BLOCK_SIZE", "4K")
410 .arg("-s1k")
411 .arg("some-dir1")
412 .succeeds()
413 .stdout_contains(format!("total {zero_file_size_4k}"))
414 .stdout_contains("0 empty-file")
415 .stdout_contains("0 file-with-holes")
416 .stdout_contains(format!("{zero_file_size_4k} zero-file"));
417
418 // but manually specified blocksize overrides -k
419 #[cfg(not(target_os = "freebsd"))]
420 scene
421 .ucmd()
422 .arg("-s1k")
423 .arg("--block-size=4K")
424 .arg("some-dir1")
425 .succeeds()
426 .stdout_contains(format!("total {zero_file_size_1k}"))
427 .stdout_contains("0 empty-file")
428 .stdout_contains("0 file-with-holes")
429 .stdout_contains(format!("{zero_file_size_1k} zero-file"));
430
431 #[cfg(not(target_os = "freebsd"))]
432 scene
433 .ucmd()
434 .arg("-s1")
435 .arg("--block-size=4K")
436 .arg("some-dir1")
437 .succeeds()
438 .stdout_contains(format!("total {zero_file_size_1k}"))
439 .stdout_contains("0 empty-file")
440 .stdout_contains("0 file-with-holes")
441 .stdout_contains(format!("{zero_file_size_1k} zero-file"));
442
443 // si option should always trump the human-readable option
444 #[cfg(not(target_os = "freebsd"))]
445 scene
446 .ucmd()
447 .arg("-s1h")
448 .arg("--si")
449 .arg("some-dir1")
450 .succeeds()
451 .stdout_contains("total 4.2M")
452 .stdout_contains("0 empty-file")
453 .stdout_contains("0 file-with-holes")
454 .stdout_contains("4.2M zero-file");
455
456 #[cfg(not(target_os = "freebsd"))]
457 scene
458 .ucmd()
459 .arg("-s1")
460 .arg("--block-size=human-readable")
461 .arg("some-dir1")
462 .succeeds()
463 .stdout_contains(format!("total {zero_file_size_4m}"))
464 .stdout_contains("0 empty-file")
465 .stdout_contains("0 file-with-holes")
466 .stdout_contains(format!("{zero_file_size_4m} zero-file"));
467
468 #[cfg(not(target_os = "freebsd"))]
469 scene
470 .ucmd()
471 .arg("-s1")
472 .arg("--block-size=si")
473 .arg("some-dir1")
474 .succeeds()
475 .stdout_contains("total 4.2M")
476 .stdout_contains("0 empty-file")
477 .stdout_contains("0 file-with-holes")
478 .stdout_contains("4.2M zero-file");
479 }
480 }
481
482 #[test]
483 fn test_ls_devices() {
484 let scene = TestScenario::new(util_name!());
485 let at = &scene.fixtures;
486 at.mkdir("some-dir1");
487
488 // Regex tests correct device ID and correct (no pad) spacing for a single file
489 #[cfg(target_vendor = "apple")]
490 {
491 scene
492 .ucmd()
493 .arg("-al")
494 .arg("/dev/null")
495 .succeeds()
496 .stdout_matches(&Regex::new("[^ ] 3, 2 [^ ]").unwrap());
497 }
498
499 #[cfg(any(target_os = "linux", target_os = "android"))]
500 {
501 scene
502 .ucmd()
503 .arg("-al")
504 .arg("/dev/null")
505 .succeeds()
506 .stdout_matches(&Regex::new("[^ ] 1, 3 [^ ]").unwrap());
507 }
508
509 // Tests display alignment against a file (stdout is a link to a tty)
510 #[cfg(unix)]
511 {
512 #[cfg(not(target_os = "android"))]
513 let stdout = "/dev/stdout";
514 #[cfg(target_os = "android")]
515 let stdout = "/proc/self/fd/1";
516 let res = scene
517 .ucmd()
518 .arg("-alL")
519 .arg("/dev/null")
520 .arg(stdout)
521 .succeeds();
522
523 let null_len = String::from_utf8(res.stdout().to_owned())
524 .ok()
525 .unwrap()
526 .lines()
527 .next()
528 .unwrap()
529 .strip_suffix("/dev/null")
530 .unwrap()
531 .len();
532
533 let stdout_len = String::from_utf8(res.stdout().to_owned())
534 .ok()
535 .unwrap()
536 .lines()
537 .nth(1)
538 .unwrap()
539 .strip_suffix(stdout)
540 .unwrap()
541 .len();
542
543 assert_eq!(stdout_len, null_len);
544 }
545 }
546
547 #[cfg(feature = "chmod")]
548 #[test]
549 fn test_ls_io_errors() {
550 let scene = TestScenario::new(util_name!());
551 let at = &scene.fixtures;
552 at.mkdir("some-dir1");
553 at.mkdir("some-dir2");
554 at.symlink_file("does_not_exist", "some-dir2/dangle");
555 at.mkdir("some-dir3");
556 at.mkdir("some-dir3/some-dir4");
557 at.mkdir("some-dir4");
558
559 scene.ccmd("chmod").arg("000").arg("some-dir1").succeeds();
560
561 scene
562 .ucmd()
563 .arg("-1")
564 .arg("some-dir1")
565 .fails_with_code(2)
566 .stderr_contains("cannot open directory")
567 .stderr_contains("Permission denied");
568
569 scene
570 .ucmd()
571 .arg("-Li")
572 .arg("some-dir2")
573 .fails_with_code(1)
574 .stderr_contains("cannot access")
575 .stderr_contains("No such file or directory")
576 .stdout_contains(if cfg!(windows) { "dangle" } else { "? dangle" });
577
578 scene
579 .ccmd("chmod")
580 .arg("000")
581 .arg("some-dir3/some-dir4")
582 .succeeds();
583
584 scene
585 .ucmd()
586 .arg("-laR")
587 .arg("some-dir3")
588 .fails_with_code(1)
589 .stderr_contains("some-dir4")
590 .stderr_contains("cannot open directory")
591 .stderr_contains("Permission denied")
592 .stdout_contains("some-dir4");
593
594 // don't double print on dangling link metadata errors
595 scene
596 .ucmd()
597 .arg("-iRL")
598 .arg("some-dir2")
599 .fails()
600 .stderr_does_not_contain(
601 "ls: cannot access 'some-dir2/dangle': No such file or directory\nls: cannot access 'some-dir2/dangle': No such file or directory"
602 );
603
604 #[cfg(unix)]
605 {
606 use std::os::fd::AsRawFd;
607
608 at.touch("some-dir4/bad-fd.txt");
609 let fd1 = at.open("some-dir4/bad-fd.txt");
610 let fd2 = rustix::io::dup(dbg!(&fd1)).unwrap();
611 drop(fd1); //close
612
613 // on the mac and in certain Linux containers bad fds are typed as dirs,
614 // however sometimes bad fds are typed as links and directory entry on links won't fail
615 if PathBuf::from(format!("/dev/fd/{}", fd2.as_raw_fd())).is_dir() {
616 scene
617 .ucmd()
618 .arg("-alR")
619 .arg(format!("/dev/fd/{}", fd2.as_raw_fd()))
620 .fails()
621 .stderr_contains(format!(
622 "cannot open directory '/dev/fd/{}': Bad file descriptor",
623 fd2.as_raw_fd()
624 ))
625 .stdout_does_not_contain(format!("{}:\n", fd2.as_raw_fd()));
626
627 scene
628 .ucmd()
629 .arg("-RiL")
630 .arg(format!("/dev/fd/{}", fd2.as_raw_fd()))
631 .fails()
632 .stderr_contains(format!("cannot open directory '/dev/fd/{}': Bad file descriptor", fd2.as_raw_fd()))
633 // don't double print bad fd errors
634 .stderr_does_not_contain(format!("ls: cannot open directory '/dev/fd/{0}': Bad file descriptor\nls: cannot open directory '/dev/fd/{0}': Bad file descriptor", fd2.as_raw_fd()));
635 } else {
636 scene
637 .ucmd()
638 .arg("-alR")
639 .arg(format!("/dev/fd/{}", fd2.as_raw_fd()))
640 .succeeds();
641
642 scene
643 .ucmd()
644 .arg("-RiL")
645 .arg(format!("/dev/fd/{}", fd2.as_raw_fd()))
646 .succeeds();
647 }
648
649 scene
650 .ucmd()
651 .arg("-alL")
652 .arg(format!("/dev/fd/{}", fd2.as_raw_fd()))
653 .succeeds();
654
655 drop(fd2); //close
656 }
657 }
658
659 #[test]
660 fn test_ls_only_dirs_formatting() {
661 let scene = TestScenario::new(util_name!());
662 let at = &scene.fixtures;
663 at.mkdir("some-dir1");
664 at.mkdir("some-dir2");
665 at.mkdir("some-dir3");
666
667 #[cfg(unix)]
668 {
669 scene.ucmd().arg("-1").arg("-R").succeeds().stdout_only(
670 ".:\nsome-dir1\nsome-dir2\nsome-dir3\n\n./some-dir1:\n\n./some-dir2:\n\n./some-dir3:\n",
671 );
672 }
673 #[cfg(windows)]
674 {
675 scene.ucmd().arg("-1").arg("-R").succeeds().stdout_only(
676 ".:\nsome-dir1\nsome-dir2\nsome-dir3\n\n.\\some-dir1:\n\n.\\some-dir2:\n\n.\\some-dir3:\n",
677 );
678 }
679 }
680
681 #[test]
682 fn test_ls_walk_glob() {
683 let scene = TestScenario::new(util_name!());
684 let at = &scene.fixtures;
685 at.touch(".test-1");
686 at.mkdir("some-dir");
687 at.touch(
688 Path::new("some-dir")
689 .join("test-2~")
690 .as_os_str()
691 .to_str()
692 .unwrap(),
693 );
694
695 #[allow(clippy::trivial_regex)]
696 let re_pwd = Regex::new(r"^\.\n").unwrap();
697
698 scene
699 .ucmd()
700 .arg("-1")
701 .arg("--ignore-backups")
702 .arg("some-dir")
703 .succeeds()
704 .stdout_does_not_contain("test-2~")
705 .stdout_does_not_contain("..")
706 .stdout_does_not_match(&re_pwd);
707 }
708
709 #[test]
710 #[cfg(unix)]
711 fn test_ls_a() {
712 let scene = TestScenario::new(util_name!());
713 let at = &scene.fixtures;
714 at.touch(".test-1");
715 at.mkdir("some-dir");
716 at.touch(
717 Path::new("some-dir")
718 .join(".test-2")
719 .as_os_str()
720 .to_str()
721 .unwrap(),
722 );
723
724 #[allow(clippy::trivial_regex)]
725 let re_pwd = Regex::new(r"^\.\n").unwrap();
726
727 // Using the present working directory
728 scene
729 .ucmd()
730 .arg("-1")
731 .succeeds()
732 .stdout_does_not_contain(".test-1")
733 .stdout_does_not_contain("..")
734 .stdout_does_not_match(&re_pwd);
735
736 scene
737 .ucmd()
738 .arg("-a")
739 .arg("-1")
740 .succeeds()
741 .stdout_contains(".test-1")
742 .stdout_contains("..")
743 .stdout_matches(&re_pwd);
744
745 scene
746 .ucmd()
747 .arg("-A")
748 .arg("-1")
749 .succeeds()
750 .stdout_contains(".test-1")
751 .stdout_does_not_contain("..")
752 .stdout_does_not_match(&re_pwd);
753
754 // Using a subdirectory
755 scene
756 .ucmd()
757 .arg("-1")
758 .arg("some-dir")
759 .succeeds()
760 .stdout_does_not_contain(".test-2")
761 .stdout_does_not_contain("..")
762 .stdout_does_not_match(&re_pwd);
763
764 scene
765 .ucmd()
766 .arg("-a")
767 .arg("-1")
768 .arg("some-dir")
769 .succeeds()
770 .stdout_contains(".test-2")
771 .stdout_contains("..")
772 .no_stderr()
773 .stdout_matches(&re_pwd);
774
775 scene
776 .ucmd()
777 .arg("-A")
778 .arg("-1")
779 .arg("some-dir")
780 .succeeds()
781 .stdout_contains(".test-2")
782 .stdout_does_not_contain("..")
783 .stdout_does_not_match(&re_pwd);
784 }
785
786 #[test]
787 fn test_ls_width() {
788 let scene = TestScenario::new(util_name!());
789 let at = &scene.fixtures;
790 at.touch(at.plus_as_string("test-width-1"));
791 at.touch(at.plus_as_string("test-width-2"));
792 at.touch(at.plus_as_string("test-width-3"));
793 at.touch(at.plus_as_string("test-width-4"));
794
795 for option in [
796 "-w 100",
797 "-w=100",
798 "--width=100",
799 "--width 100",
800 "--wid=100",
801 ] {
802 scene
803 .ucmd()
804 .args(&option.split(' ').collect::<Vec<_>>())
805 .arg("-C")
806 .succeeds()
807 .stdout_only("test-width-1 test-width-2 test-width-3 test-width-4\n");
808 }
809
810 for option in ["-w 50", "-w=50", "--width=50", "--width 50", "--wid=50"] {
811 scene
812 .ucmd()
813 .args(&option.split(' ').collect::<Vec<_>>())
814 .arg("-C")
815 .succeeds()
816 .stdout_only("test-width-1 test-width-3\ntest-width-2 test-width-4\n");
817 }
818
819 for option in ["-w 25", "-w=25", "--width=25", "--width 25", "--wid=25"] {
820 scene
821 .ucmd()
822 .args(&option.split(' ').collect::<Vec<_>>())
823 .arg("-C")
824 .succeeds()
825 .stdout_only("test-width-1\ntest-width-2\ntest-width-3\ntest-width-4\n");
826 }
827
828 for option in ["-w 0", "-w=0", "--width=0", "--width 0", "--wid=0"] {
829 scene
830 .ucmd()
831 .args(&option.split(' ').collect::<Vec<_>>())
832 .arg("-C")
833 .succeeds()
834 .stdout_only("test-width-1 test-width-2 test-width-3 test-width-4\n");
835 }
836
837 for option in [
838 "-w 062",
839 "-w=062",
840 "--width=062",
841 "--width 062",
842 "--wid=062",
843 ] {
844 scene
845 .ucmd()
846 .args(&option.split(' ').collect::<Vec<_>>())
847 .arg("-C")
848 .succeeds()
849 .stdout_only("test-width-1 test-width-3\ntest-width-2 test-width-4\n");
850 }
851
852 for option in [
853 "-w 100000000000000",
854 "-w=100000000000000",
855 "--width=100000000000000",
856 "--width 100000000000000",
857 "-w 07777777777777777777",
858 "-w=07777777777777777777",
859 "--width=07777777777777777777",
860 "--width 07777777777777777777",
861 ] {
862 scene
863 .ucmd()
864 .args(&option.split(' ').collect::<Vec<_>>())
865 .arg("-C")
866 .succeeds()
867 .stdout_only("test-width-1 test-width-2 test-width-3 test-width-4\n");
868 }
869 scene
870 .ucmd()
871 .arg("-w=bad")
872 .arg("-C")
873 .fails()
874 .stderr_contains("invalid line width");
875
876 for option in ["-w 1a", "-w=1a", "--width=1a", "--width 1a", "--wid 1a"] {
877 scene
878 .ucmd()
879 .args(&option.split(' ').collect::<Vec<_>>())
880 .arg("-C")
881 .fails()
882 .stderr_only("ls: invalid line width: '1a'\n");
883 }
884 }
885
886 #[test]
887 fn test_ls_columns() {
888 let scene = TestScenario::new(util_name!());
889 let at = &scene.fixtures;
890 at.touch(at.plus_as_string("test-columns-1"));
891 at.touch(at.plus_as_string("test-columns-2"));
892 at.touch(at.plus_as_string("test-columns-3"));
893 at.touch(at.plus_as_string("test-columns-4"));
894
895 // Columns is the default
896 let result = scene.ucmd().succeeds();
897
898 result.stdout_only("test-columns-1\ntest-columns-2\ntest-columns-3\ntest-columns-4\n");
899
900 for option in COLUMN_ARGS {
901 let result = scene.ucmd().arg(option).succeeds();
902 result.stdout_only("test-columns-1\ttest-columns-2\ttest-columns-3\ttest-columns-4\n");
903 }
904
905 for option in COLUMN_ARGS {
906 scene
907 .ucmd()
908 .arg("-w=40")
909 .arg(option)
910 .succeeds()
911 .stdout_only("test-columns-1\ttest-columns-3\ntest-columns-2\ttest-columns-4\n");
912 }
913
914 // On windows we are always able to get the terminal size, so we can't simulate falling back to the
915 // environment variable.
916 #[cfg(not(windows))]
917 {
918 for option in COLUMN_ARGS {
919 scene
920 .ucmd()
921 .env("COLUMNS", "40")
922 .arg(option)
923 .succeeds()
924 .stdout_only("test-columns-1\ttest-columns-3\ntest-columns-2\ttest-columns-4\n");
925 }
926
927 scene
928 .ucmd()
929 .env("COLUMNS", "garbage")
930 .arg("-C")
931 .succeeds()
932 .stdout_is("test-columns-1\ttest-columns-2\ttest-columns-3\ttest-columns-4\n")
933 .stderr_is("ls: ignoring invalid width in environment variable COLUMNS: 'garbage'\n");
934 }
935 scene
936 .ucmd()
937 .arg("-Cw0")
938 .succeeds()
939 .stdout_only("test-columns-1 test-columns-2 test-columns-3 test-columns-4\n");
940 scene
941 .ucmd()
942 .arg("-mw0")
943 .succeeds()
944 .stdout_only("test-columns-1, test-columns-2, test-columns-3, test-columns-4\n");
945 }
946
947 #[test]
948 fn test_ls_across() {
949 let scene = TestScenario::new(util_name!());
950 let at = &scene.fixtures;
951 at.touch(at.plus_as_string("test-across-1"));
952 at.touch(at.plus_as_string("test-across-2"));
953 at.touch(at.plus_as_string("test-across-3"));
954 at.touch(at.plus_as_string("test-across-4"));
955
956 for option in ACROSS_ARGS {
957 let result = scene.ucmd().arg(option).succeeds();
958 // Because the test terminal has width 0, this is the same output as
959 // the columns option.
960 result.stdout_only("test-across-1 test-across-2 test-across-3 test-across-4\n");
961 }
962
963 for option in ACROSS_ARGS {
964 // Because the test terminal has width 0, this is the same output as
965 // the columns option.
966 scene
967 .ucmd()
968 .arg("-w=30")
969 .arg(option)
970 .succeeds()
971 .stdout_only("test-across-1 test-across-2\ntest-across-3 test-across-4\n");
972 }
973 }
974
975 #[test]
976 fn test_ls_commas() {
977 let scene = TestScenario::new(util_name!());
978 let at = &scene.fixtures;
979 at.touch(at.plus_as_string("test-commas-1"));
980 at.touch(at.plus_as_string("test-commas-2"));
981 at.touch(at.plus_as_string("test-commas-3"));
982 at.touch(at.plus_as_string("test-commas-4"));
983
984 for option in COMMA_ARGS {
985 let result = scene.ucmd().arg(option).succeeds();
986 result.stdout_only("test-commas-1, test-commas-2, test-commas-3, test-commas-4\n");
987 }
988
989 for option in COMMA_ARGS {
990 scene
991 .ucmd()
992 .arg("-w=30")
993 .arg(option)
994 .succeeds()
995 .stdout_only("test-commas-1, test-commas-2,\ntest-commas-3, test-commas-4\n");
996 }
997 for option in COMMA_ARGS {
998 scene
999 .ucmd()
1000 .arg("-w=45")
1001 .arg(option)
1002 .succeeds()
1003 .stdout_only("test-commas-1, test-commas-2, test-commas-3,\ntest-commas-4\n");
1004 }
1005 }
1006
1007 #[test]
1008 fn test_ls_zero() {
1009 let scene = TestScenario::new(util_name!());
1010 let at = &scene.fixtures;
1011 at.mkdir("0-test-zero");
1012 at.touch(at.plus_as_string("2-test-zero"));
1013 at.touch(at.plus_as_string("3-test-zero"));
1014
1015 let ignored_opts = [
1016 "--quoting-style=c",
1017 "--color=always",
1018 "-m",
1019 "--hide-control-chars",
1020 ];
1021
1022 scene
1023 .ucmd()
1024 .arg("--zero")
1025 .succeeds()
1026 .stdout_only("0-test-zero\x002-test-zero\x003-test-zero\x00");
1027
1028 for opt in ignored_opts {
1029 scene
1030 .ucmd()
1031 .args(&[opt, "--zero"])
1032 .succeeds()
1033 .stdout_only("0-test-zero\x002-test-zero\x003-test-zero\x00");
1034 }
1035
1036 scene
1037 .ucmd()
1038 .args(&["--zero", "--quoting-style=c"])
1039 .succeeds()
1040 .stdout_only("\"0-test-zero\"\x00\"2-test-zero\"\x00\"3-test-zero\"\x00");
1041
1042 let result = scene.ucmd().args(&["--zero", "--color=always"]).succeeds();
1043 assert_eq!(
1044 result.stdout_str(),
1045 "\u{1b}[0m\u{1b}[01;34m0-test-zero\x1b[0m\x002-test-zero\x003-test-zero\x00"
1046 );
1047
1048 scene
1049 .ucmd()
1050 .args(&["--zero", "-m"])
1051 .succeeds()
1052 .stdout_only("0-test-zero, 2-test-zero, 3-test-zero\x00");
1053
1054 scene
1055 .ucmd()
1056 .args(&["--zero", "--hide-control-chars"])
1057 .succeeds()
1058 .stdout_only("0-test-zero\x002-test-zero\x003-test-zero\x00");
1059
1060 scene
1061 .ucmd()
1062 .args(&["--zero", "--quoting-style=c", "--zero"])
1063 .succeeds()
1064 .stdout_only("0-test-zero\x002-test-zero\x003-test-zero\x00");
1065
1066 #[cfg(unix)]
1067 {
1068 at.touch(at.plus_as_string("1\ntest-zero"));
1069
1070 let ignored_opts = [
1071 "--quoting-style=c",
1072 "--color=always",
1073 "--color=alway",
1074 "--color=al",
1075 "-m",
1076 "--hide-control-chars",
1077 ];
1078
1079 scene
1080 .ucmd()
1081 .arg("--zero")
1082 .succeeds()
1083 .stdout_only("0-test-zero\x001\ntest-zero\x002-test-zero\x003-test-zero\x00");
1084
1085 for opt in ignored_opts {
1086 scene
1087 .ucmd()
1088 .args(&[opt, "--zero"])
1089 .succeeds()
1090 .stdout_only("0-test-zero\x001\ntest-zero\x002-test-zero\x003-test-zero\x00");
1091 }
1092
1093 scene
1094 .ucmd()
1095 .args(&["--zero", "--quoting-style=c"])
1096 .succeeds()
1097 .stdout_only(
1098 "\"0-test-zero\"\x00\"1\\ntest-zero\"\x00\"2-test-zero\"\x00\"3-test-zero\"\x00",
1099 );
1100
1101 let result = scene.ucmd().args(&["--zero", "--color=always"]).succeeds();
1102 assert_eq!(
1103 result.stdout_str(),
1104 "\u{1b}[0m\u{1b}[01;34m0-test-zero\x1b[0m\x001\ntest-zero\x002-test-zero\x003-test-zero\x00",
1105 );
1106
1107 scene
1108 .ucmd()
1109 .args(&["--zero", "-m"])
1110 .succeeds()
1111 .stdout_only("0-test-zero, 1\ntest-zero, 2-test-zero, 3-test-zero\x00");
1112
1113 scene
1114 .ucmd()
1115 .args(&["--zero", "--hide-control-chars"])
1116 .succeeds()
1117 .stdout_only("0-test-zero\x001?test-zero\x002-test-zero\x003-test-zero\x00");
1118 }
1119
1120 scene
1121 .ucmd()
1122 .args(&["-l", "--zero"])
1123 .succeeds()
1124 .stdout_contains("total ");
1125 }
1126
1127 #[test]
1128 fn test_ls_commas_trailing() {
1129 let scene = TestScenario::new(util_name!());
1130 let at = &scene.fixtures;
1131 at.touch(at.plus_as_string("test-commas-trailing-2"));
1132
1133 at.touch(at.plus_as_string("test-commas-trailing-1"));
1134 at.append(
1135 "test-commas-trailing-1",
1136 &(0..2000)
1137 .map(|x| x.to_string())
1138 .collect::<Vec<_>>()
1139 .join("\n"),
1140 );
1141
1142 scene
1143 .ucmd()
1144 .arg("-sm")
1145 .arg("./test-commas-trailing-1")
1146 .arg("./test-commas-trailing-2")
1147 .succeeds()
1148 .stdout_matches(&Regex::new(r"\S\n$").unwrap());
1149 }
1150
1151 #[test]
1152 fn test_ls_long() {
1153 let scene = TestScenario::new(util_name!());
1154 let at = &scene.fixtures;
1155 at.touch(at.plus_as_string("test-long"));
1156
1157 #[cfg(not(windows))]
1158 let regex = r"[-bcCdDlMnpPsStTx?]([r-][w-][xt-]){3}.*";
1159 #[cfg(windows)]
1160 let regex = r"[-dl](r[w-]x){3}.*";
1161
1162 let re = &Regex::new(regex).unwrap();
1163
1164 for arg in LONG_ARGS {
1165 let result = scene.ucmd().arg(arg).arg("test-long").succeeds();
1166 result.stdout_matches(re);
1167 }
1168 }
1169
1170 #[cfg(not(windows))]
1171 #[test]
1172 #[cfg(not(feature = "selinux"))]
1173 // Disabled on the SELinux runner for now
1174 fn test_ls_long_format() {
1175 let scene = TestScenario::new(util_name!());
1176 let at = &scene.fixtures;
1177 at.mkdir(at.plus_as_string("test-long-dir"));
1178 at.touch(at.plus_as_string("test-long-dir/test-long-file"));
1179 at.mkdir(at.plus_as_string("test-long-dir/test-long-dir"));
1180
1181 // Assuming sane username do not have spaces within them.
1182 // A line of the output should be:
1183 // One of the characters -bcCdDlMnpPsStTx?
1184 // rwx, with - for missing permissions, thrice.
1185 // Zero or one "." for indicating a file with security context
1186 // A number, preceded by column whitespace, and followed by a single space.
1187 // A username, currently [^ ], followed by column whitespace, twice (or thrice for Hurd).
1188 // A number, followed by a single space.
1189 // A month, followed by a single space.
1190 // A day, preceded by column whitespace, and followed by a single space.
1191 // Either a year or a time, currently [0-9:]+, preceded by column whitespace,
1192 // and followed by a single space.
1193 // Whatever comes after is irrelevant to this specific test.
1194 let re = &Regex::new(
1195 r"\n[-bcCdDlMnpPsStTx?]([r-][w-][xt-]){3}[.+]? +\d+ [^ ]+ +[^ ]+( +[^ ]+)? +\d+ [A-Z][a-z]{2} {0,2}\d{0,2} {0,2}[0-9:]+ "
1196 ).unwrap();
1197
1198 for arg in LONG_ARGS {
1199 scene
1200 .ucmd()
1201 .arg(arg)
1202 .arg("test-long-dir")
1203 .succeeds()
1204 .stdout_matches(re);
1205 }
1206
1207 // This checks for the line with the .. entry. The uname and group should be digits.
1208 scene.ucmd().arg("-lan").arg("test-long-dir").succeeds().stdout_matches(&Regex::new(
1209 r"\nd([r-][w-][xt-]){3}[.+]? +\d+ \d+ +\d+( +\d+)? +\d+ [A-Z][a-z]{2} {0,2}\d{0,2} {0,2}[0-9:]+ \.\."
1210 ).unwrap());
1211 }
1212
1213 #[test]
1214 fn test_ls_long_padding_of_size_column_with_multiple_files() {
1215 let (at, mut ucmd) = at_and_ucmd!();
1216
1217 at.mkdir("dir");
1218 at.touch("dir/a");
1219 at.touch("dir/b");
1220
1221 ucmd.arg("-l")
1222 .arg("dir")
1223 .succeeds()
1224 .stdout_contains(" 0 ")
1225 .stdout_does_not_contain(" 0 ");
1226 }
1227
1228 /// This test tests `ls -laR --color`.
1229 /// This test is mainly about coloring, but, the recursion, symlink `->` processing,
1230 /// and `.` and `..` being present in `-a` all need to work for the test to pass.
1231 /// This test does not really test anything provided by `-l` but the file names and symlinks.
1232 #[cfg(all(feature = "ln", feature = "mkdir", feature = "touch"))]
1233 #[test]
1234 #[cfg(all(feature = "ln", feature = "mkdir", feature = "touch"))]
1235 #[allow(clippy::items_after_statements)]
1236 fn test_ls_long_symlink_color() {
1237 // If you break this test after breaking mkdir, touch, or ln, do not be alarmed!
1238 // This test is made for ls, but it attempts to run those utils in the process.
1239
1240 // Having Some([2, 0]) in a color basically means that "it has the same color as whatever
1241 // is in the 2nd expected output, the 0th color", where the 0th color is the name color, and
1242 // the 1st color is the target color, in a fixed-size array of size 2.
1243 // Basically these are references to be used for indexing the `colors` vector defined below.
1244 type ColorReference = Option<[usize; 2]>;
1245
1246 // The string between \x1b[ and m
1247 type Color = String;
1248
1249 // The string between the color start and the color end is the file name itself.
1250 type Name = String;
1251
1252 let scene = TestScenario::new(util_name!());
1253
1254 // .
1255 // ├── dir1
1256 // │ ├── file1
1257 // │ ├── dir2
1258 // │ │ └── dir3
1259 // │ ├── ln-dir-invalid -> dir1/dir2
1260 // │ ├── ln-up2 -> ../..
1261 // │ └── ln-root -> /
1262 // ├── ln-file1 -> dir1/file1
1263 // ├── ln-file-invalid -> dir1/invalid-target
1264 // └── ln-dir3 -> ./dir1/dir2/dir3
1265 prepare_folder_structure(&scene);
1266
1267 // We memoize the colors so we can refer to them later.
1268 // Each entry will be the colors of the link name and link target of a specific output.
1269 let mut colors: Vec<[Color; 2]> = vec![];
1270
1271 // The contents of each tuple are the expected colors and names for the link and target.
1272 // We will loop over the ls output and compare to those.
1273 // None values mean that we do not know what color to expect yet, as LS_COLOR might
1274 // be set differently, and as different implementations of ls may use different codes,
1275 // for example, our ls uses `[1;36m` while the GNU ls uses `[01;36m`.
1276 //
1277 // These have been sorting according to default ls sort, and this affects the order of
1278 // discovery of colors, so be very careful when changing directory/file names being created.
1279 let expected_output: [(ColorReference, &str, ColorReference, &str); 6] = [
1280 // We don't know what colors are what the first time we meet a link.
1281 (None, "ln-dir3", None, "./dir1/dir2/dir3"),
1282 // We have acquired [0, 0], which should be the link color,
1283 // and [0, 1], which should be the dir color, and we can compare to them from now on.
1284 (None, "ln-file-invalid", Some([1, 1]), "dir1/invalid-target"),
1285 // We acquired [1, 1], the non-existent color.
1286 (Some([0, 0]), "ln-file1", None, "dir1/file1"),
1287 (Some([1, 1]), "ln-dir-invalid", Some([1, 1]), "dir1/dir2"),
1288 (Some([0, 0]), "ln-root", Some([0, 1]), "/"),
1289 (Some([0, 0]), "ln-up2", None, "../.."),
1290 ];
1291
1292 // We are only interested in lines or the ls output that are symlinks. These start with "lrwx".
1293 // Use --file-type to ensure symlink targets are stat'd and colored
1294 let result = scene
1295 .ucmd()
1296 .arg("-laR")
1297 .arg("--color")
1298 .arg("--file-type")
1299 .arg(".")
1300 .succeeds();
1301 let mut result_lines = result
1302 .stdout_str()
1303 .lines()
1304 .filter(|line| line.starts_with("lrwx"))
1305 .enumerate();
1306
1307 // For each enumerated line, we assert that the output of ls matches the expected output.
1308 //
1309 // The unwraps within get_index_name_target will panic if a line starting lrwx does
1310 // not have `colored_name -> target` within it.
1311 while let Some((i, name, target)) = get_index_name_target(&mut result_lines) {
1312 // The unwraps within capture_colored_string will panic if the name/target's color
1313 // format is invalid.
1314 dbg!(&name);
1315 dbg!(&target);
1316 let (matched_name_color, matched_name) = capture_colored_string(&name);
1317 let (matched_target_color, matched_target) = capture_colored_string(&target);
1318
1319 colors.push([matched_name_color, matched_target_color]);
1320
1321 // We borrow them again after having moved them. This unwrap will never panic.
1322 let [matched_name_color, matched_target_color] = colors.last().unwrap();
1323
1324 // We look up the Colors that are expected in `colors` using the ColorReferences
1325 // stored in `expected_output`.
1326 let expected_name_color = expected_output[i]
1327 .0
1328 .map(|color_reference| colors[color_reference[0]][color_reference[1]].as_str());
1329 let expected_target_color = expected_output[i]
1330 .2
1331 .map(|color_reference| colors[color_reference[0]][color_reference[1]].as_str());
1332
1333 // This is the important part. The asserts inside assert_names_and_colors_are_equal
1334 // will panic if the colors or names do not match the expected colors or names.
1335 // Keep in mind an expected color `Option<&str>` of None can mean either that we
1336 // don't expect any color here, as in `expected_output[2], or don't know what specific
1337 // color to expect yet, as in expected_output[0:1].
1338 dbg!(&colors);
1339 assert_names_and_colors_are_equal(
1340 matched_name_color,
1341 expected_name_color,
1342 &matched_name,
1343 expected_output[i].1,
1344 matched_target_color,
1345 expected_target_color,
1346 &matched_target,
1347 expected_output[i].3,
1348 );
1349 }
1350
1351 // End of test, only definitions of the helper functions used above follows...
1352
1353 fn get_index_name_target<'a, I>(lines: &mut I) -> Option<(usize, Name, Name)>
1354 where
1355 I: Iterator<Item = (usize, &'a str)>,
1356 {
1357 match lines.next() {
1358 Some((c, s)) => {
1359 // `name` is whatever comes between \x1b (inclusive) and the arrow.
1360 let name = String::from("\x1b")
1361 + s.split(" -> ")
1362 .next()
1363 .unwrap()
1364 .split(" \x1b")
1365 .last()
1366 .unwrap();
1367 // `target` is whatever comes after the arrow.
1368 let target = s.split(" -> ").last().unwrap().to_string();
1369 Some((c, name, target))
1370 }
1371 None => None,
1372 }
1373 }
1374
1375 #[allow(clippy::too_many_arguments)]
1376 fn assert_names_and_colors_are_equal(
1377 name_color: &str,
1378 expected_name_color: Option<&str>,
1379 name: &str,
1380 expected_name: &str,
1381 target_color: &str,
1382 expected_target_color: Option<&str>,
1383 target: &str,
1384 expected_target: &str,
1385 ) {
1386 // Names are always compared.
1387 assert_eq!(name, expected_name);
1388 assert_eq!(target, expected_target);
1389
1390 // Colors are only compared when we have inferred what color we are looking for.
1391 if let Some(name) = expected_name_color {
1392 assert_eq!(name_color, name);
1393 }
1394 if let Some(name) = expected_target_color {
1395 assert_eq!(target_color, name);
1396 }
1397 }
1398
1399 fn capture_colored_string(input: &str) -> (Color, Name) {
1400 // Input can be:
1401 // \u{1b}[0m\u{1b}[01;36mln-dir3\u{1b}[0m
1402 // \u{1b}[0m\u{1b}[01;34m./dir1/dir2/dir3\u{1b}[0m
1403 // \u{1b}[0m\u{1b}[01;36mln-file-invalid\u{1b}[0m
1404 // \u{1b}[01;36mdir1/invalid-target\u{1b}[0m
1405 let colored_name = Regex::new(r"(?:\x1b\[0m\x1b)?\[([0-9;]+)m(.+)\x1b\[0m").unwrap();
1406 match colored_name.captures(input) {
1407 Some(captures) => {
1408 dbg!(captures.get(1).unwrap().as_str().to_string());
1409 dbg!(captures.get(2).unwrap().as_str().to_string());
1410 (
1411 captures.get(1).unwrap().as_str().to_string(),
1412 captures.get(2).unwrap().as_str().to_string(),
1413 )
1414 }
1415 None => (String::new(), input.to_string()),
1416 }
1417 }
1418
1419 fn prepare_folder_structure(scene: &TestScenario) {
1420 // There is no way to change directory in the CI, so this is the best we can do.
1421 // Also, keep in mind that windows might require privilege to symlink directories.
1422 //
1423 // We use scene.ccmd instead of scene.fixtures because we care about relative symlinks.
1424 // So we're going to try out the built mkdir, touch, and ln here, and we expect them to succeed.
1425 scene.ccmd("mkdir").arg("dir1").succeeds();
1426 scene.ccmd("mkdir").arg("dir1/dir2").succeeds();
1427 scene.ccmd("mkdir").arg("dir1/dir2/dir3").succeeds();
1428 scene.ccmd("touch").arg("dir1/file1").succeeds();
1429
1430 scene
1431 .ccmd("ln")
1432 .arg("-s")
1433 .arg("dir1/dir2")
1434 .arg("dir1/ln-dir-invalid")
1435 .succeeds();
1436 scene
1437 .ccmd("ln")
1438 .arg("-s")
1439 .arg("./dir1/dir2/dir3")
1440 .arg("ln-dir3")
1441 .succeeds();
1442 scene
1443 .ccmd("ln")
1444 .arg("-s")
1445 .arg("../..")
1446 .arg("dir1/ln-up2")
1447 .succeeds();
1448 scene
1449 .ccmd("ln")
1450 .arg("-s")
1451 .arg("/")
1452 .arg("dir1/ln-root")
1453 .succeeds();
1454 scene
1455 .ccmd("ln")
1456 .arg("-s")
1457 .arg("dir1/file1")
1458 .arg("ln-file1")
1459 .succeeds();
1460 scene
1461 .ccmd("ln")
1462 .arg("-s")
1463 .arg("dir1/invalid-target")
1464 .arg("ln-file-invalid")
1465 .succeeds();
1466 }
1467 }
1468
1469 /// This test is for "ls -l --color=auto|--color=always"
1470 /// We use "--color=always" as the colors are the same regardless of the color option being "auto" or "always"
1471 /// tests whether the specific color of the target and the `dangling_symlink` are equal and checks
1472 /// whether checks whether ls outputs the correct path for the symlink and the file it points to and applies the color code to it.
1473 #[test]
1474 fn test_ls_long_dangling_symlink_color() {
1475 let ts = TestScenario::new(util_name!());
1476 let at = &ts.fixtures;
1477
1478 at.mkdir("dir1");
1479 at.symlink_dir("foo", "dir1/dangling_symlink");
1480 let ls_colors = "ln=target:or=40:mi=34";
1481 let result = ts
1482 .ucmd()
1483 .env("LS_COLORS", ls_colors)
1484 .arg("-l")
1485 .arg("--color=always")
1486 .arg("dir1/dangling_symlink")
1487 .succeeds();
1488
1489 let stdout = result.stdout_str();
1490 // Ensure dangling link name uses `or=` and target uses `mi=`.
1491 let name_regex =
1492 Regex::new(r"(?:\x1b\[[0-9;]*m)*\x1b\[([0-9;]*)mdir1/dangling_symlink\x1b\[0m").unwrap();
1493 let target_path = regex::escape(&at.plus_as_string("foo"));
1494 let target_pattern = format!(r"(?:\x1b\[[0-9;]*m)*\x1b\[([0-9;]*)m{target_path}\x1b\[0m");
1495 let target_regex = Regex::new(&target_pattern).unwrap();
1496
1497 let name_caps = name_regex
1498 .captures(stdout)
1499 .expect("failed to capture dangling symlink name color");
1500 let target_caps = target_regex
1501 .captures(stdout)
1502 .expect("failed to capture dangling target color");
1503
1504 let name_color = name_caps.get(1).unwrap().as_str();
1505 let target_color = target_caps.get(1).unwrap().as_str();
1506
1507 assert_eq!(name_color, "40");
1508 assert_eq!(target_color, "34");
1509 }
1510
1511 #[test]
1512 /// Mirrors GNU `tests/ls/ls-misc.pl::sl-dangle3`.
1513 fn test_ls_dangling_symlink_or_and_missing_colors() {
1514 let ts = TestScenario::new(util_name!());
1515 let at = &ts.fixtures;
1516 at.symlink_file("nowhere", "dangling");
1517
1518 let stdout = ts
1519 .ucmd()
1520 .env("LS_COLORS", "ln=target:or=40:mi=34")
1521 .arg("-o")
1522 .arg("--time-style=+:TIME:")
1523 .arg("--color=always")
1524 .arg("dangling")
1525 .succeeds()
1526 .stdout_str()
1527 .to_string();
1528
1529 let color_regex = Regex::new(
1530 r"\x1b\[0m\x1b\[(?P<link>[0-9;]*)mdangling\x1b\[0m -> \x1b\[(?P<target>[0-9;]*)m",
1531 )
1532 .unwrap();
1533 let captures = color_regex
1534 .captures(&stdout)
1535 .expect("failed to capture dangling colors");
1536
1537 assert_eq!(captures.name("link").unwrap().as_str(), "40");
1538 assert_eq!(captures.name("target").unwrap().as_str(), "34");
1539 }
1540
1541 #[test]
1542 #[cfg(unix)]
1543 fn test_ls_symlink_to_dir_with_mi_colors() {
1544 // When LS_COLORS contains mi=, ln=, di=, ls -lp should stat the symlink target,
1545 // color the link with ln color, the target with di color, and append '/' to the target.
1546 use std::os::unix::fs::symlink;
1547
1548 let ts = TestScenario::new(util_name!());
1549 let at = &ts.fixtures;
1550 at.mkdir("target_dir");
1551 symlink("target_dir", at.plus("link")).unwrap();
1552
1553 let stdout = ts
1554 .ucmd()
1555 .env("LS_COLORS", "mi=41:ln=1;36:di=1;34")
1556 .arg("-lp")
1557 .arg("--color=always")
1558 .arg("link")
1559 .succeeds()
1560 .stdout_str()
1561 .to_string();
1562
1563 // Regex to capture link color and target color
1564 let color_regex = Regex::new(
1565 r"\x1b\[0m\x1b\[(?P<link>[0-9;]*)[m]link\x1b\[0m -> \x1b\[(?P<target>[0-9;]*)[m]target_dir\x1b\[0m/",
1566 )
1567 .unwrap();
1568 let captures = color_regex
1569 .captures(&stdout)
1570 .expect("failed to capture symlink colors");
1571
1572 assert_eq!(captures.name("link").unwrap().as_str(), "1;36");
1573 assert_eq!(captures.name("target").unwrap().as_str(), "1;34");
1574 }
1575
1576 #[test]
1577 /// Mirrors GNU `tests/ls/ls-misc.pl::sl-dangle4`.
1578 fn test_ls_dangling_symlink_ln_or_priority() {
1579 let ts = TestScenario::new(util_name!());
1580 let at = &ts.fixtures;
1581 at.symlink_file("nowhere", "dangling");
1582
1583 let stdout = ts
1584 .ucmd()
1585 .env("LS_COLORS", "ln=34:mi=35:or=36")
1586 .arg("-o")
1587 .arg("--time-style=+:TIME:")
1588 .arg("--color=always")
1589 .arg("dangling")
1590 .succeeds()
1591 .stdout_str()
1592 .to_string();
1593
1594 let color_regex = Regex::new(
1595 r"\x1b\[0m\x1b\[(?P<link>[0-9;]*)mdangling\x1b\[0m -> \x1b\[(?P<target>[0-9;]*)m",
1596 )
1597 .unwrap();
1598 let captures = color_regex
1599 .captures(&stdout)
1600 .expect("failed to capture dangling colors");
1601 assert_eq!(captures.name("link").unwrap().as_str(), "36");
1602 assert_eq!(captures.name("target").unwrap().as_str(), "35");
1603 }
1604
1605 #[test]
1606 /// Mirrors GNU `tests/ls/ls-misc.pl::sl-dangle5`.
1607 fn test_ls_dangling_symlink_ln_and_missing_colors() {
1608 let ts = TestScenario::new(util_name!());
1609 let at = &ts.fixtures;
1610 at.symlink_file("nowhere", "dangling");
1611
1612 let stdout = ts
1613 .ucmd()
1614 .env("LS_COLORS", "ln=34:mi=35")
1615 .arg("-o")
1616 .arg("--time-style=+:TIME:")
1617 .arg("--color=always")
1618 .arg("dangling")
1619 .succeeds()
1620 .stdout_str()
1621 .to_string();
1622
1623 let color_regex = Regex::new(
1624 r"\x1b\[0m\x1b\[(?P<link>[0-9;]*)mdangling\x1b\[0m -> \x1b\[(?P<target>[0-9;]*)m",
1625 )
1626 .unwrap();
1627 let captures = color_regex
1628 .captures(&stdout)
1629 .expect("failed to capture dangling colors");
1630 assert_eq!(captures.name("link").unwrap().as_str(), "34");
1631 assert_eq!(captures.name("target").unwrap().as_str(), "35");
1632 }
1633
1634 #[test]
1635 /// Mirrors GNU `tests/ls/ls-misc.pl::sl-dangle7`.
1636 fn test_ls_dangling_symlink_blank_or_still_emits_reset() {
1637 let ts = TestScenario::new(util_name!());
1638 let at = &ts.fixtures;
1639 at.symlink_file("nowhere", "dangling");
1640
1641 let stdout = ts
1642 .ucmd()
1643 .env("LS_COLORS", "ln=target:or=:ex=:")
1644 .arg("--color=always")
1645 .arg("dangling")
1646 .succeeds()
1647 .stdout_str()
1648 .to_string();
1649
1650 assert!(
1651 stdout.contains("\u{1b}[0m\u{1b}[mdangling\u{1b}[0m"),
1652 "unexpected output: {stdout:?}"
1653 );
1654 }
1655
1656 #[test]
1657 /// Mirrors GNU `tests/ls/ls-misc.pl::sl-dangle9`.
1658 fn test_ls_dangling_symlink_blank_or_in_directory_listing() {
1659 let ts = TestScenario::new(util_name!());
1660 let at = &ts.fixtures;
1661 at.mkdir("dir");
1662 at.symlink_file("nowhere", "dir/entry");
1663
1664 let stdout = ts
1665 .ucmd()
1666 .env("LS_COLORS", "ln=target:or=:ex=:")
1667 .arg("--color=always")
1668 .arg("dir")
1669 .succeeds()
1670 .stdout_str()
1671 .to_string();
1672
1673 assert!(
1674 stdout.contains("\u{1b}[0m\u{1b}[mentry\u{1b}[0m"),
1675 "unexpected output: {stdout:?}"
1676 );
1677 }
1678
1679 #[test]
1680 /// Mirrors GNU `tests/ls/ls-misc.pl::sl-dangle8`.
1681 fn test_ls_dangling_symlink_uses_ln_when_or_blank() {
1682 let ts = TestScenario::new(util_name!());
1683 let at = &ts.fixtures;
1684 at.symlink_file("nowhere", "dangling");
1685
1686 let stdout = ts
1687 .ucmd()
1688 .env("LS_COLORS", "ln=1;36:or=:")
1689 .arg("--color=always")
1690 .arg("dangling")
1691 .succeeds()
1692 .stdout_str()
1693 .to_string();
1694
1695 assert!(
1696 stdout.contains("\u{1b}[0m\u{1b}[1;36mdangling\u{1b}[0m"),
1697 "unexpected output: {stdout:?}"
1698 );
1699 }
1700
1701 #[test]
1702 /// Mirrors GNU `tests/ls/ls-misc.pl::sl-dangle6`.
1703 fn test_ls_directory_dangling_symlink_uses_ln_when_or_blank() {
1704 let ts = TestScenario::new(util_name!());
1705 let at = &ts.fixtures;
1706 at.mkdir("dir");
1707 at.symlink_file("nowhere", "dir/entry");
1708
1709 let stdout = ts
1710 .ucmd()
1711 .env("LS_COLORS", "ln=1;36:or=:")
1712 .arg("--color=always")
1713 .arg("dir")
1714 .succeeds()
1715 .stdout_str()
1716 .to_string();
1717
1718 assert!(
1719 stdout.contains("\u{1b}[0m\u{1b}[1;36mentry\u{1b}[0m"),
1720 "unexpected output: {stdout:?}"
1721 );
1722 }
1723
1724 #[test]
1725 #[cfg(not(target_os = "openbsd"))]
1726 fn test_ls_long_total_size() {
1727 let scene = TestScenario::new(util_name!());
1728 let at = &scene.fixtures;
1729 at.touch(at.plus_as_string("test-long"));
1730 at.append("test-long", "1");
1731 at.touch(at.plus_as_string("test-long2"));
1732 at.append("test-long2", "2");
1733
1734 let expected_prints: HashMap<_, _> = if cfg!(unix) {
1735 [
1736 ("long_vanilla", "total 8"),
1737 ("long_human_readable", "total 8.0K"),
1738 ("long_si", "total 8.2k"),
1739 ]
1740 .iter()
1741 .copied()
1742 .collect()
1743 } else {
1744 [
1745 ("long_vanilla", "total 2"),
1746 ("long_human_readable", "total 2"),
1747 ("long_si", "total 2"),
1748 ]
1749 .iter()
1750 .copied()
1751 .collect()
1752 };
1753
1754 for arg in LONG_ARGS {
1755 let result = scene.ucmd().arg(arg).succeeds();
1756 result.stdout_contains(expected_prints["long_vanilla"]);
1757
1758 for arg2 in ["-h", "--human-readable", "--si"] {
1759 let result = scene.ucmd().arg(arg).arg(arg2).succeeds();
1760 result.stdout_contains(if arg2 == "--si" {
1761 expected_prints["long_si"]
1762 } else {
1763 expected_prints["long_human_readable"]
1764 });
1765 }
1766 }
1767 }
1768
1769 #[test]
1770 #[cfg(not(feature = "selinux"))]
1771 // Disabled on the SELinux runner for now
1772 fn test_ls_long_formats() {
1773 let scene = TestScenario::new(util_name!());
1774 let at = &scene.fixtures;
1775 at.touch(at.plus_as_string("test-long-formats"));
1776
1777 // Zero or one "." for indicating a file with security context
1778
1779 // Regex for three names, so all of author, group and owner
1780 let re_three = Regex::new(r"[xrw-]{9}[.+]? \d ([-0-9_a-z.A-Z]+ ){3}0").unwrap();
1781
1782 #[cfg(unix)]
1783 let re_three_num = Regex::new(r"[xrw-]{9}[.+]? \d (\d+ ){3}0").unwrap();
1784
1785 // Regex for two names, either:
1786 // - group and owner
1787 // - author and owner
1788 // - author and group
1789 let re_two = Regex::new(r"[xrw-]{9}[.+]? \d ([-0-9_a-z.A-Z]+ ){2}0").unwrap();
1790
1791 #[cfg(unix)]
1792 let re_two_num = Regex::new(r"[xrw-]{9}[.+]? \d (\d+ ){2}0").unwrap();
1793
1794 // Regex for one name: author, group or owner
1795 let re_one = Regex::new(r"[xrw-]{9}[.+]? \d [-0-9_a-z.A-Z]+ 0").unwrap();
1796
1797 #[cfg(unix)]
1798 let re_one_num = Regex::new(r"[xrw-]{9}[.+]? \d \d+ 0").unwrap();
1799
1800 // Regex for no names
1801 let re_zero = Regex::new(r"[xrw-]{9}[.+]? \d 0").unwrap();
1802
1803 scene
1804 .ucmd()
1805 .arg("-l")
1806 .arg("--author")
1807 .arg("test-long-formats")
1808 .succeeds()
1809 .stdout_matches(&re_three);
1810
1811 scene
1812 .ucmd()
1813 .arg("-l1")
1814 .arg("--author")
1815 .arg("test-long-formats")
1816 .succeeds()
1817 .stdout_matches(&re_three);
1818
1819 #[cfg(unix)]
1820 {
1821 scene
1822 .ucmd()
1823 .arg("-n")
1824 .arg("--author")
1825 .arg("test-long-formats")
1826 .succeeds()
1827 .stdout_matches(&re_three_num);
1828 }
1829
1830 for arg in [
1831 "-l", // only group and owner
1832 "-g --author", // only author and group
1833 "-o --author", // only author and owner
1834 "-lG --author", // only author and owner
1835 "-l --no-group --author", // only author and owner
1836 ] {
1837 scene
1838 .ucmd()
1839 .args(&arg.split(' ').collect::<Vec<_>>())
1840 .arg("test-long-formats")
1841 .succeeds()
1842 .stdout_matches(&re_two);
1843
1844 #[cfg(unix)]
1845 {
1846 scene
1847 .ucmd()
1848 .arg("-n")
1849 .args(&arg.split(' ').collect::<Vec<_>>())
1850 .arg("test-long-formats")
1851 .succeeds()
1852 .stdout_matches(&re_two_num);
1853 }
1854 }
1855
1856 for arg in [
1857 "-g", // only group
1858 "-gl", // only group
1859 "-o", // only owner
1860 "-ol", // only owner
1861 "-oG", // only owner
1862 "-lG", // only owner
1863 "-l --no-group", // only owner
1864 "-gG --author", // only author
1865 ] {
1866 scene
1867 .ucmd()
1868 .args(&arg.split(' ').collect::<Vec<_>>())
1869 .arg("test-long-formats")
1870 .succeeds()
1871 .stdout_matches(&re_one);
1872
1873 #[cfg(unix)]
1874 {
1875 scene
1876 .ucmd()
1877 .arg("-n")
1878 .args(&arg.split(' ').collect::<Vec<_>>())
1879 .arg("test-long-formats")
1880 .succeeds()
1881 .stdout_matches(&re_one_num);
1882 }
1883 }
1884
1885 for arg in [
1886 "-og",
1887 "-ogl",
1888 "-lgo",
1889 "-gG",
1890 "-g --no-group",
1891 "-og --no-group",
1892 "-og --format=long",
1893 "-ogCl",
1894 "-og --format=vertical -l",
1895 "-og1",
1896 "-og1l",
1897 ] {
1898 scene
1899 .ucmd()
1900 .args(&arg.split(' ').collect::<Vec<_>>())
1901 .arg("test-long-formats")
1902 .succeeds()
1903 .stdout_matches(&re_zero);
1904
1905 #[cfg(unix)]
1906 {
1907 scene
1908 .ucmd()
1909 .arg("-n")
1910 .args(&arg.split(' ').collect::<Vec<_>>())
1911 .arg("test-long-formats")
1912 .succeeds()
1913 .stdout_matches(&re_zero);
1914 }
1915 }
1916 }
1917
1918 #[test]
1919 fn test_ls_oneline() {
1920 let scene = TestScenario::new(util_name!());
1921 let at = &scene.fixtures;
1922 at.touch(at.plus_as_string("test-oneline-1"));
1923 at.touch(at.plus_as_string("test-oneline-2"));
1924
1925 // Bit of a weird situation: in the tests oneline and columns have the same output,
1926 // except on Windows.
1927 for option in ["-1", "--format=single-column"] {
1928 scene
1929 .ucmd()
1930 .arg(option)
1931 .succeeds()
1932 .stdout_only("test-oneline-1\ntest-oneline-2\n");
1933 }
1934 }
1935
1936 #[test]
1937 fn test_ls_deref() {
1938 let scene = TestScenario::new(util_name!());
1939 let at = &scene.fixtures;
1940 let path_regexp = r"(.*)test-long.link -> (.*)test-long(.*)";
1941 let re = Regex::new(path_regexp).unwrap();
1942
1943 at.touch(at.plus_as_string("test-long"));
1944 at.symlink_file("test-long", "test-long.link");
1945 assert!(at.is_symlink("test-long.link"));
1946
1947 let result = scene
1948 .ucmd()
1949 .arg("-l")
1950 .arg("--color=never")
1951 .arg("test-long")
1952 .arg("test-long.link")
1953 .succeeds();
1954 assert!(re.is_match(result.stdout_str().trim()));
1955
1956 let result = scene
1957 .ucmd()
1958 .arg("-l")
1959 .arg("--color=neve") // spell-checker:disable-line
1960 .arg("test-long")
1961 .arg("test-long.link")
1962 .succeeds();
1963 assert!(re.is_match(result.stdout_str().trim()));
1964
1965 let result = scene
1966 .ucmd()
1967 .arg("-l")
1968 .arg("--color=n")
1969 .arg("test-long")
1970 .arg("test-long.link")
1971 .succeeds();
1972 assert!(re.is_match(result.stdout_str().trim()));
1973
1974 let result = scene
1975 .ucmd()
1976 .arg("-L")
1977 .arg("--color=never")
1978 .arg("test-long")
1979 .arg("test-long.link")
1980 .succeeds();
1981 assert!(!re.is_match(result.stdout_str().trim()));
1982 }
1983
1984 #[test]
1985 fn test_ls_group_directories_first() {
1986 let scene = TestScenario::new(util_name!());
1987 let at = &scene.fixtures;
1988 let mut filenames = ["file1", "file2", "anotherFile", "abc", "xxx", "zzz"];
1989 for filename in filenames {
1990 at.touch(filename);
1991 }
1992 filenames.sort_unstable();
1993
1994 for (i, name) in filenames.iter().enumerate() {
1995 at.write_bytes(name, "a".repeat(i).as_bytes());
1996 }
1997
1998 let dirnames = ["aaa", "bbb", "ccc", "yyy"];
1999 for dirname in dirnames {
2000 at.mkdir(dirname);
2001 }
2002
2003 let dots = [".", ".."];
2004
2005 let result = scene
2006 .ucmd()
2007 .arg("-1a")
2008 .arg("--group-directories-first")
2009 .succeeds();
2010 assert_eq!(
2011 result.stdout_str().lines().collect::<Vec<_>>(),
2012 dots.into_iter()
2013 .chain(dirnames.into_iter())
2014 .chain(filenames.into_iter())
2015 .collect::<Vec<_>>(),
2016 );
2017
2018 let result = scene
2019 .ucmd()
2020 .arg("-1")
2021 .arg("--group-directories-first")
2022 .arg("--sort=size")
2023 .succeeds();
2024 assert_eq!(
2025 result.stdout_str().lines().collect::<Vec<_>>(),
2026 dirnames
2027 .into_iter()
2028 .chain(filenames.into_iter().rev())
2029 .collect::<Vec<_>>()
2030 );
2031
2032 let result = scene
2033 .ucmd()
2034 .arg("-1ar")
2035 .arg("--group-directories-first")
2036 .succeeds();
2037 assert_eq!(
2038 result.stdout_str().lines().collect::<Vec<_>>(),
2039 dirnames
2040 .into_iter()
2041 .rev()
2042 .chain(dots.into_iter().rev())
2043 .chain(filenames.into_iter().rev())
2044 .collect::<Vec<_>>(),
2045 );
2046
2047 let result = scene
2048 .ucmd()
2049 .arg("-1aU")
2050 .arg("--group-directories-first")
2051 .succeeds();
2052 let result2 = scene.ucmd().arg("-1aU").succeeds();
2053 assert_eq!(result.stdout_str(), result2.stdout_str());
2054 }
2055 #[test]
2056 fn test_ls_sort_none() {
2057 let scene = TestScenario::new(util_name!());
2058 let at = &scene.fixtures;
2059
2060 at.touch("test-3");
2061 at.touch("test-1");
2062 at.touch("test-2");
2063
2064 // Order is not specified so we just check that it doesn't
2065 // give any errors.
2066 scene.ucmd().arg("--sort=none").succeeds();
2067 scene.ucmd().arg("--sort=non").succeeds();
2068 scene.ucmd().arg("--sort=no").succeeds();
2069 // scene.ucmd().arg("--sort=n").succeeds();
2070 // We refuse to accept "--sort=n", since this is too confusable with "--sort=name", which is our own extension.
2071 scene.ucmd().arg("-U").succeeds();
2072 }
2073
2074 #[test]
2075 fn test_ls_sort_name() {
2076 let scene = TestScenario::new(util_name!());
2077 let at = &scene.fixtures;
2078
2079 at.touch("test-3");
2080 at.touch("test-1");
2081 at.touch("test-2");
2082
2083 scene
2084 .ucmd()
2085 .arg("--sort=name")
2086 .succeeds()
2087 .stdout_is("test-1\ntest-2\ntest-3\n");
2088 scene
2089 .ucmd()
2090 .arg("--sort=nam")
2091 .succeeds()
2092 .stdout_is("test-1\ntest-2\ntest-3\n");
2093 scene
2094 .ucmd()
2095 .arg("--sort=na")
2096 .succeeds()
2097 .stdout_is("test-1\ntest-2\ntest-3\n");
2098
2099 let scene_dot = TestScenario::new(util_name!());
2100 let at = &scene_dot.fixtures;
2101 at.touch(".a");
2102 at.touch("a");
2103 at.touch(".b");
2104 at.touch("b");
2105
2106 scene_dot
2107 .ucmd()
2108 .arg("--sort=name")
2109 .arg("-A")
2110 .succeeds()
2111 .stdout_is(".a\n.b\na\nb\n");
2112 }
2113
2114 // https://github.com/uutils/coreutils/issues/11831
2115 // In a UTF-8 locale, GNU ls places "." and ".." before names starting with
2116 // punctuation such as '#' due to locale-aware collation.
2117 #[test]
2118 fn test_ls_sort_dot_first_utf8_locale() {
2119 let scene = TestScenario::new(util_name!());
2120 let at = &scene.fixtures;
2121 at.touch("#asdf");
2122 at.touch("bar");
2123 at.touch("foo");
2124
2125 scene
2126 .ucmd()
2127 .env("LANG", "en_US.UTF-8")
2128 .env("LC_ALL", "en_US.UTF-8")
2129 .arg("-1a")
2130 .succeeds()
2131 .stdout_is(".\n..\n#asdf\nbar\nfoo\n");
2132 }
2133
2134 #[test]
2135 fn test_ls_sort_width() {
2136 let scene = TestScenario::new(util_name!());
2137 let at = &scene.fixtures;
2138
2139 at.touch("aaaaa");
2140 at.touch("bbb");
2141 at.touch("cccc");
2142 at.touch("eee");
2143 at.touch("d");
2144 at.touch("fffff");
2145 at.touch("abc");
2146 at.touch("zz");
2147 at.touch("bcdef");
2148
2149 scene
2150 .ucmd()
2151 .arg("--sort=width")
2152 .succeeds()
2153 .stdout_is("d\nzz\nabc\nbbb\neee\ncccc\naaaaa\nbcdef\nfffff\n");
2154 scene
2155 .ucmd()
2156 .arg("--sort=widt") // spell-checker:disable-line
2157 .succeeds()
2158 .stdout_is("d\nzz\nabc\nbbb\neee\ncccc\naaaaa\nbcdef\nfffff\n");
2159 scene
2160 .ucmd()
2161 .arg("--sort=w")
2162 .succeeds()
2163 .stdout_is("d\nzz\nabc\nbbb\neee\ncccc\naaaaa\nbcdef\nfffff\n");
2164 }
2165
2166 #[test]
2167 fn test_ls_order_size() {
2168 let scene = TestScenario::new(util_name!());
2169 let at = &scene.fixtures;
2170
2171 at.touch("test-1");
2172 at.append("test-1", "1");
2173
2174 at.touch("test-2");
2175 at.append("test-2", "22");
2176 at.touch("test-3");
2177 at.append("test-3", "333");
2178 at.touch("test-4");
2179 at.append("test-4", "4444");
2180
2181 scene.ucmd().arg("-al").succeeds();
2182
2183 let result = scene.ucmd().arg("-S").succeeds();
2184 result.stdout_only("test-4\ntest-3\ntest-2\ntest-1\n");
2185
2186 let result = scene.ucmd().arg("-S").arg("-r").succeeds();
2187 result.stdout_only("test-1\ntest-2\ntest-3\ntest-4\n");
2188
2189 let result = scene.ucmd().arg("--sort=size").succeeds();
2190 result.stdout_only("test-4\ntest-3\ntest-2\ntest-1\n");
2191
2192 let result = scene.ucmd().arg("--sort=siz").succeeds();
2193 result.stdout_only("test-4\ntest-3\ntest-2\ntest-1\n");
2194
2195 let result = scene.ucmd().arg("--sort=s").succeeds();
2196 result.stdout_only("test-4\ntest-3\ntest-2\ntest-1\n");
2197
2198 let result = scene.ucmd().arg("--sort=size").arg("-r").succeeds();
2199 result.stdout_only("test-1\ntest-2\ntest-3\ntest-4\n");
2200 }
2201
2202 #[test]
2203 fn test_ls_long_ctime() {
2204 let scene = TestScenario::new(util_name!());
2205 let at = &scene.fixtures;
2206
2207 at.touch("test-long-ctime-1");
2208
2209 for arg in ["-c", "--time=ctime", "--time=status"] {
2210 let result = scene.ucmd().arg("-l").arg(arg).succeeds();
2211
2212 // Should show the time on Unix, but question marks on windows.
2213 #[cfg(unix)]
2214 result.stdout_contains(":");
2215 #[cfg(not(unix))]
2216 result.stdout_contains("???");
2217 }
2218 }
2219
2220 #[test]
2221 #[ignore = ""]
2222 fn test_ls_order_birthtime() {
2223 let scene = TestScenario::new(util_name!());
2224 let at = &scene.fixtures;
2225
2226 /*
2227 Here we make 2 files with a timeout in between.
2228 After creating the first file try to sync it.
2229 This ensures the file gets created immediately instead of being saved
2230 inside the OS's IO operation buffer.
2231 Without this, both files might accidentally be created at the same time.
2232 */
2233 at.make_file("test-birthtime-1").sync_all().unwrap();
2234 at.make_file("test-birthtime-2").sync_all().unwrap();
2235 at.open("test-birthtime-1");
2236
2237 let result = scene.ucmd().arg("--time=birth").arg("-t").succeeds();
2238
2239 #[cfg(not(windows))]
2240 assert_eq!(result.stdout_str(), "test-birthtime-2\ntest-birthtime-1\n");
2241 #[cfg(windows)]
2242 assert_eq!(result.stdout_str(), "test-birthtime-2 test-birthtime-1\n");
2243 }
2244
2245 #[test]
2246 fn test_ls_time_styles() {
2247 let scene = TestScenario::new(util_name!());
2248 let at = &scene.fixtures;
2249 // Create a recent and old (<6 months) file, as format can be different.
2250 at.touch("test");
2251 let f3 = at.make_file("test-old");
2252 f3.set_modified(SystemTime::now() - Duration::from_secs(3600 * 24 * 365))
2253 .unwrap();
2254
2255 let re_full_recent = Regex::new(
2256 r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d* (\+|\-)\d{4} test\n",
2257 )
2258 .unwrap();
2259 let re_long_recent =
2260 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}-\d{2}-\d{2} \d{2}:\d{2} test\n").unwrap();
2261 let re_iso_recent =
2262 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{2}-\d{2} \d{2}:\d{2} test\n").unwrap();
2263 let re_locale_recent =
2264 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* [A-Z][a-z]{2} ( |\d)\d \d{2}:\d{2} test\n")
2265 .unwrap();
2266 let re_full_old = Regex::new(
2267 r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d* (\+|\-)\d{4} test-old\n",
2268 )
2269 .unwrap();
2270 let re_long_old =
2271 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}-\d{2}-\d{2} \d{2}:\d{2} test-old\n")
2272 .unwrap();
2273 let re_iso_old =
2274 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}-\d{2}-\d{2} test-old\n").unwrap();
2275 let re_locale_old =
2276 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* [A-Z][a-z]{2} ( |\d)\d \d{4} test-old\n")
2277 .unwrap();
2278
2279 //full-iso
2280 scene
2281 .ucmd()
2282 .arg("-l")
2283 .arg("--time-style=full-iso")
2284 .succeeds()
2285 .stdout_matches(&re_full_recent)
2286 .stdout_matches(&re_full_old);
2287 //long-iso
2288 scene
2289 .ucmd()
2290 .arg("-l")
2291 .arg("--time-style=long-iso")
2292 .succeeds()
2293 .stdout_matches(&re_long_recent)
2294 .stdout_matches(&re_long_old);
2295 //iso
2296 scene
2297 .ucmd()
2298 .arg("-l")
2299 .arg("--time-style=iso")
2300 .succeeds()
2301 .stdout_matches(&re_iso_recent)
2302 .stdout_matches(&re_iso_old);
2303 //locale
2304 scene
2305 .ucmd()
2306 .arg("-l")
2307 .arg("--time-style=locale")
2308 .succeeds()
2309 .stdout_matches(&re_locale_recent)
2310 .stdout_matches(&re_locale_old);
2311
2312 //posix-full-iso
2313 scene
2314 .ucmd()
2315 .arg("-l")
2316 .arg("--time-style=posix-full-iso")
2317 .succeeds()
2318 .stdout_matches(&re_full_recent)
2319 .stdout_matches(&re_full_old);
2320 //posix-long-iso
2321 scene
2322 .ucmd()
2323 .arg("-l")
2324 .arg("--time-style=posix-long-iso")
2325 .succeeds()
2326 .stdout_matches(&re_long_recent)
2327 .stdout_matches(&re_long_old);
2328 //posix-iso
2329 scene
2330 .ucmd()
2331 .arg("-l")
2332 .arg("--time-style=posix-iso")
2333 .succeeds()
2334 .stdout_matches(&re_iso_recent)
2335 .stdout_matches(&re_iso_old);
2336
2337 //posix-* with LC_TIME/LC_ALL=POSIX is equivalent to locale
2338 scene
2339 .ucmd()
2340 .env("LC_TIME", "POSIX")
2341 .arg("-l")
2342 .arg("--time-style=posix-full-iso")
2343 .succeeds()
2344 .stdout_matches(&re_locale_recent)
2345 .stdout_matches(&re_locale_old);
2346 scene
2347 .ucmd()
2348 .env("LC_ALL", "POSIX")
2349 .arg("-l")
2350 .arg("--time-style=posix-iso")
2351 .succeeds()
2352 .stdout_matches(&re_locale_recent)
2353 .stdout_matches(&re_locale_old);
2354
2355 //+FORMAT
2356 let re_custom_format_recent =
2357 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}__\d{2} test\n").unwrap();
2358 let re_custom_format_old =
2359 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}__\d{2} test-old\n").unwrap();
2360 scene
2361 .ucmd()
2362 .arg("-l")
2363 .arg("--time-style=+%Y__%M")
2364 .succeeds()
2365 .stdout_matches(&re_custom_format_recent)
2366 .stdout_matches(&re_custom_format_old);
2367
2368 //+FORMAT_RECENT\nFORMAT_OLD
2369 let re_custom_format_old =
2370 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}--\d{2} test-old\n").unwrap();
2371 scene
2372 .ucmd()
2373 .arg("-l")
2374 .arg("--time-style=+%Y__%M\n%Y--%M")
2375 .succeeds()
2376 .stdout_matches(&re_custom_format_recent)
2377 .stdout_matches(&re_custom_format_old);
2378
2379 // Also fails due to not having full clap support for time_styles
2380 scene
2381 .ucmd()
2382 .arg("-l")
2383 .arg("--time-style=invalid")
2384 .fails_with_code(2);
2385
2386 // Cannot have 2 new lines in custom format
2387 scene
2388 .ucmd()
2389 .arg("-l")
2390 .arg("--time-style=+%Y__%M\n%Y--%M\n")
2391 .fails_with_code(2);
2392
2393 //Overwrite options tests
2394 scene
2395 .ucmd()
2396 .arg("-l")
2397 .arg("--time-style=long-iso")
2398 .arg("--time-style=iso")
2399 .succeeds()
2400 .stdout_matches(&re_iso_recent);
2401 scene
2402 .ucmd()
2403 .arg("--time-style=iso")
2404 .arg("--full-time")
2405 .succeeds()
2406 .stdout_matches(&re_full_recent);
2407 scene
2408 .ucmd()
2409 .arg("--full-time")
2410 .arg("--time-style=iso")
2411 .succeeds()
2412 .stdout_matches(&re_iso_recent);
2413
2414 scene
2415 .ucmd()
2416 .arg("--full-time")
2417 .arg("--time-style=iso")
2418 .arg("--full-time")
2419 .succeeds()
2420 .stdout_matches(&re_full_recent);
2421
2422 scene
2423 .ucmd()
2424 .arg("--full-time")
2425 .arg("-x")
2426 .arg("-l")
2427 .succeeds()
2428 .stdout_matches(&re_full_recent);
2429
2430 scene
2431 .ucmd()
2432 .arg("--full-time")
2433 .arg("-x")
2434 .succeeds()
2435 .stdout_is("test test-old\n");
2436
2437 // Time style can also be setup from environment
2438 scene
2439 .ucmd()
2440 .env("TIME_STYLE", "full-iso")
2441 .arg("-l")
2442 .succeeds()
2443 .stdout_matches(&re_full_recent);
2444
2445 // ... but option takes precedence
2446 scene
2447 .ucmd()
2448 .env("TIME_STYLE", "full-iso")
2449 .arg("-l")
2450 .arg("--time-style=long-iso")
2451 .succeeds()
2452 .stdout_matches(&re_long_recent);
2453 }
2454
2455 #[test]
2456 fn test_ls_time_recent_future() {
2457 let scene = TestScenario::new(util_name!());
2458 let at = &scene.fixtures;
2459 let f = at.make_file("test");
2460
2461 let re_iso_recent =
2462 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{2}-\d{2} \d{2}:\d{2} test\n").unwrap();
2463 let re_iso_old =
2464 Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* \d{4}-\d{2}-\d{2} test\n").unwrap();
2465
2466 // `test` has just been created, so it's recent
2467 scene
2468 .ucmd()
2469 .arg("-l")
2470 .arg("--time-style=iso")
2471 .succeeds()
2472 .stdout_matches(&re_iso_recent);
2473
2474 // 100 days ago is still recent (<0.5 years)
2475 f.set_modified(SystemTime::now() - Duration::from_secs(3600 * 24 * 100))
2476 .unwrap();
2477 scene
2478 .ucmd()
2479 .arg("-l")
2480 .arg("--time-style=iso")
2481 .succeeds()
2482 .stdout_matches(&re_iso_recent);
2483
2484 // 200 days ago is not recent
2485 f.set_modified(SystemTime::now() - Duration::from_secs(3600 * 24 * 200))
2486 .unwrap();
2487 scene
2488 .ucmd()
2489 .arg("-l")
2490 .arg("--time-style=iso")
2491 .succeeds()
2492 .stdout_matches(&re_iso_old);
2493
2494 // A timestamp in the future (even just a minute), is not considered "recent"
2495 f.set_modified(SystemTime::now() + Duration::from_secs(60))
2496 .unwrap();
2497 scene
2498 .ucmd()
2499 .arg("-l")
2500 .arg("--time-style=iso")
2501 .succeeds()
2502 .stdout_matches(&re_iso_old);
2503
2504 // Also test that we can set a format that varies for recent of older files.
2505 //+FORMAT_RECENT\nFORMAT_OLD
2506 f.set_modified(SystemTime::now()).unwrap();
2507 scene
2508 .ucmd()
2509 .arg("-l")
2510 .arg("--time-style=+RECENT\nOLD")
2511 .succeeds()
2512 .stdout_contains("RECENT");
2513
2514 // Old file
2515 f.set_modified(SystemTime::now() - Duration::from_secs(3600 * 24 * 200))
2516 .unwrap();
2517 scene
2518 .ucmd()
2519 .arg("-l")
2520 .arg("--time-style=+RECENT\nOLD")
2521 .succeeds()
2522 .stdout_contains("OLD");
2523
2524 // RECENT format is still used if no "OLD" one provided.
2525 scene
2526 .ucmd()
2527 .arg("-l")
2528 .arg("--time-style=+RECENT")
2529 .succeeds()
2530 .stdout_contains("RECENT");
2531 }
2532
2533 #[test]
2534 fn test_ls_order_time_breaks_ties_by_name() {
2535 // Every other sort in this utility falls back on the name, and GNU ls does
2536 // the same for -t. Without the fallback, entries sharing a timestamp come
2537 // out in whatever order the directory happened to be read in.
2538 use filetime::{FileTime, set_file_times};
2539
2540 let scene = TestScenario::new(util_name!());
2541 let at = &scene.fixtures;
2542
2543 let names = ["zulu", "alpha", "Mike", "bravo"];
2544 for name in names {
2545 at.touch(name);
2546 at.append(name, "x");
2547 }
2548 let same = FileTime::from_unix_time(1_700_000_000, 0);
2549 for name in names {
2550 set_file_times(at.plus_as_string(name), same, same).unwrap();
2551 }
2552
2553 scene
2554 .ucmd()
2555 .env("LC_ALL", "C")
2556 .arg("-t")
2557 .succeeds()
2558 .stdout_only("Mike\nalpha\nbravo\nzulu\n");
2559
2560 scene
2561 .ucmd()
2562 .env("LC_ALL", "C")
2563 .arg("-tr")
2564 .succeeds()
2565 .stdout_only("zulu\nbravo\nalpha\nMike\n");
2566
2567 // The tie is broken with the same order the name sort uses, so a UTF-8
2568 // locale puts `alpha` before `Mike` where the C locale does the reverse.
2569 #[cfg(unix)]
2570 {
2571 use uutests::util::is_locale_available;
2572 let locale = "en_US.UTF-8";
2573 if is_locale_available(locale) {
2574 scene
2575 .ucmd()
2576 .env("LC_ALL", locale)
2577 .arg("-t")
2578 .succeeds()
2579 .stdout_only("alpha\nbravo\nMike\nzulu\n");
2580 }
2581 }
2582 }
2583
2584 #[test]
2585 fn test_ls_order_time() {
2586 let scene = TestScenario::new(util_name!());
2587 let at = &scene.fixtures;
2588
2589 at.touch("test-1");
2590 at.append("test-1", "1");
2591 sleep(Duration::from_millis(100));
2592 at.touch("test-2");
2593 at.append("test-2", "22");
2594
2595 sleep(Duration::from_millis(100));
2596 at.touch("test-3");
2597 at.append("test-3", "333");
2598 sleep(Duration::from_millis(100));
2599 at.touch("test-4");
2600 at.append("test-4", "4444");
2601 sleep(Duration::from_millis(100));
2602
2603 // Read test-3, only changing access time
2604 at.read("test-3");
2605
2606 // Set permissions of test-2, only changing ctime
2607 std::fs::set_permissions(
2608 at.plus_as_string("test-2"),
2609 at.metadata("test-2").permissions(),
2610 )
2611 .unwrap();
2612
2613 scene.ucmd().arg("-al").succeeds();
2614
2615 // ctime was changed at write, so the order is 4 3 2 1
2616 let result = scene.ucmd().arg("-t").succeeds();
2617 result.stdout_only("test-4\ntest-3\ntest-2\ntest-1\n");
2618
2619 let result = scene.ucmd().arg("--sort=time").succeeds();
2620 result.stdout_only("test-4\ntest-3\ntest-2\ntest-1\n");
2621
2622 let result = scene.ucmd().arg("-tr").succeeds();
2623 result.stdout_only("test-1\ntest-2\ntest-3\ntest-4\n");
2624
2625 let result = scene.ucmd().arg("--sort=time").arg("-r").succeeds();
2626 result.stdout_only("test-1\ntest-2\ntest-3\ntest-4\n");
2627
2628 // Long format selects the displayed time without enabling time sorting.
2629 let name_order = Regex::new(r"(?s)test-1\n.*test-2\n.*test-3\n.*test-4\n").unwrap();
2630 for (time, format) in itertools::iproduct!(["-u", "-c"], ["-g", "--format=long", "--dired"]) {
2631 scene
2632 .ucmd()
2633 .args(&[time, format])
2634 .succeeds()
2635 .stdout_matches(&name_order);
2636 }
2637
2638 let args: [&[&str]; 10] = [
2639 &["-t", "-u"],
2640 &["-u"], //-t is optional: when -l is not set -u/--time controls sorting
2641 &["-t", "--time=atime"],
2642 &["--time=atime"],
2643 &["--time=atim"], // spell-checker:disable-line
2644 &["--time=a"],
2645 &["-t", "--time=access"],
2646 &["--time=access"],
2647 &["-t", "--time=use"],
2648 &["--time=use"],
2649 ];
2650 // 3 was accessed last in the read
2651 // So the order should be 2 3 4 1
2652 for args in args {
2653 let result = scene.ucmd().args(args).succeeds();
2654 at.open("test-3").metadata().unwrap().accessed().unwrap();
2655 at.open("test-4").metadata().unwrap().accessed().unwrap();
2656
2657 // It seems to be dependent on the platform whether the access time is actually set
2658 #[cfg(unix)]
2659 {
2660 let expected = unwrap_or_return!(expected_result(&scene, args));
2661 at.open("test-3").metadata().unwrap().accessed().unwrap();
2662 at.open("test-4").metadata().unwrap().accessed().unwrap();
2663
2664 result.stdout_only(expected.stdout_str());
2665 }
2666 #[cfg(windows)]
2667 result.stdout_only("test-4\ntest-3\ntest-2\ntest-1\n");
2668 }
2669
2670 // test-2 had the last ctime change when the permissions were set
2671 // So the order should be 2 4 3 1
2672 #[cfg(unix)]
2673 {
2674 let result = scene.ucmd().arg("-tc").succeeds();
2675 result.stdout_only("test-2\ntest-4\ntest-3\ntest-1\n");
2676
2677 // When -l is not set, -c also controls sorting
2678 let result = scene.ucmd().arg("-c").succeeds();
2679 result.stdout_only("test-2\ntest-4\ntest-3\ntest-1\n");
2680 }
2681 }
2682
2683 #[test]
2684 fn test_ls_order_mtime() {
2685 use std::time::SystemTime;
2686 let scene = TestScenario::new(util_name!());
2687 let at = &scene.fixtures;
2688
2689 let f3 = at.make_file("test-3");
2690 f3.set_modified(SystemTime::now()).unwrap();
2691 let f4 = at.make_file("test-4");
2692 f4.set_modified(SystemTime::now()).unwrap();
2693 let f1 = at.make_file("test-1");
2694 f1.set_modified(SystemTime::now()).unwrap();
2695 let f2 = at.make_file("test-2");
2696 f2.set_modified(SystemTime::now()).unwrap();
2697
2698 let result = scene.ucmd().arg("-t").arg("--time=mtime").succeeds();
2699 result.stdout_only("test-2\ntest-1\ntest-4\ntest-3\n");
2700 f3.set_modified(SystemTime::now()).unwrap();
2701
2702 f4.set_modified(SystemTime::now()).unwrap();
2703 let result = scene.ucmd().arg("-t").arg("--time=mtime").succeeds();
2704 result.stdout_only("test-4\ntest-3\ntest-2\ntest-1\n");
2705 }
2706
2707 #[test]
2708 fn test_ls_non_existing() {
2709 new_ucmd!().arg("doesntexist").fails();
2710 }
2711
2712 #[test]
2713 fn test_ls_files_dirs() {
2714 let scene = TestScenario::new(util_name!());
2715 let at = &scene.fixtures;
2716 at.mkdir("a");
2717 at.mkdir("a/b");
2718 at.mkdir("a/b/c");
2719 at.mkdir("z");
2720 at.touch(at.plus_as_string("a/a"));
2721 at.touch(at.plus_as_string("a/b/b"));
2722
2723 scene.ucmd().arg("a").succeeds();
2724 scene.ucmd().arg("a/a").succeeds();
2725 scene.ucmd().arg("a").arg("z").succeeds();
2726
2727 // Doesn't exist
2728 scene
2729 .ucmd()
2730 .arg("doesntexist")
2731 .fails()
2732 .stderr_contains("'doesntexist': No such file or directory");
2733
2734 // One exists, the other doesn't
2735 scene
2736 .ucmd()
2737 .arg("a")
2738 .arg("doesntexist")
2739 .fails()
2740 .stderr_contains("'doesntexist': No such file or directory")
2741 .stdout_contains("a:");
2742 }
2743
2744 #[test]
2745 fn test_ls_recursive() {
2746 let scene = TestScenario::new(util_name!());
2747 let at = &scene.fixtures;
2748 at.mkdir("a");
2749 at.mkdir("a/b");
2750 at.mkdir("a/b/c");
2751 at.mkdir("z");
2752 at.touch(at.plus_as_string("a/a"));
2753 at.touch(at.plus_as_string("a/b/b"));
2754
2755 scene.ucmd().arg("a").succeeds();
2756 scene.ucmd().arg("a/a").succeeds();
2757 scene
2758 .ucmd()
2759 .arg("z")
2760 .arg("-R")
2761 .succeeds()
2762 .stdout_contains("z:");
2763 let result = scene
2764 .ucmd()
2765 .arg("--color=never")
2766 .arg("-R")
2767 .arg("a")
2768 .arg("z")
2769 .succeeds();
2770
2771 #[cfg(not(windows))]
2772 result.stdout_contains("a/b:\nb");
2773 #[cfg(windows)]
2774 result.stdout_contains("a\\b:\nb");
2775 }
2776
2777 #[test]
2778 fn test_ls_recursive_1() {
2779 let scene = TestScenario::new(util_name!());
2780 let at = &scene.fixtures;
2781 at.mkdir("x");
2782 at.mkdir("y");
2783 at.mkdir("a");
2784 at.mkdir("b");
2785 at.mkdir("c");
2786 at.mkdir("a/1");
2787 at.mkdir("a/2");
2788 at.mkdir("a/3");
2789 at.touch("f");
2790 at.touch("a/1/I");
2791 at.touch("a/1/II");
2792 #[cfg(unix)]
2793 let out = "a:\n1\n2\n3\n\na/1:\nI\nII\n\na/2:\n\na/3:\n\nb:\n\nc:\n";
2794 #[cfg(windows)]
2795 let out = "a:\n1\n2\n3\n\na\\1:\nI\nII\n\na\\2:\n\na\\3:\n\nb:\n\nc:\n";
2796 scene
2797 .ucmd()
2798 .arg("-R1")
2799 .arg("a")
2800 .arg("b")
2801 .arg("c")
2802 .succeeds()
2803 .stdout_is(out);
2804 }
2805
2806 #[test]
2807 fn test_ls_recursive_all_with_version_sort_does_not_walk_up() {
2808 // Regression test for https://github.com/uutils/coreutils/issues/13501:
2809 // combining `-a` (show `.`/`..`) with `-R` (recursive) and `-v`
2810 // (version/natural sort) used to make `ls` recurse into the listed
2811 // `.`/`..` entries themselves, walking all the way up to the
2812 // filesystem root instead of stopping at the leaf directories.
2813 let scene = TestScenario::new(util_name!());
2814 let at = &scene.fixtures;
2815 at.mkdir("a");
2816 at.mkdir("a/b");
2817 at.mkdir("a/b/c");
2818
2819 #[cfg(unix)]
2820 let out = "a/b:\n.\n..\nc\n\na/b/c:\n.\n..\n";
2821 #[cfg(windows)]
2822 let out = "a/b:\n.\n..\nc\n\na/b\\c:\n.\n..\n";
2823 scene
2824 .ucmd()
2825 .arg("-aRv")
2826 .arg("a/b")
2827 .succeeds()
2828 .stdout_is(out);
2829 }
2830
2831 /// The quoting module regroups tests that check the behavior of ls when
2832 /// quoting and escaping special characters with different quoting styles.
2833 #[cfg(unix)]
2834 mod quoting {
2835 use super::TestScenario;
2836 use uutests::at_and_ucmd;
2837 use uutests::util::is_locale_available;
2838 use uutests::util_name;
2839
2840 /// Create a directory with "dirname", then for each check, assert that the
2841 /// output is correct.
2842 fn check_quoting_dirname(dirname: &str, checks: &[(&str, &str, &str)], extra_args: &[&str]) {
2843 for (qt_style, regular_mode, dir_mode) in checks {
2844 let scene = TestScenario::new(util_name!());
2845 let at = &scene.fixtures;
2846 at.mkdir(dirname);
2847
2848 let expected = format!(
2849 "{}:\n{regular_mode}\n\n{dir_mode}:\n",
2850 match *qt_style {
2851 "shell-always" | "shell-escape-always" => "'.'",
2852 "c" => "\".\"",
2853 _ => ".",
2854 },
2855 );
2856
2857 scene
2858 .ucmd()
2859 .arg("-R")
2860 .arg(format!("--quoting-style={qt_style}"))
2861 .args(extra_args)
2862 .succeeds()
2863 .stdout_is(expected);
2864 }
2865 }
2866
2867 #[test]
2868 fn test_ls_quoting_simple() {
2869 check_quoting_dirname(
2870 // Control case
2871 "dirname",
2872 &[
2873 ("literal", "dirname", "./dirname"),
2874 ("shell", "dirname", "./dirname"),
2875 ("shell-always", "'dirname'", "'./dirname'"),
2876 ("shell-escape", "dirname", "./dirname"),
2877 ("shell-escape-always", "'dirname'", "'./dirname'"),
2878 ("c", "\"dirname\"", "\"./dirname\""),
2879 ("escape", "dirname", "./dirname"),
2880 ],
2881 &[],
2882 );
2883 }
2884
2885 // Regression test for GNU tests/ls/quoting-utf8.sh: in a UTF-8 locale the
2886 // locale/clocale quoting styles use Unicode quotation marks U+2018/U+2019
2887 // and must not escape embedded apostrophes or double quotes; in the C
2888 // locale they fall back to ASCII single/double quotes.
2889 #[test]
2890 fn test_ls_quoting_locale_utf8() {
2891 if !is_locale_available("en_US.UTF-8") {
2892 return;
2893 }
2894
2895 let lq = "\u{2018}";
2896 let rq = "\u{2019}";
2897
2898 for style in ["locale", "clocale"] {
2899 let (at, mut ucmd) = at_and_ucmd!();
2900 at.touch("hello world");
2901 at.touch("it's");
2902 at.touch("say \"hi\"");
2903 at.touch("tab\there");
2904 at.touch("nel\u{0085}here");
2905
2906 let out = ucmd
2907 .env("LC_ALL", "en_US.UTF-8")
2908 .arg(format!("--quoting-style={style}"))
2909 .arg("-1")
2910 .succeeds()
2911 .stdout_move_str();
2912
2913 assert!(
2914 out.contains(&format!("{lq}hello world{rq}")),
2915 "{style}: 'hello world' not quoted with Unicode quotes: {out:?}"
2916 );
2917 // Embedded apostrophe and double quote must stay unescaped.
2918 assert!(
2919 out.contains(&format!("{lq}it's{rq}")),
2920 "{style}: embedded apostrophe should not be escaped: {out:?}"
2921 );
2922 assert!(
2923 out.contains(&format!("{lq}say \"hi\"{rq}")),
2924 "{style}: embedded double quote should not be escaped: {out:?}"
2925 );
2926 // Control characters are still C-escaped.
2927 assert!(
2928 out.contains(&format!("{lq}tab\\there{rq}")),
2929 "{style}: tab should be escaped as \\t: {out:?}"
2930 );
2931 // Non-ASCII (C1) control characters are octal-escaped by byte.
2932 assert!(
2933 out.contains(&format!("{lq}nel\\302\\205here{rq}")),
2934 "{style}: U+0085 should be octal-escaped: {out:?}"
2935 );
2936 }
2937
2938 // In the C locale, locale uses ASCII single quotes and clocale uses
2939 // ASCII double quotes.
2940 let (at, mut ucmd) = at_and_ucmd!();
2941 at.touch("hello world");
2942 ucmd.env("LC_ALL", "C")
2943 .arg("--quoting-style=locale")
2944 .arg("-1")
2945 .succeeds()
2946 .stdout_contains("'hello world'");
2947
2948 let (at, mut ucmd) = at_and_ucmd!();
2949 at.touch("hello world");
2950 ucmd.env("LC_ALL", "C")
2951 .arg("--quoting-style=clocale")
2952 .arg("-1")
2953 .succeeds()
2954 .stdout_contains("\"hello world\"");
2955 }
2956
2957 #[test]
2958 fn test_ls_quoting_space() {
2959 check_quoting_dirname(
2960 // Space character
2961 "dir name",
2962 &[
2963 ("literal", "dir name", "./dir name"),
2964 ("shell", "'dir name'", "'./dir name'"),
2965 ("shell-always", "'dir name'", "'./dir name'"),
2966 ("shell-escape", "'dir name'", "'./dir name'"),
2967 ("shell-escape-always", "'dir name'", "'./dir name'"),
2968 ("c", "\"dir name\"", "\"./dir name\""),
2969 ("escape", "dir\\ name", "./dir name"),
2970 ],
2971 &[],
2972 );
2973 }
2974
2975 #[test]
2976 fn test_ls_quoting_dollar() {
2977 check_quoting_dirname(
2978 // Dollar character
2979 "dir$name",
2980 &[
2981 ("literal", "dir$name", "./dir$name"),
2982 ("shell", "'dir$name'", "'./dir$name'"),
2983 ("shell-always", "'dir$name'", "'./dir$name'"),
2984 ("shell-escape", "'dir$name'", "'./dir$name'"),
2985 ("shell-escape-always", "'dir$name'", "'./dir$name'"),
2986 ("c", "\"dir$name\"", "\"./dir$name\""),
2987 ("escape", "dir$name", "./dir$name"),
2988 ],
2989 &[],
2990 );
2991 }
2992
2993 #[test]
2994 fn test_ls_quoting_single_quote() {
2995 check_quoting_dirname(
2996 // Single quote character
2997 "dir'name",
2998 &[
2999 ("literal", "dir'name", "./dir'name"),
3000 ("shell", "\"dir'name\"", "\"./dir'name\""),
3001 ("shell-always", "\"dir'name\"", "\"./dir'name\""),
3002 ("shell-escape", "\"dir'name\"", "\"./dir'name\""),
3003 ("shell-escape-always", "\"dir'name\"", "\"./dir'name\""),
3004 ("c", "\"dir'name\"", "\"./dir'name\""),
3005 ("escape", "dir'name", "./dir'name"),
3006 ],
3007 &[],
3008 );
3009 }
3010
3011 #[test]
3012 fn test_ls_quoting_double_quote() {
3013 check_quoting_dirname(
3014 // Double quote character
3015 "dir\"name",
3016 &[
3017 ("literal", "dir\"name", "./dir\"name"),
3018 ("shell", "'dir\"name'", "'./dir\"name'"),
3019 ("shell-always", "'dir\"name'", "'./dir\"name'"),
3020 ("shell-escape", "'dir\"name'", "'./dir\"name'"),
3021 ("shell-escape-always", "'dir\"name'", "'./dir\"name'"),
3022 ("c", "\"dir\\\"name\"", "\"./dir\\\"name\""),
3023 ("escape", "dir\"name", "./dir\"name"),
3024 ],
3025 &[],
3026 );
3027 }
3028
3029 #[test]
3030 fn test_ls_quoting_colon() {
3031 check_quoting_dirname(
3032 // Colon character
3033 "dir:name",
3034 &[
3035 ("literal", "dir:name", "./dir:name"),
3036 ("shell", "dir:name", "'./dir:name'"),
3037 ("shell-always", "'dir:name'", "'./dir:name'"),
3038 ("shell-escape", "dir:name", "'./dir:name'"),
3039 ("shell-escape-always", "'dir:name'", "'./dir:name'"),
3040 ("c", "\"dir:name\"", "\"./dir\\:name\""),
3041 ("escape", "dir:name", "./dir\\:name"),
3042 ],
3043 &[],
3044 );
3045 }
3046
3047 #[test]
3048 fn test_ls_quoting_backslash() {
3049 check_quoting_dirname(
3050 // Backslash character
3051 "dir\\name",
3052 &[
3053 ("literal", "dir\\name", "./dir\\name"),
3054 ("shell", "'dir\\name'", "'./dir\\name'"),
3055 ("shell-always", "'dir\\name'", "'./dir\\name'"),
3056 ("shell-escape", "'dir\\name'", "'./dir\\name'"),
3057 ("shell-escape-always", "'dir\\name'", "'./dir\\name'"),
3058 ("c", "\"dir\\\\name\"", "\"./dir\\\\name\""),
3059 ("escape", "dir\\\\name", "./dir\\\\name"),
3060 ],
3061 &[],
3062 );
3063 }
3064
3065 #[test]
3066 fn test_ls_quoting_linefeed() {
3067 check_quoting_dirname(
3068 // Linefeed character
3069 "dir\nname",
3070 &[
3071 ("literal", "dir\nname", "./dir\nname"),
3072 ("shell", "'dir\nname'", "'./dir\nname'"),
3073 ("shell-always", "'dir\nname'", "'./dir\nname'"),
3074 ("shell-escape", "'dir'$'\\n''name'", "'./dir'$'\\n''name'"),
3075 (
3076 "shell-escape-always",
3077 "'dir'$'\\n''name'",
3078 "'./dir'$'\\n''name'",
3079 ),
3080 ("c", "\"dir\\nname\"", "\"./dir\\nname\""),
3081 ("escape", "dir\\nname", "./dir\\nname"),
3082 ],
3083 &[],
3084 );
3085
3086 check_quoting_dirname(
3087 // Linefeed character WITH hide-control-chars
3088 "dir\nname",
3089 &[
3090 ("literal", "dir?name", "./dir?name"),
3091 ("shell", "'dir?name'", "'./dir?name'"),
3092 ("shell-always", "'dir?name'", "'./dir?name'"),
3093 ("shell-escape", "'dir'$'\\n''name'", "'./dir'$'\\n''name'"),
3094 (
3095 "shell-escape-always",
3096 "'dir'$'\\n''name'",
3097 "'./dir'$'\\n''name'",
3098 ),
3099 ("c", "\"dir\\nname\"", "\"./dir\\nname\""),
3100 ("escape", "dir\\nname", "./dir\\nname"),
3101 ],
3102 &["--hide-control-chars"],
3103 );
3104 }
3105
3106 #[test]
3107 fn test_ls_quoting_tabulation() {
3108 check_quoting_dirname(
3109 // Tabulation character
3110 "dir\tname",
3111 &[
3112 ("literal", "dir\tname", "./dir\tname"),
3113 ("shell", "'dir\tname'", "'./dir\tname'"),
3114 ("shell-always", "'dir\tname'", "'./dir\tname'"),
3115 ("shell-escape", "'dir'$'\\t''name'", "'./dir'$'\\t''name'"),
3116 (
3117 "shell-escape-always",
3118 "'dir'$'\\t''name'",
3119 "'./dir'$'\\t''name'",
3120 ),
3121 ("c", "\"dir\\tname\"", "\"./dir\\tname\""),
3122 ("escape", "dir\\tname", "./dir\\tname"),
3123 ],
3124 &[],
3125 );
3126
3127 check_quoting_dirname(
3128 // Tabulation character
3129 "dir\tname",
3130 &[
3131 ("literal", "dir?name", "./dir?name"),
3132 ("shell", "'dir?name'", "'./dir?name'"),
3133 ("shell-always", "'dir?name'", "'./dir?name'"),
3134 ("shell-escape", "'dir'$'\\t''name'", "'./dir'$'\\t''name'"),
3135 (
3136 "shell-escape-always",
3137 "'dir'$'\\t''name'",
3138 "'./dir'$'\\t''name'",
3139 ),
3140 ("c", "\"dir\\tname\"", "\"./dir\\tname\""),
3141 ("escape", "dir\\tname", "./dir\\tname"),
3142 ],
3143 &["--hide-control-chars"],
3144 );
3145 }
3146
3147 #[test]
3148 fn test_ls_quoting_carriage_return() {
3149 check_quoting_dirname(
3150 // Carriage return character
3151 "dir\rname",
3152 &[
3153 ("literal", "dir?name", "./dir?name"),
3154 ("shell", "'dir?name'", "'./dir?name'"),
3155 ("shell-always", "'dir?name'", "'./dir?name'"),
3156 ("shell-escape", "'dir'$'\\r''name'", "'./dir'$'\\r''name'"),
3157 (
3158 "shell-escape-always",
3159 "'dir'$'\\r''name'",
3160 "'./dir'$'\\r''name'",
3161 ),
3162 ("c", "\"dir\\rname\"", "\"./dir\\rname\""),
3163 ("escape", "dir\\rname", "./dir\\rname"),
3164 ],
3165 &["--hide-control-chars"],
3166 );
3167 }
3168
3169 #[test]
3170 fn test_ls_quoting_bell() {
3171 check_quoting_dirname(
3172 // Bell character
3173 "dir\x07name",
3174 &[
3175 ("shell", "dir?name", "./dir?name"),
3176 ("shell-always", "'dir?name'", "'./dir?name'"),
3177 ("shell-escape", "'dir'$'\\a''name'", "'./dir'$'\\a''name'"),
3178 (
3179 "shell-escape-always",
3180 "'dir'$'\\a''name'",
3181 "'./dir'$'\\a''name'",
3182 ),
3183 ("c", "\"dir\\aname\"", "\"./dir\\aname\""),
3184 ("escape", "dir\\aname", "./dir\\aname"),
3185 ],
3186 &["--hide-control-chars"],
3187 );
3188 }
3189
3190 #[test]
3191 fn test_ls_quoting_backspace() {
3192 check_quoting_dirname(
3193 // Backspace character
3194 "dir\x08name",
3195 &[
3196 ("shell", "dir?name", "./dir?name"),
3197 ("shell-always", "'dir?name'", "'./dir?name'"),
3198 ("shell-escape", "'dir'$'\\b''name'", "'./dir'$'\\b''name'"),
3199 (
3200 "shell-escape-always",
3201 "'dir'$'\\b''name'",
3202 "'./dir'$'\\b''name'",
3203 ),
3204 ("c", "\"dir\\bname\"", "\"./dir\\bname\""),
3205 ("escape", "dir\\bname", "./dir\\bname"),
3206 ],
3207 &["--hide-control-chars"],
3208 );
3209 }
3210
3211 #[test]
3212 fn test_ls_quoting_vertical_tab() {
3213 check_quoting_dirname(
3214 // Vertical tab character
3215 "dir\x0bname",
3216 &[
3217 ("shell", "dir?name", "./dir?name"),
3218 ("shell-always", "'dir?name'", "'./dir?name'"),
3219 ("shell-escape", "'dir'$'\\v''name'", "'./dir'$'\\v''name'"),
3220 (
3221 "shell-escape-always",
3222 "'dir'$'\\v''name'",
3223 "'./dir'$'\\v''name'",
3224 ),
3225 ("c", "\"dir\\vname\"", "\"./dir\\vname\""),
3226 ("escape", "dir\\vname", "./dir\\vname"),
3227 ],
3228 &["--hide-control-chars"],
3229 );
3230 }
3231
3232 #[test]
3233 fn test_ls_quoting_formfeed() {
3234 check_quoting_dirname(
3235 // Form feed character
3236 "dir\x0cname",
3237 &[
3238 ("shell", "dir?name", "./dir?name"),
3239 ("shell-always", "'dir?name'", "'./dir?name'"),
3240 ("shell-escape", "'dir'$'\\f''name'", "'./dir'$'\\f''name'"),
3241 (
3242 "shell-escape-always",
3243 "'dir'$'\\f''name'",
3244 "'./dir'$'\\f''name'",
3245 ),
3246 ("c", "\"dir\\fname\"", "\"./dir\\fname\""),
3247 ("escape", "dir\\fname", "./dir\\fname"),
3248 ],
3249 &["--hide-control-chars"],
3250 );
3251 }
3252
3253 #[test]
3254 fn test_ls_quoting_open_bracket() {
3255 check_quoting_dirname(
3256 "[-open_bracket",
3257 &[
3258 ("shell", "'[-open_bracket'", "'./[-open_bracket'"),
3259 ("shell-always", "'[-open_bracket'", "'./[-open_bracket'"),
3260 ("shell-escape", "'[-open_bracket'", "'./[-open_bracket'"),
3261 (
3262 "shell-escape-always",
3263 "'[-open_bracket'",
3264 "'./[-open_bracket'",
3265 ),
3266 ("c", "\"[-open_bracket\"", "\"./[-open_bracket\""),
3267 ("escape", "[-open_bracket", "./[-open_bracket"),
3268 ],
3269 &[],
3270 );
3271 }
3272
3273 #[test]
3274 fn test_ls_quoting_close_bracket() {
3275 check_quoting_dirname(
3276 "]-close_bracket",
3277 &[
3278 ("shell", "]-close_bracket", "./]-close_bracket"),
3279 ("shell-always", "']-close_bracket'", "'./]-close_bracket'"),
3280 ("shell-escape", "]-close_bracket", "./]-close_bracket"),
3281 (
3282 "shell-escape-always",
3283 "']-close_bracket'",
3284 "'./]-close_bracket'",
3285 ),
3286 ("c", "\"]-close_bracket\"", "\"./]-close_bracket\""),
3287 ("escape", "]-close_bracket", "./]-close_bracket"),
3288 ],
3289 &[],
3290 );
3291 }
3292
3293 #[test]
3294 fn test_ls_quoting_open_brace() {
3295 check_quoting_dirname(
3296 "{-open_brace",
3297 &[
3298 ("shell", "{-open_brace", "./{-open_brace"),
3299 ("shell-always", "'{-open_brace'", "'./{-open_brace'"),
3300 ("shell-escape", "{-open_brace", "./{-open_brace"),
3301 ("shell-escape-always", "'{-open_brace'", "'./{-open_brace'"),
3302 ("c", "\"{-open_brace\"", "\"./{-open_brace\""),
3303 ("escape", "{-open_brace", "./{-open_brace"),
3304 ],
3305 &[],
3306 );
3307 }
3308
3309 #[test]
3310 fn test_ls_quoting_close_brace() {
3311 check_quoting_dirname(
3312 "}-close_brace",
3313 &[
3314 ("shell", "}-close_brace", "./}-close_brace"),
3315 ("shell-always", "'}-close_brace'", "'./}-close_brace'"),
3316 ("shell-escape", "}-close_brace", "./}-close_brace"),
3317 (
3318 "shell-escape-always",
3319 "'}-close_brace'",
3320 "'./}-close_brace'",
3321 ),
3322 ("c", "\"}-close_brace\"", "\"./}-close_brace\""),
3323 ("escape", "}-close_brace", "./}-close_brace"),
3324 ],
3325 &[],
3326 );
3327 }
3328
3329 #[test]
3330 fn test_ls_quoting_caret() {
3331 check_quoting_dirname(
3332 "^-caret",
3333 &[
3334 ("shell", "'^-caret'", "'./^-caret'"),
3335 ("shell-always", "'^-caret'", "'./^-caret'"),
3336 ("shell-escape", "'^-caret'", "'./^-caret'"),
3337 ("shell-escape-always", "'^-caret'", "'./^-caret'"),
3338 ("c", "\"^-caret\"", "\"./^-caret\""),
3339 ("escape", "^-caret", "./^-caret"),
3340 ],
3341 &[],
3342 );
3343 }
3344
3345 #[test]
3346 fn test_ls_quoting_equal() {
3347 check_quoting_dirname(
3348 "=-equal",
3349 &[
3350 ("shell", "'=-equal'", "'./=-equal'"),
3351 ("shell-always", "'=-equal'", "'./=-equal'"),
3352 ("shell-escape", "'=-equal'", "'./=-equal'"),
3353 ("shell-escape-always", "'=-equal'", "'./=-equal'"),
3354 ("c", "\"=-equal\"", "\"./=-equal\""),
3355 ("escape", "=-equal", "./=-equal"),
3356 ],
3357 &[],
3358 );
3359 }
3360
3361 #[cfg(not(any(target_vendor = "apple", windows, target_os = "openbsd")))]
3362 #[test]
3363 /// This test creates files with an UTF-8 encoded name and verify that it
3364 /// gets escaped depending on the used locale.
3365 fn test_locale_aware_quoting() {
3366 let cases: &[(&[u8], _, _, &[&str])] = &[
3367 (
3368 "😁".as_bytes(), // == b"\xF0\x9F\x98\x81"
3369 "''$'\\360\\237\\230\\201'\n", // ASCII sees 4 bytes
3370 "😁\n", // UTF-8 sees an emoji
3371 &["--quoting-style=shell-escape"],
3372 ),
3373 (
3374 "€".as_bytes(), // == b"\xE2\x82\xAC"
3375 "''$'\\342\\202\\254'\n", // ASCII sees 3 bytes
3376 "€\n", // UTF-8 still only 2
3377 &["--quoting-style=shell-escape"],
3378 ),
3379 (
3380 b"\xC2\x80\xC2\x81", // 2 first Unicode control characters
3381 "????\n", // ASCII sees 4 bytes
3382 "??\n", // UTF-8 sees only 2
3383 &["--quoting-style=literal", "--hide-control-char"],
3384 ),
3385 (
3386 b"\xC2\xC2\x81",
3387 "???\n", // ASCII sees 3 bytes
3388 "??\n", // UTF-8 still only 2
3389 &["--quoting-style=literal", "--hide-control-char"],
3390 ),
3391 (
3392 b"\xC2\x81\xC2",
3393 "???\n", // ASCII sees 3 bytes
3394 "??\n", // UTF-8 still only 2
3395 &["--quoting-style=literal", "--hide-control-char"],
3396 ),
3397 ];
3398
3399 for (filename, ascii_ref, utf_8_ref, args) in cases {
3400 let scene = TestScenario::new(util_name!());
3401 let at = &scene.fixtures;
3402
3403 let filename = uucore::os_str_from_bytes(filename)
3404 .expect("Filename is valid Unicode supported on Linux");
3405
3406 at.touch(filename);
3407
3408 // When the locale does not handle UTF-8 encoding, escaping is done.
3409 scene
3410 .ucmd()
3411 .env("LC_ALL", "C") // Non UTF-8 locale
3412 .args(args)
3413 .succeeds()
3414 .stdout_only(ascii_ref);
3415
3416 // When the locale has UTF-8 support, the symbol is shown as-is.
3417 scene
3418 .ucmd()
3419 .env("LC_ALL", "en_US.UTF-8") // UTF-8 locale
3420 .args(args)
3421 .succeeds()
3422 .stdout_only(utf_8_ref);
3423 }
3424 }
3425
3426 #[test]
3427 fn test_c_dot_utf8_renders_utf8() {
3428 let scene = TestScenario::new(util_name!());
3429 let at = &scene.fixtures;
3430 let filename = "é";
3431 at.touch(filename);
3432
3433 // C (no UTF-8): bytes 0xC3 0xA9 replaced with ??
3434 scene
3435 .ucmd()
3436 .env("LC_ALL", "C")
3437 .args(&["--quoting-style=literal", "--hide-control-chars"])
3438 .succeeds()
3439 .stdout_is("??\n");
3440
3441 // C.UTF-8: multi-byte UTF-8 character rendered literally
3442 scene
3443 .ucmd()
3444 .env("LC_ALL", "C.UTF-8")
3445 .args(&["--quoting-style=literal", "--hide-control-chars"])
3446 .succeeds()
3447 .stdout_is("é\n");
3448 }
3449 }
3450
3451 #[test]
3452 fn test_ls_color() {
3453 let scene = TestScenario::new(util_name!());
3454 let at = &scene.fixtures;
3455 at.mkdir("a");
3456 let nested_dir = Path::new("a")
3457 .join("nested_dir")
3458 .to_string_lossy()
3459 .to_string();
3460 at.mkdir(nested_dir);
3461 at.mkdir("z");
3462 let nested_file = Path::new("a")
3463 .join("nested_file")
3464 .to_string_lossy()
3465 .to_string();
3466 at.touch(nested_file);
3467 at.touch("test-color");
3468
3469 let a_with_colors = "\x1b[0m\x1b[01;34ma\x1b[0m";
3470 let z_with_colors = "\x1b[01;34mz\x1b[0m\n";
3471 let nested_dir_with_colors = "\x1b[0m\x1b[01;34mnested_dir\x1b[0m\x0anested_file"; // spell-checker:disable-line
3472
3473 // Color is disabled by default
3474 let result = scene.ucmd().succeeds();
3475 assert!(!result.stdout_str().contains(a_with_colors));
3476 assert!(!result.stdout_str().contains(z_with_colors));
3477
3478 // Color should be enabled
3479 for param in ["--color", "--col", "--color=always", "--col=always"] {
3480 let result = scene.ucmd().arg(param).succeeds();
3481 assert!(result.stdout_str().contains(a_with_colors));
3482 assert!(result.stdout_str().contains(z_with_colors));
3483 }
3484
3485 // Color should be disabled
3486 let result = scene.ucmd().arg("--color=never").succeeds();
3487 assert!(!result.stdout_str().contains(a_with_colors));
3488 assert!(!result.stdout_str().contains(z_with_colors));
3489
3490 // Nested dir should be shown and colored
3491 let result = scene.ucmd().arg("--color").arg("a").succeeds();
3492 assert!(result.stdout_str().contains(nested_dir_with_colors));
3493
3494 // No output
3495 scene
3496 .ucmd()
3497 .arg("--color=never")
3498 .arg("z")
3499 .succeeds()
3500 .stdout_only("");
3501
3502 // The colors must not mess up the grid layout
3503 at.touch("b");
3504 let result = scene
3505 .ucmd()
3506 .arg("--color")
3507 .arg("-w=15")
3508 .arg("-C")
3509 .succeeds();
3510 let expected = format!("{a_with_colors} test-color\x0ab {z_with_colors}");
3511 assert_eq!(
3512 result.stdout_str().escape_default().to_string(),
3513 expected.escape_default().to_string()
3514 );
3515 assert_eq!(result.stdout_str(), expected);
3516 }
3517
3518 #[cfg(unix)]
3519 #[test]
3520 #[cfg(not(feature = "selinux"))]
3521 // Disabled on the SELinux runner for now
3522 fn test_ls_inode() {
3523 let scene = TestScenario::new(util_name!());
3524 let at = &scene.fixtures;
3525
3526 let file = "test_inode";
3527 at.touch(file);
3528
3529 let re_short = Regex::new(r" *(\d+) test_inode").unwrap();
3530 let re_long =
3531 Regex::new(r" *(\d+) [-bcdlpsDx]([r-][w-][xt-]){3}[.+]? +\d .+ test_inode").unwrap();
3532
3533 let result = scene.ucmd().arg("test_inode").arg("-i").succeeds();
3534 assert!(re_short.is_match(result.stdout_str()));
3535 let inode_short = re_short
3536 .captures(result.stdout_str())
3537 .unwrap()
3538 .get(1)
3539 .unwrap()
3540 .as_str();
3541
3542 let result = scene.ucmd().arg("test_inode").succeeds();
3543 assert!(!re_short.is_match(result.stdout_str()));
3544 assert!(!result.stdout_str().contains(inode_short));
3545
3546 let result = scene.ucmd().arg("-li").arg("test_inode").succeeds();
3547 assert!(re_long.is_match(result.stdout_str()));
3548 let inode_long = re_long
3549 .captures(result.stdout_str())
3550 .unwrap()
3551 .get(1)
3552 .unwrap()
3553 .as_str();
3554
3555 let result = scene.ucmd().arg("-l").arg("test_inode").succeeds();
3556 assert!(!re_long.is_match(result.stdout_str()));
3557 assert!(!result.stdout_str().contains(inode_long));
3558
3559 assert_eq!(inode_short, inode_long);
3560 }
3561
3562 #[test]
3563 #[cfg(not(windows))]
3564 fn test_ls_indicator_style() {
3565 let scene = TestScenario::new(util_name!());
3566 let at = &scene.fixtures;
3567
3568 // Setup: Directory, Symlink, and Pipes.
3569 at.mkdir("directory");
3570 assert!(at.dir_exists("directory"));
3571
3572 at.touch(at.plus_as_string("link-src"));
3573 at.symlink_file("link-src", "link-dest.link");
3574 assert!(at.is_symlink("link-dest.link"));
3575
3576 at.mkfifo("named-pipe.fifo");
3577 assert!(at.is_fifo("named-pipe.fifo"));
3578
3579 // Classify, File-Type, and Slash all contain indicators for directories.
3580 for opt in [
3581 "--indicator-style=classify",
3582 "--ind=classify",
3583 "--indicator-style=clas", // spell-checker:disable-line
3584 "--indicator-style=c",
3585 "--indicator-style=file-type",
3586 "--ind=file-type",
3587 "--indicator-style=slash",
3588 "--ind=slash",
3589 "--classify",
3590 "--classify=always",
3591 "--classify=alway",
3592 "--classify=al",
3593 "--classify=yes",
3594 "--classify=force",
3595 "--class",
3596 "--file-type",
3597 "--file",
3598 "-p",
3599 ] {
3600 // Verify that classify and file-type both contain indicators for symlinks.
3601 scene.ucmd().arg(opt).succeeds().stdout_contains("/");
3602 }
3603
3604 // Classify, Indicator options should not contain any indicators when value is none.
3605 for opt in [
3606 "--indicator-style=none",
3607 "--indicator-style=n",
3608 "--ind=none",
3609 "--classify=none",
3610 "--classify=never",
3611 "--classify=non",
3612 "--classify=no",
3613 "--classify=n",
3614 ] {
3615 // Verify that there are no indicators for any of the file types.
3616 scene
3617 .ucmd()
3618 .arg(opt)
3619 .succeeds()
3620 .stdout_does_not_contain("/")
3621 .stdout_does_not_contain("@")
3622 .stdout_does_not_contain("|");
3623 }
3624
3625 // Classify and File-Type all contain indicators for pipes and links.
3626 let options = vec!["classify", "file-type"];
3627 for opt in options {
3628 // Verify that classify and file-type both contain indicators for symlinks.
3629 scene
3630 .ucmd()
3631 .arg(format!("--indicator-style={opt}"))
3632 .succeeds()
3633 .stdout_contains("@")
3634 .stdout_contains("|");
3635 }
3636
3637 // Test sockets. Because the canonical way of making sockets to test is with
3638 // TempDir, we need a separate test.
3639 {
3640 use std::os::unix::net::UnixListener;
3641
3642 let dir = tempfile::Builder::new()
3643 .prefix("unix_socket")
3644 .tempdir()
3645 .expect("failed to create dir");
3646 let socket_path = dir.path().join("sock");
3647 let _listener = UnixListener::bind(socket_path).expect("failed to create socket");
3648
3649 new_ucmd!()
3650 .args(&[
3651 PathBuf::from(dir.path().to_str().unwrap()),
3652 PathBuf::from("--indicator-style=classify"),
3653 ])
3654 .succeeds()
3655 .stdout_only("sock=\n");
3656 }
3657 }
3658
3659 #[test]
3660 #[cfg(not(windows))]
3661 fn test_ls_indicator_style_symlink_target_long() {
3662 let scene = TestScenario::new(util_name!());
3663 let at = &scene.fixtures;
3664
3665 at.mkdir("dir");
3666 assert!(at.dir_exists("dir"));
3667
3668 at.symlink_dir("dir", "dir_link");
3669 assert!(at.is_symlink("dir_link"));
3670
3671 scene
3672 .ucmd()
3673 .arg("--classify")
3674 .arg("-l")
3675 .arg("dir_link")
3676 .succeeds()
3677 .stdout_contains("dir_link -> ")
3678 .stdout_does_not_contain("dir_link@ -> ")
3679 .stdout_contains("/dir/");
3680 }
3681
3682 #[test]
3683 #[cfg(unix)]
3684 fn test_ls_indicator_style_filetype_symlink_target_long() {
3685 // GNU `ls -l --file-type` does append `/` to a symlink target that resolves to a
3686 // directory unlike `ls -lp`
3687 use std::os::unix::fs::symlink;
3688
3689 let scene = TestScenario::new(util_name!());
3690 let at = &scene.fixtures;
3691
3692 at.mkdir("dir");
3693 assert!(at.dir_exists("dir"));
3694
3695 // Use a relative-path symlink so the displayed target matches GNU output.
3696 symlink("dir", at.plus("dir_link")).unwrap();
3697 assert!(at.is_symlink("dir_link"));
3698
3699 scene
3700 .ucmd()
3701 .arg("--file-type")
3702 .arg("-l")
3703 .arg("dir_link")
3704 .succeeds()
3705 .stdout_contains("dir_link -> dir/")
3706 .stdout_does_not_contain("dir_link/");
3707 }
3708
3709 #[test]
3710 #[cfg(unix)]
3711 fn test_ls_indicator_style_filetype_symlink_to_executable_target_long() {
3712 use std::fs;
3713 use std::os::unix::fs::{PermissionsExt, symlink};
3714
3715 let scene = TestScenario::new(util_name!());
3716 let at = &scene.fixtures;
3717
3718 at.touch("exec_target");
3719 let mut perms = fs::metadata(at.plus("exec_target")).unwrap().permissions();
3720 perms.set_mode(0o755);
3721 fs::set_permissions(at.plus("exec_target"), perms).unwrap();
3722
3723 symlink("exec_target", at.plus("link")).unwrap();
3724 assert!(at.is_symlink("link"));
3725
3726 scene
3727 .ucmd()
3728 .arg("--file-type")
3729 .arg("-l")
3730 .arg("link")
3731 .succeeds()
3732 .stdout_contains("link -> exec_target")
3733 .stdout_does_not_contain("exec_target*");
3734 }
3735
3736 #[test]
3737 #[cfg(unix)]
3738 fn test_ls_indicator_style_slash_symlink_target_long() {
3739 // GNU `ls -lp` does NOT append `/` to a symlink target that resolves to a
3740 // directory — the slash indicator style only applies to real directories.
3741 use std::os::unix::fs::symlink;
3742
3743 let scene = TestScenario::new(util_name!());
3744 let at = &scene.fixtures;
3745
3746 at.mkdir("dir");
3747 assert!(at.dir_exists("dir"));
3748
3749 // Use a relative-path symlink so the displayed target matches GNU output.
3750 symlink("dir", at.plus("dir_link")).unwrap();
3751 assert!(at.is_symlink("dir_link"));
3752
3753 scene
3754 .ucmd()
3755 .arg("-lp")
3756 .arg("dir_link")
3757 .succeeds()
3758 .stdout_contains("dir_link -> dir\n")
3759 .stdout_does_not_contain("dir_link/")
3760 .stdout_does_not_contain("-> dir/");
3761 }
3762
3763 // Essentially the same test as above, but only test symlinks and directories,
3764 // not pipes or sockets.
3765 #[test]
3766 #[cfg(not(unix))]
3767 fn test_ls_indicator_style() {
3768 let scene = TestScenario::new(util_name!());
3769 let at = &scene.fixtures;
3770
3771 // Setup: Directory, Symlink.
3772 at.mkdir("directory");
3773 assert!(at.dir_exists("directory"));
3774
3775 at.touch(at.plus_as_string("link-src"));
3776 at.symlink_file("link-src", "link-dest.link");
3777 assert!(at.is_symlink("link-dest.link"));
3778
3779 // Classify, File-Type, and Slash all contain indicators for directories.
3780 let options = vec!["classify", "file-type", "slash"];
3781 for opt in options {
3782 // Verify that classify and file-type both contain indicators for symlinks.
3783 scene
3784 .ucmd()
3785 .arg(format!("--indicator-style={opt}"))
3786 .succeeds()
3787 .stdout_contains("/");
3788 }
3789
3790 // Same test as above, but with the alternate flags.
3791 let options = vec!["--classify", "--file-type", "-p"];
3792 for opt in options {
3793 scene.ucmd().arg(opt).succeeds().stdout_contains("/");
3794 }
3795
3796 // Classify and File-Type all contain indicators for pipes and links.
3797 let options = vec!["classify", "file-type"];
3798 for opt in options {
3799 // Verify that classify and file-type both contain indicators for symlinks.
3800 scene
3801 .ucmd()
3802 .arg(format!("--indicator-style={opt}"))
3803 .succeeds()
3804 .stdout_contains("@");
3805 }
3806 }
3807
3808 #[cfg(not(any(target_vendor = "apple", windows, target_os = "openbsd")))] // Truncate not available on mac or win
3809 #[test]
3810 fn test_ls_human_si() {
3811 let scene = TestScenario::new(util_name!());
3812 let file1 = "test_human-1";
3813 scene
3814 .cmd("truncate")
3815 .arg("-s")
3816 .arg("+1000")
3817 .arg(file1)
3818 .succeeds();
3819
3820 scene
3821 .ucmd()
3822 .arg("-hl")
3823 .arg(file1)
3824 .succeeds()
3825 .stdout_contains(" 1000 ");
3826
3827 scene
3828 .ucmd()
3829 .arg("-l")
3830 .arg("--si")
3831 .arg(file1)
3832 .succeeds()
3833 .stdout_contains(" 1.0k ");
3834
3835 scene
3836 .cmd("truncate")
3837 .arg("-s")
3838 .arg("+1000k")
3839 .arg(file1)
3840 .succeeds();
3841
3842 scene
3843 .ucmd()
3844 .arg("-hl")
3845 .arg(file1)
3846 .succeeds()
3847 .stdout_contains(" 1001K ");
3848
3849 scene
3850 .ucmd()
3851 .arg("-l")
3852 .arg("--si")
3853 .arg(file1)
3854 .succeeds()
3855 .stdout_contains(" 1.1M ");
3856
3857 let file2 = "test-human-2";
3858 scene
3859 .cmd("truncate")
3860 .arg("-s")
3861 .arg("+12300k")
3862 .arg(file2)
3863 .succeeds();
3864
3865 // GNU rounds up, so we must too.
3866 scene
3867 .ucmd()
3868 .arg("-hl")
3869 .arg(file2)
3870 .succeeds()
3871 .stdout_contains(" 13M ");
3872
3873 // GNU rounds up, so we must too.
3874 scene
3875 .ucmd()
3876 .arg("-l")
3877 .arg("--si")
3878 .arg(file2)
3879 .succeeds()
3880 .stdout_contains(" 13M ");
3881
3882 let file3 = "test-human-3";
3883 scene
3884 .cmd("truncate")
3885 .arg("-s")
3886 .arg("+9999")
3887 .arg(file3)
3888 .succeeds();
3889
3890 scene
3891 .ucmd()
3892 .arg("-hl")
3893 .arg(file3)
3894 .succeeds()
3895 .stdout_contains(" 9.8K ");
3896
3897 scene
3898 .ucmd()
3899 .arg("-l")
3900 .arg("--si")
3901 .arg(file3)
3902 .succeeds()
3903 .stdout_contains(" 10k ");
3904 }
3905
3906 #[cfg(windows)]
3907 #[test]
3908 fn test_ls_hidden_windows() {
3909 let scene = TestScenario::new(util_name!());
3910 let at = &scene.fixtures;
3911 let file = "hiddenWindowsFileNoDot";
3912 at.touch(file);
3913 // hide the file
3914 scene
3915 .cmd("attrib")
3916 .arg("+h")
3917 .arg("+S")
3918 .arg("+r")
3919 .arg(file)
3920 .succeeds();
3921
3922 let result = scene.ucmd().succeeds();
3923 assert!(!result.stdout_str().contains(file));
3924 scene.ucmd().arg("-a").succeeds().stdout_contains(file);
3925 }
3926
3927 #[cfg(windows)]
3928 #[test]
3929 fn test_ls_hidden_link_windows() {
3930 let scene = TestScenario::new(util_name!());
3931 let at = &scene.fixtures;
3932
3933 let file = "visibleWindowsFileNoDot";
3934 at.touch(file);
3935
3936 let link = "hiddenWindowsLinkNoDot";
3937 at.symlink_dir(file, link);
3938 // hide the link
3939 scene.cmd("attrib").arg("/l").arg("+h").arg(link).succeeds();
3940
3941 scene
3942 .ucmd()
3943 .succeeds()
3944 .stdout_contains(file)
3945 .stdout_does_not_contain(link);
3946
3947 scene
3948 .ucmd()
3949 .arg("-a")
3950 .succeeds()
3951 .stdout_contains(file)
3952 .stdout_contains(link);
3953 }
3954
3955 #[cfg(windows)]
3956 #[test]
3957 fn test_ls_success_on_c_drv_root_windows() {
3958 let scene = TestScenario::new(util_name!());
3959 scene.ucmd().arg("C:\\").succeeds();
3960 }
3961
3962 #[test]
3963 fn test_ls_version_sort() {
3964 let scene = TestScenario::new(util_name!());
3965 let at = &scene.fixtures;
3966 for filename in [
3967 "a2",
3968 "b1",
3969 "b20",
3970 "a1.4",
3971 "a1.40",
3972 "b3",
3973 "b11",
3974 "b20b",
3975 "b20a",
3976 "a100",
3977 "a1.13",
3978 "aa",
3979 "a1",
3980 "aaa",
3981 "a1.00000040",
3982 "abab",
3983 "ab",
3984 "a01.40",
3985 "a001.001",
3986 "a01.0000001",
3987 "a01.001",
3988 "a001.01",
3989 ] {
3990 at.touch(filename);
3991 }
3992
3993 let mut expected = vec![
3994 "a1",
3995 "a001.001",
3996 "a001.01",
3997 "a01.0000001",
3998 "a01.001",
3999 "a1.4",
4000 "a1.13",
4001 "a01.40",
4002 "a1.00000040",
4003 "a1.40",
4004 "a2",
4005 "a100",
4006 "aa",
4007 "aaa",
4008 "ab",
4009 "abab",
4010 "b1",
4011 "b3",
4012 "b11",
4013 "b20",
4014 "b20a",
4015 "b20b",
4016 "", // because of '\n' at the end of the output
4017 ];
4018
4019 let result = scene.ucmd().arg("-1v").succeeds();
4020 assert_eq!(
4021 result.stdout_str().split('\n').collect::<Vec<_>>(),
4022 expected
4023 );
4024
4025 let result = scene.ucmd().arg("-1").arg("--sort=version").succeeds();
4026 assert_eq!(
4027 result.stdout_str().split('\n').collect::<Vec<_>>(),
4028 expected
4029 );
4030
4031 let result = scene.ucmd().arg("-1").arg("--sort=v").succeeds();
4032 assert_eq!(
4033 result.stdout_str().split('\n').collect::<Vec<_>>(),
4034 expected
4035 );
4036
4037 let result = scene.ucmd().arg("-a1v").succeeds();
4038 expected.insert(0, "..");
4039 expected.insert(0, ".");
4040 assert_eq!(
4041 result.stdout_str().split('\n').collect::<Vec<_>>(),
4042 expected,
4043 );
4044 }
4045
4046 #[test]
4047 fn test_ls_quoting_style() {
4048 let scene = TestScenario::new(util_name!());
4049 let at = &scene.fixtures;
4050
4051 at.touch("one two");
4052 at.touch("one");
4053
4054 // It seems that windows doesn't allow \n in filenames.
4055 // And it also doesn't like \, of course.
4056 #[cfg(unix)]
4057 {
4058 at.touch("one\ntwo");
4059 at.touch("one\\two");
4060
4061 // Default is literal, when stdout is not a TTY...
4062 scene
4063 .ucmd()
4064 .arg("--hide-control-chars")
4065 .arg("one\ntwo")
4066 .succeeds()
4067 .stdout_only("one?two\n");
4068
4069 // ... Otherwise, it is shell-escape
4070 #[cfg(unix)]
4071 scene
4072 .ucmd()
4073 .arg("--hide-control-chars")
4074 .arg("one\ntwo")
4075 .terminal_simulation(true)
4076 .succeeds()
4077 .stdout_only("'one'$'\\n''two'\r\n");
4078
4079 for (arg, correct) in [
4080 ("--quoting-style=literal", "one?two"),
4081 ("--quoting-style=litera", "one?two"), // spell-checker:disable-line
4082 ("--quoting-style=li", "one?two"),
4083 ("-N", "one?two"),
4084 ("--literal", "one?two"),
4085 ("--l", "one?two"),
4086 ("--quoting-style=c", "\"one\\ntwo\""),
4087 ("--quoting-style=c-", "\"one\\ntwo\""),
4088 ("--quoting-style=c-maybe", "\"one\\ntwo\""),
4089 ("-Q", "\"one\\ntwo\""),
4090 ("--quote-name", "\"one\\ntwo\""),
4091 ("--quoting-style=escape", "one\\ntwo"),
4092 ("--quoting-style=escap", "one\\ntwo"), // spell-checker:disable-line
4093 ("-b", "one\\ntwo"),
4094 ("--escape", "one\\ntwo"),
4095 ("--quoting-style=shell-escape", "'one'$'\\n''two'"),
4096 ("--quoting-style=shell-escape-always", "'one'$'\\n''two'"),
4097 ("--quoting-style=shell-escape-alway", "'one'$'\\n''two'"),
4098 ("--quoting-style=shell-escape-a", "'one'$'\\n''two'"),
4099 ("--quoting-style=shell", "'one?two'"),
4100 ("--quoting-style=shell-always", "'one?two'"),
4101 ("--quoting-style=shell-a", "'one?two'"),
4102 ] {
4103 scene
4104 .ucmd()
4105 .arg("--hide-control-chars")
4106 .arg(arg)
4107 .arg("one\ntwo")
4108 .succeeds()
4109 .stdout_only(format!("{correct}\n"));
4110 }
4111
4112 for (arg, correct) in [
4113 ("--quoting-style=literal", "one\ntwo"),
4114 ("-N", "one\ntwo"),
4115 ("--literal", "one\ntwo"),
4116 ("--l", "one\ntwo"),
4117 ("--quoting-style=shell", "'one\ntwo'"),
4118 ("--quoting-style=shell-always", "'one\ntwo'"),
4119 ] {
4120 scene
4121 .ucmd()
4122 .arg(arg)
4123 .arg("--show-control-chars")
4124 .arg("one\ntwo")
4125 .succeeds()
4126 .stdout_only(format!("{correct}\n"));
4127 }
4128
4129 for (arg, correct) in [
4130 ("--quoting-style=literal", "one\\two"),
4131 ("-N", "one\\two"),
4132 ("--quoting-style=c", "\"one\\\\two\""),
4133 ("-Q", "\"one\\\\two\""),
4134 ("--quote-name", "\"one\\\\two\""),
4135 ("--quoting-style=escape", "one\\\\two"),
4136 ("-b", "one\\\\two"),
4137 ("--quoting-style=shell-escape", "'one\\two'"),
4138 ("--quoting-style=shell-escape-always", "'one\\two'"),
4139 ("--quoting-style=shell", "'one\\two'"),
4140 ("--quoting-style=shell-always", "'one\\two'"),
4141 ] {
4142 scene
4143 .ucmd()
4144 .arg("--hide-control-chars")
4145 .arg(arg)
4146 .arg("one\\two")
4147 .succeeds()
4148 .stdout_only(format!("{correct}\n"));
4149 }
4150
4151 // Tests for a character that forces quotation in shell-style escaping
4152 // after a character in a dollar expression
4153 at.touch("one\n&two");
4154 for (arg, correct) in [
4155 ("--quoting-style=shell-escape", "'one'$'\\n''&two'"),
4156 ("--quoting-style=shell-escape-always", "'one'$'\\n''&two'"),
4157 ] {
4158 scene
4159 .ucmd()
4160 .arg("--hide-control-chars")
4161 .arg(arg)
4162 .arg("one\n&two")
4163 .succeeds()
4164 .stdout_only(format!("{correct}\n"));
4165 }
4166 }
4167
4168 // No-TTY
4169 scene
4170 .ucmd()
4171 .arg("one two")
4172 .succeeds()
4173 .stdout_only("one two\n");
4174
4175 // TTY
4176 #[cfg(unix)]
4177 scene
4178 .ucmd()
4179 .arg("one two")
4180 .terminal_simulation(true)
4181 .succeeds()
4182 .stdout_only("'one two'\r\n");
4183
4184 for (arg, correct) in [
4185 ("--quoting-style=literal", "one two"),
4186 ("-N", "one two"),
4187 ("--literal", "one two"),
4188 ("--l", "one two"),
4189 ("--quoting-style=c", "\"one two\""),
4190 ("-Q", "\"one two\""),
4191 ("--quote-name", "\"one two\""),
4192 ("--quoting-style=escape", "one\\ two"),
4193 ("-b", "one\\ two"),
4194 ("--escape", "one\\ two"),
4195 ("--quoting-style=shell-escape", "'one two'"),
4196 ("--quoting-style=shell-escape-always", "'one two'"),
4197 ("--quoting-style=shell", "'one two'"),
4198 ("--quoting-style=shell-always", "'one two'"),
4199 ] {
4200 scene
4201 .ucmd()
4202 .arg("--hide-control-chars")
4203 .arg(arg)
4204 .arg("one two")
4205 .succeeds()
4206 .stdout_only(format!("{correct}\n"));
4207 }
4208
4209 scene.ucmd().arg("one").succeeds().stdout_only("one\n");
4210
4211 for (arg, correct) in [
4212 ("--quoting-style=literal", "one"),
4213 ("-N", "one"),
4214 ("--quoting-style=c", "\"one\""),
4215 ("-Q", "\"one\""),
4216 ("--quote-name", "\"one\""),
4217 ("--quoting-style=escape", "one"),
4218 ("-b", "one"),
4219 ("--quoting-style=shell-escape", "one"),
4220 ("--quoting-style=shell-escape-always", "'one'"),
4221 ("--quoting-style=shell", "one"),
4222 ("--quoting-style=shell-always", "'one'"),
4223 ] {
4224 scene
4225 .ucmd()
4226 .arg("--hide-control-chars")
4227 .arg(arg)
4228 .arg("one")
4229 .succeeds()
4230 .stdout_only(format!("{correct}\n"));
4231 }
4232 }
4233
4234 #[test]
4235 fn test_ls_quoting_style_env_var_default() {
4236 let scene = TestScenario::new(util_name!());
4237 let at = &scene.fixtures;
4238 at.touch(at.plus_as_string("foo-1"));
4239 at.touch(at.plus_as_string("bar-2"));
4240
4241 // If no quoting style argument is provided, the QUOTING_STYLE environment variable
4242 // shall be used.
4243
4244 let correct_c = "\"bar-2\"\n\"foo-1\"";
4245 scene
4246 .ucmd()
4247 .env("QUOTING_STYLE", "c")
4248 .succeeds()
4249 .stdout_only(format!("{correct_c}\n"));
4250 }
4251
4252 // An unwritable stderr must not turn the QUOTING_STYLE warning into an abort:
4253 // the diagnostic is best-effort, so a failed write is dropped and the listing
4254 // still goes out. /dev/full is Linux-only.
4255 #[cfg(target_os = "linux")]
4256 #[test]
4257 fn test_ls_invalid_quoting_style_env_var_with_unwritable_stderr() {
4258 let scene = TestScenario::new(util_name!());
4259 let at = &scene.fixtures;
4260 at.touch("zeta");
4261 at.touch("alpha");
4262
4263 let dev_full = std::fs::OpenOptions::new()
4264 .write(true)
4265 .open("/dev/full")
4266 .unwrap();
4267
4268 scene
4269 .ucmd()
4270 .env("QUOTING_STYLE", "not-a-style")
4271 .set_stderr(dev_full)
4272 .succeeds()
4273 .stdout_is("alpha\nzeta\n");
4274 }
4275
4276 #[test]
4277 fn test_ls_quoting_style_arg_overrides_env_var() {
4278 let scene = TestScenario::new(util_name!());
4279 let at = &scene.fixtures;
4280 at.touch(at.plus_as_string("foo-1"));
4281 at.touch(at.plus_as_string("bar-2"));
4282
4283 // The quoting style given by the env variable should be
4284 // overridden by any escape style provided by argument.
4285 for (arg, correct) in [
4286 ("--quoting-style=literal", "foo-1"),
4287 ("-N", "foo-1"),
4288 ("--quoting-style=escape", "foo-1"),
4289 ("-b", "foo-1"),
4290 ("--quoting-style=shell-escape", "foo-1"),
4291 ("--quoting-style=shell-escape-always", "'foo-1'"),
4292 ("--quoting-style=shell", "foo-1"),
4293 ("--quoting-style=shell-always", "'foo-1'"),
4294 ] {
4295 scene
4296 .ucmd()
4297 .env("QUOTING_STYLE", "c")
4298 .arg("--hide-control-chars")
4299 .arg(arg)
4300 .arg("foo-1")
4301 .succeeds()
4302 .stdout_only(format!("{correct}\n"));
4303 }
4304
4305 // Another loop to check for the C quoting style that is used as a default above.
4306 for (arg, correct) in [
4307 ("--quoting-style=c", "\"foo-1\""),
4308 ("-Q", "\"foo-1\""),
4309 ("--quote-name", "\"foo-1\""),
4310 ] {
4311 scene
4312 .ucmd()
4313 .env("QUOTING_STYLE", "literal")
4314 .arg("--hide-control-chars")
4315 .arg(arg)
4316 .arg("foo-1")
4317 .succeeds()
4318 .stdout_only(format!("{correct}\n"));
4319 }
4320 }
4321
4322 #[test]
4323 fn test_ls_quoting_and_color() {
4324 let scene = TestScenario::new(util_name!());
4325 let at = &scene.fixtures;
4326
4327 at.touch("one two");
4328
4329 // No-TTY
4330 scene
4331 .ucmd()
4332 .arg("--color")
4333 .arg("one two")
4334 .succeeds()
4335 .stdout_only("one two\n");
4336
4337 // TTY
4338 #[cfg(unix)]
4339 scene
4340 .ucmd()
4341 .arg("--color")
4342 .arg("one two")
4343 .terminal_simulation(true)
4344 .succeeds()
4345 .stdout_only("'one two'\r\n");
4346 }
4347
4348 #[test]
4349 fn test_ls_align_unquoted() {
4350 let scene = TestScenario::new(util_name!());
4351 let at = &scene.fixtures;
4352
4353 at.touch("elf two");
4354 at.touch("foobar");
4355 at.touch("CAPS");
4356 at.touch("'quoted'");
4357
4358 // In TTY
4359 #[cfg(unix)]
4360 scene
4361 .ucmd()
4362 .arg("--color")
4363 .terminal_simulation(true)
4364 .succeeds()
4365 .stdout_only("\"'quoted'\" CAPS 'elf two' foobar\r\n");
4366 // ^ ^ ^
4367 // space no-space space
4368
4369 // The same should happen with format columns/across
4370 // and shell quoting style, except for the `\r` at the end.
4371 for format in &["--format=column", "--format=across"] {
4372 scene
4373 .ucmd()
4374 .arg("--color")
4375 .arg(format)
4376 .arg("--quoting-style=shell")
4377 .succeeds()
4378 .stdout_only("\"'quoted'\" CAPS 'elf two' foobar\n");
4379 // ^ ^ ^
4380 // space no-space space
4381 }
4382 }
4383
4384 #[test]
4385 fn test_ls_color_does_not_make_quoted_names_align_as_unquoted() {
4386 let scene = TestScenario::new(util_name!());
4387 let at = &scene.fixtures;
4388
4389 at.mkdir("dir one");
4390 at.touch("file one");
4391
4392 let args = ["-C", "-T0", "-w=80", "--quoting-style=shell-escape-always"];
4393
4394 let plain = scene
4395 .ucmd()
4396 .args(&args)
4397 .arg("--color=never")
4398 .succeeds()
4399 .stdout_move_str();
4400 let colored = scene
4401 .ucmd()
4402 .args(&args)
4403 .arg("--color=always")
4404 .succeeds()
4405 .stdout_move_str();
4406
4407 let ansi_re = Regex::new(r"\x1b\[[0-9;]*[A-Za-z]").unwrap();
4408 assert_eq!(ansi_re.replace_all(&colored, ""), plain);
4409
4410 let long_args = ["-l", "--quoting-style=shell-escape-always"];
4411 let plain = scene
4412 .ucmd()
4413 .args(&long_args)
4414 .arg("--color=never")
4415 .succeeds()
4416 .stdout_move_str();
4417 let colored = scene
4418 .ucmd()
4419 .args(&long_args)
4420 .arg("--color=always")
4421 .succeeds()
4422 .stdout_move_str();
4423
4424 assert_eq!(ansi_re.replace_all(&colored, ""), plain);
4425 }
4426
4427 #[test]
4428 fn test_ls_align_unquoted_multiline() {
4429 let scene = TestScenario::new(util_name!());
4430 let at = &scene.fixtures;
4431
4432 at.touch("one");
4433 at.touch("two");
4434 at.touch("three_long");
4435 at.touch("four_long");
4436 at.touch("five");
4437 at.touch("s ix");
4438 at.touch("s even");
4439 at.touch("eight_long_long");
4440 at.touch("nine");
4441 at.touch("ten");
4442
4443 // In TTY
4444 #[cfg(unix)]
4445 scene
4446 .ucmd()
4447 .arg("--color")
4448 .terminal_simulation(true)
4449 .succeeds()
4450 .stdout_only(concat!(
4451 " eight_long_long four_long one 's ix' three_long\r\n",
4452 " five nine 's even' ten two\r\n"
4453 ));
4454 }
4455
4456 #[test]
4457 fn test_ls_ignore_hide() {
4458 let scene = TestScenario::new(util_name!());
4459 let at = &scene.fixtures;
4460
4461 at.touch("README.md");
4462 at.touch("CONTRIBUTING.md");
4463 at.touch("some_other_file");
4464 at.touch("READMECAREFULLY.md");
4465
4466 scene
4467 .ucmd()
4468 .arg("--hide=*")
4469 .arg("-1")
4470 .succeeds()
4471 .stdout_only("");
4472
4473 scene
4474 .ucmd()
4475 .arg("--ignore=*")
4476 .arg("-1")
4477 .succeeds()
4478 .stdout_only("");
4479
4480 scene
4481 .ucmd()
4482 .arg("--ignore=irrelevant pattern")
4483 .arg("-1")
4484 .succeeds()
4485 .stdout_only("CONTRIBUTING.md\nREADME.md\nREADMECAREFULLY.md\nsome_other_file\n");
4486
4487 scene
4488 .ucmd()
4489 .arg("--ignore=README*.md")
4490 .arg("-1")
4491 .succeeds()
4492 .stdout_only("CONTRIBUTING.md\nsome_other_file\n");
4493
4494 scene
4495 .ucmd()
4496 .arg("--hide=README*.md")
4497 .arg("-1")
4498 .succeeds()
4499 .stdout_only("CONTRIBUTING.md\nsome_other_file\n");
4500
4501 scene
4502 .ucmd()
4503 .arg("--ignore=*.md")
4504 .arg("-1")
4505 .succeeds()
4506 .stdout_only("some_other_file\n");
4507
4508 scene
4509 .ucmd()
4510 .arg("-a")
4511 .arg("--ignore=*.md")
4512 .arg("-1")
4513 .succeeds()
4514 .stdout_only(".\n..\nsome_other_file\n");
4515
4516 scene
4517 .ucmd()
4518 .arg("-a")
4519 .arg("--hide=*.md")
4520 .arg("-1")
4521 .succeeds()
4522 .stdout_only(".\n..\nCONTRIBUTING.md\nREADME.md\nREADMECAREFULLY.md\nsome_other_file\n");
4523
4524 scene
4525 .ucmd()
4526 .arg("-A")
4527 .arg("--ignore=*.md")
4528 .arg("-1")
4529 .succeeds()
4530 .stdout_only("some_other_file\n");
4531
4532 scene
4533 .ucmd()
4534 .arg("-A")
4535 .arg("--hide=*.md")
4536 .arg("-1")
4537 .succeeds()
4538 .stdout_only("CONTRIBUTING.md\nREADME.md\nREADMECAREFULLY.md\nsome_other_file\n");
4539
4540 // Stacking multiple patterns
4541 scene
4542 .ucmd()
4543 .arg("--ignore=README*")
4544 .arg("--ignore=CONTRIBUTING*")
4545 .arg("-1")
4546 .succeeds()
4547 .stdout_only("some_other_file\n");
4548
4549 scene
4550 .ucmd()
4551 .arg("--hide=README*")
4552 .arg("--ignore=CONTRIBUTING*")
4553 .arg("-1")
4554 .succeeds()
4555 .stdout_only("some_other_file\n");
4556
4557 scene
4558 .ucmd()
4559 .arg("--hide=README*")
4560 .arg("--hide=CONTRIBUTING*")
4561 .arg("-1")
4562 .succeeds()
4563 .stdout_only("some_other_file\n");
4564
4565 // Invalid patterns
4566 scene
4567 .ucmd()
4568 .arg("--ignore=READ[ME")
4569 .arg("-1")
4570 .succeeds()
4571 .stderr_contains("Invalid pattern")
4572 .stdout_is("CONTRIBUTING.md\nREADME.md\nREADMECAREFULLY.md\nsome_other_file\n");
4573
4574 scene
4575 .ucmd()
4576 .arg("--hide=READ[ME")
4577 .arg("-1")
4578 .succeeds()
4579 .stderr_contains("Invalid pattern")
4580 .stdout_is("CONTRIBUTING.md\nREADME.md\nREADMECAREFULLY.md\nsome_other_file\n");
4581 }
4582
4583 #[test]
4584 #[cfg(unix)]
4585 fn test_ls_ignore_backups() {
4586 let scene = TestScenario::new(util_name!());
4587 let at = &scene.fixtures;
4588
4589 at.touch("somefile");
4590 at.touch("somebackup~");
4591 at.touch(".somehiddenfile");
4592 at.touch(".somehiddenbackup~");
4593
4594 scene.ucmd().arg("-B").succeeds().stdout_is("somefile\n");
4595 scene
4596 .ucmd()
4597 .arg("--ignore-backups")
4598 .succeeds()
4599 .stdout_is("somefile\n");
4600
4601 scene
4602 .ucmd()
4603 .arg("-aB")
4604 .succeeds()
4605 .stdout_contains(".somehiddenfile")
4606 .stdout_contains("somefile")
4607 .stdout_does_not_contain("somebackup")
4608 .stdout_does_not_contain(".somehiddenbackup~");
4609
4610 scene
4611 .ucmd()
4612 .arg("-a")
4613 .arg("--ignore-backups")
4614 .succeeds()
4615 .stdout_contains(".somehiddenfile")
4616 .stdout_contains("somefile")
4617 .stdout_does_not_contain("somebackup")
4618 .stdout_does_not_contain(".somehiddenbackup~");
4619 }
4620
4621 // This test fails on windows, see details at #3985
4622 #[cfg(not(windows))]
4623 #[test]
4624 fn test_ls_ignore_explicit_period() {
4625 // In ls ignore patterns, leading periods must be explicitly specified
4626 let scene = TestScenario::new(util_name!());
4627
4628 let at = &scene.fixtures;
4629 at.touch(".hidden.yml");
4630 at.touch("regular.yml");
4631
4632 scene
4633 .ucmd()
4634 .arg("-a")
4635 .arg("--ignore")
4636 .arg("?hidden.yml")
4637 .succeeds()
4638 .stdout_contains(".hidden.yml")
4639 .stdout_contains("regular.yml");
4640
4641 scene
4642 .ucmd()
4643 .arg("-a")
4644 .arg("--ignore")
4645 .arg("*.yml")
4646 .succeeds()
4647 .stdout_contains(".hidden.yml")
4648 .stdout_does_not_contain("regular.yml");
4649
4650 // Leading period is explicitly specified
4651 scene
4652 .ucmd()
4653 .arg("-a")
4654 .arg("--ignore")
4655 .arg(".*.yml")
4656 .succeeds()
4657 .stdout_does_not_contain(".hidden.yml")
4658 .stdout_contains("regular.yml");
4659 }
4660
4661 // This test fails on windows, see details at #3985
4662 #[cfg(not(windows))]
4663 #[test]
4664 fn test_ls_ignore_negation() {
4665 let scene = TestScenario::new(util_name!());
4666
4667 let at = &scene.fixtures;
4668 at.touch("apple");
4669 at.touch("boy");
4670
4671 scene
4672 .ucmd()
4673 .arg("--ignore")
4674 .arg("[!a]*")
4675 .succeeds()
4676 .stdout_contains("apple")
4677 .stdout_does_not_contain("boy");
4678
4679 scene
4680 .ucmd()
4681 .arg("--ignore")
4682 .arg("[^a]*")
4683 .succeeds()
4684 .stdout_contains("apple")
4685 .stdout_does_not_contain("boy");
4686 }
4687
4688 #[test]
4689 fn test_ls_directory() {
4690 let scene = TestScenario::new(util_name!());
4691 let at = &scene.fixtures;
4692
4693 at.mkdir("some_dir");
4694 at.symlink_dir("some_dir", "sym_dir");
4695
4696 at.touch(Path::new("some_dir").join("nested_file").to_str().unwrap());
4697
4698 scene
4699 .ucmd()
4700 .arg("some_dir")
4701 .succeeds()
4702 .stdout_is("nested_file\n");
4703
4704 scene
4705 .ucmd()
4706 .arg("--directory")
4707 .arg("some_dir")
4708 .succeeds()
4709 .stdout_is("some_dir\n");
4710
4711 scene
4712 .ucmd()
4713 .arg("sym_dir")
4714 .succeeds()
4715 .stdout_is("nested_file\n");
4716 }
4717
4718 #[test]
4719 fn test_ls_deref_command_line() {
4720 let scene = TestScenario::new(util_name!());
4721 let at = &scene.fixtures;
4722
4723 at.touch("some_file");
4724 at.symlink_file("some_file", "sym_file");
4725
4726 scene
4727 .ucmd()
4728 .arg("sym_file")
4729 .succeeds()
4730 .stdout_is("sym_file\n");
4731
4732 // -l changes the default to no dereferencing
4733 scene
4734 .ucmd()
4735 .arg("-l")
4736 .arg("sym_file")
4737 .succeeds()
4738 .stdout_contains("sym_file ->");
4739
4740 scene
4741 .ucmd()
4742 .arg("--dereference-command-line-symlink-to-dir")
4743 .arg("sym_file")
4744 .succeeds()
4745 .stdout_is("sym_file\n");
4746
4747 scene
4748 .ucmd()
4749 .arg("-l")
4750 .arg("--dereference-command-line-symlink-to-dir")
4751 .arg("sym_file")
4752 .succeeds()
4753 .stdout_contains("sym_file ->");
4754
4755 scene
4756 .ucmd()
4757 .arg("--dereference-command-line")
4758 .arg("sym_file")
4759 .succeeds()
4760 .stdout_is("sym_file\n");
4761
4762 let result = scene
4763 .ucmd()
4764 .arg("-l")
4765 .arg("--dereference-command-line")
4766 .arg("sym_file")
4767 .succeeds();
4768
4769 assert!(!result.stdout_str().contains("->"));
4770
4771 let result = scene.ucmd().arg("-lH").arg("sym_file").succeeds();
4772
4773 assert!(!result.stdout_str().contains("sym_file ->"));
4774
4775 // If the symlink is not a command line argument, it must be shown normally
4776 scene
4777 .ucmd()
4778 .arg("-l")
4779 .arg("--dereference-command-line")
4780 .succeeds()
4781 .stdout_contains("sym_file ->");
4782 }
4783
4784 #[test]
4785 fn test_ls_deref_command_line_dir() {
4786 let scene = TestScenario::new(util_name!());
4787 let at = &scene.fixtures;
4788
4789 at.mkdir("some_dir");
4790 at.symlink_dir("some_dir", "sym_dir");
4791
4792 at.touch(Path::new("some_dir").join("nested_file").to_str().unwrap());
4793
4794 scene
4795 .ucmd()
4796 .arg("sym_dir")
4797 .succeeds()
4798 .stdout_contains("nested_file");
4799
4800 scene
4801 .ucmd()
4802 .arg("-l")
4803 .arg("sym_dir")
4804 .succeeds()
4805 .stdout_contains("sym_dir ->");
4806
4807 scene
4808 .ucmd()
4809 .arg("--dereference-command-line-symlink-to-dir")
4810 .arg("sym_dir")
4811 .succeeds()
4812 .stdout_contains("nested_file");
4813
4814 scene
4815 .ucmd()
4816 .arg("-l")
4817 .arg("--dereference-command-line-symlink-to-dir")
4818 .arg("sym_dir")
4819 .succeeds()
4820 .stdout_contains("nested_file");
4821
4822 scene
4823 .ucmd()
4824 .arg("--dereference-command-line")
4825 .arg("sym_dir")
4826 .succeeds()
4827 .stdout_contains("nested_file");
4828
4829 scene
4830 .ucmd()
4831 .arg("-l")
4832 .arg("--dereference-command-line")
4833 .arg("sym_dir")
4834 .succeeds()
4835 .stdout_contains("nested_file");
4836
4837 scene
4838 .ucmd()
4839 .arg("-lH")
4840 .arg("sym_dir")
4841 .succeeds()
4842 .stdout_contains("nested_file");
4843
4844 // If the symlink is not a command line argument, it must be shown normally
4845 scene
4846 .ucmd()
4847 .arg("-l")
4848 .arg("--dereference-command-line")
4849 .succeeds()
4850 .stdout_contains("sym_dir ->");
4851
4852 scene
4853 .ucmd()
4854 .arg("-lH")
4855 .succeeds()
4856 .stdout_contains("sym_dir ->");
4857
4858 scene
4859 .ucmd()
4860 .arg("-l")
4861 .arg("--dereference-command-line-symlink-to-dir")
4862 .succeeds()
4863 .stdout_contains("sym_dir ->");
4864
4865 // --directory does not dereference anything by default
4866 scene
4867 .ucmd()
4868 .arg("-l")
4869 .arg("--directory")
4870 .arg("sym_dir")
4871 .succeeds()
4872 .stdout_contains("sym_dir ->");
4873
4874 let result = scene
4875 .ucmd()
4876 .arg("-l")
4877 .arg("--directory")
4878 .arg("--dereference-command-line-symlink-to-dir")
4879 .arg("sym_dir")
4880 .succeeds();
4881
4882 assert!(!result.stdout_str().ends_with("sym_dir"));
4883
4884 // --classify does not dereference anything by default
4885 scene
4886 .ucmd()
4887 .arg("-l")
4888 .arg("--directory")
4889 .arg("sym_dir")
4890 .succeeds()
4891 .stdout_contains("sym_dir ->");
4892
4893 let result = scene
4894 .ucmd()
4895 .arg("-l")
4896 .arg("--directory")
4897 .arg("--dereference-command-line-symlink-to-dir")
4898 .arg("sym_dir")
4899 .succeeds();
4900
4901 assert!(!result.stdout_str().ends_with("sym_dir"));
4902 }
4903
4904 #[test]
4905 fn test_ls_sort_extension() {
4906 let scene = TestScenario::new(util_name!());
4907 let at = &scene.fixtures;
4908 for filename in [
4909 "file1",
4910 "file2",
4911 "anotherFile",
4912 ".hidden",
4913 ".file.1",
4914 ".file.2",
4915 "file.1",
4916 "file.2",
4917 "anotherFile.1",
4918 "anotherFile.2",
4919 "file.ext",
4920 "file.debug",
4921 "anotherFile.ext",
4922 "anotherFile.debug",
4923 ] {
4924 at.touch(filename);
4925 }
4926
4927 let expected = vec![
4928 ".",
4929 "..",
4930 ".hidden",
4931 "anotherFile",
4932 "file1",
4933 "file2",
4934 ".file.1",
4935 "anotherFile.1",
4936 "file.1",
4937 ".file.2",
4938 "anotherFile.2",
4939 "file.2",
4940 "anotherFile.debug",
4941 "file.debug",
4942 "anotherFile.ext",
4943 "file.ext",
4944 "", // because of '\n' at the end of the output
4945 ];
4946
4947 let result = scene.ucmd().arg("-1aX").succeeds();
4948 assert_eq!(
4949 result.stdout_str().split('\n').collect::<Vec<_>>(),
4950 expected,
4951 );
4952
4953 let result = scene.ucmd().arg("-1a").arg("--sort=extension").succeeds();
4954 assert_eq!(
4955 result.stdout_str().split('\n').collect::<Vec<_>>(),
4956 expected,
4957 );
4958 }
4959
4960 #[test]
4961 fn test_ls_path() {
4962 let scene = TestScenario::new(util_name!());
4963 let at = &scene.fixtures;
4964
4965 let file1 = "file1";
4966 let file2 = "file2";
4967 let dir = "dir";
4968 let path = &format!("{dir}/{file2}");
4969
4970 at.mkdir(dir);
4971 at.touch(file1);
4972 at.touch(path);
4973
4974 let expected_stdout = &format!("{path}\n");
4975 scene.ucmd().arg(path).succeeds().stdout_is(expected_stdout);
4976
4977 let expected_stdout = &format!("./{path}\n");
4978 scene
4979 .ucmd()
4980 .arg(format!("./{path}"))
4981 .succeeds()
4982 .stdout_is(expected_stdout);
4983
4984 let abs_path = format!("{}/{path}", at.as_string());
4985 let expected_stdout = format!("{abs_path}\n");
4986
4987 scene
4988 .ucmd()
4989 .arg(&abs_path)
4990 .succeeds()
4991 .stdout_is(expected_stdout);
4992
4993 let expected_stdout = format!("{path}\n{file1}\n");
4994 scene
4995 .ucmd()
4996 .arg(file1)
4997 .arg(path)
4998 .succeeds()
4999 .stdout_is(expected_stdout);
5000 }
5001
5002 #[test]
5003 fn test_ls_dangling_symlinks() {
5004 let scene = TestScenario::new(util_name!());
5005 let at = &scene.fixtures;
5006
5007 at.mkdir("temp_dir");
5008 at.symlink_file("does_not_exist", "temp_dir/dangle");
5009
5010 scene
5011 .ucmd()
5012 .arg("-L")
5013 .arg("temp_dir/dangle")
5014 .fails_with_code(2);
5015 scene
5016 .ucmd()
5017 .arg("-H")
5018 .arg("temp_dir/dangle")
5019 .fails_with_code(2);
5020
5021 scene
5022 .ucmd()
5023 .arg("temp_dir/dangle")
5024 .succeeds()
5025 .stdout_contains("dangle");
5026
5027 scene
5028 .ucmd()
5029 .arg("-Li")
5030 .arg("temp_dir")
5031 .fails_with_code(1)
5032 .stderr_contains("cannot access")
5033 .stderr_contains("No such file or directory")
5034 .stdout_contains(if cfg!(windows) { "dangle" } else { "? dangle" });
5035
5036 scene
5037 .ucmd()
5038 .arg("-LZ")
5039 .arg("temp_dir")
5040 .fails_with_code(1)
5041 .stderr_contains("cannot access")
5042 .stderr_contains("No such file or directory")
5043 .stdout_contains(if cfg!(windows) { "dangle" } else { "? dangle" });
5044
5045 scene
5046 .ucmd()
5047 .arg("-Ll")
5048 .arg("temp_dir")
5049 .fails_with_code(1)
5050 .stdout_contains("l?????????");
5051
5052 #[cfg(unix)]
5053 {
5054 // Check padding is the same for real files and dangling links, in non-long formats
5055 at.touch("temp_dir/real_file");
5056
5057 let real_file_res = scene.ucmd().arg("-Li1").arg("temp_dir").fails_with_code(1);
5058 let real_file_stdout_len = String::from_utf8(real_file_res.stdout().to_owned())
5059 .ok()
5060 .unwrap()
5061 .lines()
5062 .nth(1)
5063 .unwrap()
5064 .strip_suffix("real_file")
5065 .unwrap()
5066 .len();
5067
5068 let dangle_file_res = scene.ucmd().arg("-Li1").arg("temp_dir").fails_with_code(1);
5069 let dangle_stdout_len = String::from_utf8(dangle_file_res.stdout().to_owned())
5070 .ok()
5071 .unwrap()
5072 .lines()
5073 .next()
5074 .unwrap()
5075 .strip_suffix("dangle")
5076 .unwrap()
5077 .len();
5078
5079 assert_eq!(real_file_stdout_len, dangle_stdout_len);
5080 }
5081 }
5082
5083 #[test]
5084 fn test_ls_long_self_referential_dir_lists_contents() {
5085 // `ls -l` for a directory referenced via `.` (e.g. run from inside a symlinked
5086 // directory) must list its contents, not show a `. -> target` link entry. On
5087 // Windows/Redox a `.` in a symlinked dir was reported as the symlink itself
5088 // (issues #6467, #7873). A named symlink-to-dir argument must still be a link.
5089 let scene = TestScenario::new(util_name!());
5090 let at = &scene.fixtures;
5091
5092 at.mkdir("real");
5093 at.touch("real/inside");
5094 at.symlink_dir("real", "link");
5095
5096 // Run from inside the symlinked directory: the implicit `.` is the directory
5097 // itself, so its contents must be listed, never shown as a `-> target` link.
5098 scene
5099 .ucmd()
5100 .arg("-l")
5101 .current_dir(at.plus("link"))
5102 .succeeds()
5103 .stdout_contains("inside")
5104 .stdout_does_not_contain("-> ");
5105
5106 // A named symlink-to-dir argument is still shown as a link, not dereferenced.
5107 scene
5108 .ucmd()
5109 .arg("-l")
5110 .arg("link")
5111 .succeeds()
5112 .stdout_contains("link ->");
5113 }
5114
5115 #[test]
5116 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
5117 fn test_ls_context1() {
5118 if !uucore::selinux::is_selinux_enabled() {
5119 println!("test skipped: Kernel has no support for SElinux context");
5120 return;
5121 }
5122
5123 let file = "test_ls_context_file";
5124 let expected = format!("unconfined_u:object_r:user_tmp_t:s0 {file}\n");
5125 let (at, mut ucmd) = at_and_ucmd!();
5126 at.touch(file);
5127 ucmd.args(&["-Z", file]).succeeds().stdout_is(expected);
5128 }
5129
5130 #[test]
5131 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
5132 fn test_ls_context2() {
5133 if !uucore::selinux::is_selinux_enabled() {
5134 println!("test skipped: Kernel has no support for SElinux context");
5135 return;
5136 }
5137 let ts = TestScenario::new(util_name!());
5138 for c_flag in ["-Z", "--context"] {
5139 ts.ucmd()
5140 .args(&[c_flag, "/"])
5141 .succeeds()
5142 .stdout_only(unwrap_or_return!(expected_result(&ts, &[c_flag, "/"])).stdout_str());
5143 }
5144 }
5145
5146 #[test]
5147 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
5148 fn test_ls_context_long() {
5149 if !uucore::selinux::is_selinux_enabled() {
5150 return;
5151 }
5152 let scene = TestScenario::new(util_name!());
5153 let at = &scene.fixtures;
5154 at.touch("foo");
5155 for c_flag in ["-Zl", "-Zal"] {
5156 let result = scene.ucmd().args(&[c_flag, "foo"]).succeeds();
5157
5158 let line: Vec<_> = result.stdout_str().split(' ').collect();
5159 assert!(line[0].ends_with('.'));
5160 assert!(line[4].starts_with("unconfined_u"));
5161 validate_selinux_context(line[4]);
5162 }
5163 }
5164
5165 #[test]
5166 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
5167 fn test_ls_context_format() {
5168 if !uucore::selinux::is_selinux_enabled() {
5169 println!("test skipped: Kernel has no support for SElinux context");
5170 return;
5171 }
5172 let ts = TestScenario::new(util_name!());
5173 // NOTE:
5174 // --format=long/verbose matches the output of GNU's ls for --context
5175 // except for the size count which may differ to the size count reported by GNU's ls.
5176 for word in [
5177 "across",
5178 "commas",
5179 "horizontal",
5180 // "long",
5181 "single-column",
5182 // "verbose",
5183 "vertical",
5184 ] {
5185 let format = format!("--format={word}");
5186 ts.ucmd()
5187 .args(&["-Z", format.as_str(), "/"])
5188 .succeeds()
5189 .stdout_only(
5190 unwrap_or_return!(expected_result(&ts, &["-Z", format.as_str(), "/"])).stdout_str(),
5191 );
5192 }
5193 }
5194
5195 /// Helper function to validate `SELinux` context format
5196 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
5197 fn validate_selinux_context(context: &str) {
5198 assert!(
5199 context.contains(':'),
5200 "Expected SELinux context format (user:role:type:level), got: {context}"
5201 );
5202
5203 assert_eq!(
5204 context.split(':').count(),
5205 4,
5206 "SELinux context should have 4 components separated by colons, got: {context}"
5207 );
5208 }
5209
5210 #[test]
5211 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
5212 fn test_ls_selinux_context_format() {
5213 if !uucore::selinux::is_selinux_enabled() {
5214 println!("test skipped: Kernel has no support for SElinux context");
5215 return;
5216 }
5217
5218 let scene = TestScenario::new(util_name!());
5219 let at = &scene.fixtures;
5220
5221 at.touch("file");
5222 at.symlink_file("file", "link");
5223
5224 // Test that ls -lnZ properly shows the context
5225 for file in ["file", "link"] {
5226 let result = scene.ucmd().args(&["-lnZ", file]).succeeds();
5227 let output = result.stdout_str();
5228
5229 let lines: Vec<&str> = output.lines().collect();
5230 assert!(!lines.is_empty(), "Output should contain at least one line");
5231
5232 let first_line = lines[0];
5233 let parts: Vec<&str> = first_line.split_whitespace().collect();
5234 assert!(parts.len() >= 6, "Line should have at least 6 fields");
5235
5236 // The 5th field (0-indexed position 4) should contain the SELinux context
5237 // Format: permissions links owner group context size date time name
5238 let context = parts[4];
5239 validate_selinux_context(context);
5240 }
5241 }
5242
5243 #[test]
5244 #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))]
5245 fn test_ls_selinux_context_indicator() {
5246 if !uucore::selinux::is_selinux_enabled() {
5247 println!("test skipped: Kernel has no support for SElinux context");
5248 return;
5249 }
5250
5251 let scene = TestScenario::new(util_name!());
5252 let at = &scene.fixtures;
5253
5254 at.touch("file");
5255 at.symlink_file("file", "link");
5256
5257 // Test that ls -l shows "." indicator for files with SELinux contexts
5258 for file in ["file", "link"] {
5259 let result = scene.ucmd().args(&["-l", file]).succeeds();
5260 let output = result.stdout_str();
5261
5262 // The 11th character should be "." indicating SELinux context
5263 // -rw-rw-r--. (permissions + context indicator)
5264 let lines: Vec<&str> = output.lines().collect();
5265 assert!(!lines.is_empty(), "Output should contain at least one line");
5266
5267 let first_line = lines[0];
5268 let chars: Vec<char> = first_line.chars().collect();
5269 assert!(
5270 chars.len() >= 11,
5271 "Line should be at least 11 characters long"
5272 );
5273
5274 // The 11th character (0-indexed position 10) should be "." for SELinux context
5275 assert_eq!(
5276 chars[10], '.',
5277 "Expected '.' indicator for SELinux context in position 11, got '{}' in line: {first_line}",
5278 chars[10],
5279 );
5280 }
5281
5282 // Test that ls -lnZ properly shows the context
5283 for file in ["file", "link"] {
5284 let result = scene.ucmd().args(&["-lnZ", file]).succeeds();
5285 let output = result.stdout_str();
5286
5287 let lines: Vec<&str> = output.lines().collect();
5288 assert!(!lines.is_empty(), "Output should contain at least one line");
5289
5290 let first_line = lines[0];
5291 let parts: Vec<&str> = first_line.split_whitespace().collect();
5292 assert!(parts.len() >= 6, "Line should have at least 6 fields");
5293
5294 // The 5th field (0-indexed position 4) should contain the SELinux context
5295 // Format: permissions links owner group context size date time name
5296 validate_selinux_context(parts[4]);
5297 }
5298 }
5299
5300 #[test]
5301 #[allow(non_snake_case)]
5302 fn test_ls_a_A() {
5303 let scene = TestScenario::new(util_name!());
5304
5305 scene
5306 .ucmd()
5307 .arg("-A")
5308 .arg("-a")
5309 .succeeds()
5310 .stdout_contains(".")
5311 .stdout_contains("..");
5312
5313 scene
5314 .ucmd()
5315 .arg("-a")
5316 .arg("-A")
5317 .succeeds()
5318 .stdout_does_not_contain(".")
5319 .stdout_does_not_contain("..");
5320 }
5321
5322 #[test]
5323 #[allow(non_snake_case)]
5324 fn test_ls_multiple_a_A() {
5325 let scene = TestScenario::new(util_name!());
5326
5327 scene
5328 .ucmd()
5329 .arg("-a")
5330 .arg("-a")
5331 .succeeds()
5332 .stdout_contains(".")
5333 .stdout_contains("..");
5334
5335 scene
5336 .ucmd()
5337 .arg("-A")
5338 .arg("-A")
5339 .succeeds()
5340 .stdout_does_not_contain(".")
5341 .stdout_does_not_contain("..");
5342 }
5343
5344 #[test]
5345 #[cfg(feature = "ln")]
5346 fn test_ls_quoting() {
5347 let scene = TestScenario::new(util_name!());
5348
5349 scene
5350 .ccmd("ln")
5351 .arg("-s")
5352 .arg("'need quoting'")
5353 .arg("symlink")
5354 .succeeds();
5355 scene
5356 .ucmd()
5357 .arg("-l")
5358 .arg("--quoting-style=shell-escape")
5359 .arg("symlink")
5360 .succeeds()
5361 .stdout_contains("\'need quoting\'");
5362 }
5363
5364 #[test]
5365 #[cfg(feature = "ln")]
5366 fn test_ls_quoting_color() {
5367 let scene = TestScenario::new(util_name!());
5368
5369 scene
5370 .ccmd("ln")
5371 .arg("-s")
5372 .arg("'need quoting'")
5373 .arg("symlink")
5374 .succeeds();
5375 scene
5376 .ucmd()
5377 .arg("-l")
5378 .arg("--quoting-style=shell-escape")
5379 .arg("--color=auto")
5380 .arg("symlink")
5381 .succeeds()
5382 .stdout_contains("\'need quoting\'");
5383 }
5384
5385 #[test]
5386 fn test_ls_dereference_looped_symlinks_recursive() {
5387 let (at, mut ucmd) = at_and_ucmd!();
5388
5389 at.mkdir("loop");
5390 at.relative_symlink_dir("../loop", "loop/sub");
5391
5392 ucmd.args(&["-RL", "loop"])
5393 .fails_with_code(2)
5394 .stderr_contains("not listing already-listed directory");
5395 }
5396
5397 #[test]
5398 fn test_dereference_dangling_color() {
5399 let (at, mut ucmd) = at_and_ucmd!();
5400 at.relative_symlink_file("wat", "nonexistent");
5401 let out_exp = ucmd.args(&["--color"]).succeeds().stdout_move_str();
5402
5403 let (at, mut ucmd) = at_and_ucmd!();
5404 at.relative_symlink_file("wat", "nonexistent");
5405 ucmd.args(&["-L", "--color"])
5406 .fails_with_code(1)
5407 .stderr_contains("No such file or directory")
5408 .stdout_is(out_exp);
5409 }
5410
5411 #[test]
5412 fn test_dereference_symlink_dir_color() {
5413 let (at, mut ucmd) = at_and_ucmd!();
5414 at.mkdir("dir1");
5415 at.mkdir("dir1/link");
5416 let out_exp = ucmd.args(&["--color", "dir1"]).succeeds().stdout_move_str();
5417
5418 let (at, mut ucmd) = at_and_ucmd!();
5419 at.mkdir("dir1");
5420 at.mkdir("dir2");
5421 at.relative_symlink_dir("../dir2", "dir1/link");
5422 ucmd.args(&["-L", "--color", "dir1"])
5423 .succeeds()
5424 .stdout_is(out_exp);
5425 }
5426
5427 #[test]
5428 fn test_dereference_symlink_file_color() {
5429 let (at, mut ucmd) = at_and_ucmd!();
5430 at.mkdir("dir1");
5431 at.touch("dir1/link");
5432 let out_exp = ucmd.args(&["--color", "dir1"]).succeeds().stdout_move_str();
5433
5434 let (at, mut ucmd) = at_and_ucmd!();
5435 at.mkdir("dir1");
5436 at.touch("file");
5437 at.relative_symlink_file("../file", "dir1/link");
5438 ucmd.args(&["-L", "--color", "dir1"])
5439 .succeeds()
5440 .stdout_is(out_exp);
5441 }
5442
5443 /// Symlink chain target should be colored by final target type, not as symlink (#8934).
5444 #[test]
5445 fn test_symlink_chain_target_color() {
5446 let (at, mut ucmd) = at_and_ucmd!();
5447 at.touch("file");
5448 at.relative_symlink_file("file", "link1");
5449 at.relative_symlink_file("link1", "link2");
5450 let out = ucmd
5451 .args(&["-l", "--color=always", "link2"])
5452 .succeeds()
5453 .stdout_move_str();
5454 let target = out.split("->").nth(1).unwrap();
5455 assert!(!target.contains("36m")); // 36m = cyan (symlink color)
5456 }
5457
5458 /// Symlink target should be colored by extension (e.g., .tar.gz shows as archive color).
5459 #[test]
5460 fn test_symlink_target_extension_color() {
5461 let (at, mut ucmd) = at_and_ucmd!();
5462 at.touch("archive.tar.gz");
5463 at.relative_symlink_file("archive.tar.gz", "link");
5464 let out = ucmd
5465 .env("LS_COLORS", "*.tar.gz=31:or=33")
5466 .args(&["-l", "--color=always", "link"])
5467 .succeeds()
5468 .stdout_move_str();
5469 let target = out.split("->").nth(1).unwrap();
5470 assert!(target.contains("31m")); // 31 = red (our configured archive color)
5471 }
5472
5473 #[test]
5474 fn test_tabsize_option() {
5475 let scene = TestScenario::new(util_name!());
5476
5477 for valid in ["3", "0", "0xff"] {
5478 scene.ucmd().args(&["-T", valid]).succeeds();
5479 }
5480 scene.ucmd().args(&["--tabsize", "0"]).succeeds();
5481 for invalid in ["-3", "a", "3.14"] {
5482 scene
5483 .ucmd()
5484 .arg(format!("--tabsize={invalid}"))
5485 .fails()
5486 .stderr_is(format!("ls: invalid tab size: '{invalid}'\n"));
5487 }
5488 scene.ucmd().arg("-T").fails();
5489 }
5490
5491 #[test]
5492 fn test_tabsize_formatting() {
5493 let scene = TestScenario::new(util_name!());
5494 let at = &scene.fixtures;
5495
5496 at.touch("aaaaaaaa");
5497 at.touch("bbbb");
5498 at.touch("cccc");
5499 at.touch("dddddddd");
5500
5501 scene
5502 .ucmd()
5503 .args(&["-x", "-w18", "-T4"])
5504 .succeeds()
5505 .stdout_is("aaaaaaaa bbbb\ncccc\t dddddddd\n");
5506
5507 scene
5508 .ucmd()
5509 .args(&["-C", "-w18", "-T4"])
5510 .succeeds()
5511 .stdout_is("aaaaaaaa cccc\nbbbb\t dddddddd\n");
5512
5513 scene
5514 .ucmd()
5515 .args(&["-x", "-w18", "-T2"])
5516 .succeeds()
5517 .stdout_is("aaaaaaaa\tbbbb\ncccc\t\t\tdddddddd\n");
5518
5519 scene
5520 .ucmd()
5521 .args(&["-C", "-w18", "-T2"])
5522 .succeeds()
5523 .stdout_is("aaaaaaaa\tcccc\nbbbb\t\t\tdddddddd\n");
5524
5525 scene
5526 .ucmd()
5527 .args(&["-x", "-w18", "-T0"])
5528 .succeeds()
5529 .stdout_is("aaaaaaaa bbbb\ncccc dddddddd\n");
5530
5531 // use spaces
5532 scene
5533 .ucmd()
5534 .args(&["-C", "-w18", "-T0"])
5535 .succeeds()
5536 .stdout_is("aaaaaaaa cccc\nbbbb dddddddd\n");
5537 }
5538
5539 #[cfg(all(unix, not(target_os = "android")))]
5540 #[test]
5541 fn test_device_number() {
5542 use std::fs::{metadata, read_dir};
5543 use std::os::unix::fs::{FileTypeExt, MetadataExt};
5544 use uucore::libc::{dev_t, major, minor};
5545
5546 let dev_dir = read_dir("/dev").unwrap();
5547 // let's use the first device for test
5548 let blk_dev = dev_dir
5549 .map(|res_entry| res_entry.unwrap())
5550 .find(|entry| {
5551 entry.file_type().unwrap().is_block_device()
5552 || entry.file_type().unwrap().is_char_device()
5553 })
5554 .expect("Expect a block/char device");
5555 let blk_dev_path = blk_dev.path();
5556 let blk_dev_meta = metadata(blk_dev_path.as_path()).unwrap();
5557 let blk_dev_number = blk_dev_meta.rdev() as dev_t;
5558 let (major, minor) = (major(blk_dev_number), minor(blk_dev_number));
5559 let major_minor_str = format!("{major}, {minor}");
5560
5561 let scene = TestScenario::new(util_name!());
5562 scene
5563 .ucmd()
5564 .arg("-l")
5565 .arg(blk_dev_path.to_str().expect("should be UTF-8 encoded"))
5566 .succeeds()
5567 .stdout_contains(major_minor_str);
5568 }
5569
5570 #[test]
5571 #[cfg(target_os = "linux")]
5572 fn test_invalid_utf8() {
5573 let (at, mut ucmd) = at_and_ucmd!();
5574
5575 let filename = OsStr::from_bytes(b"-\xE0-foo");
5576 at.touch(filename);
5577 ucmd.succeeds();
5578 }
5579
5580 #[cfg(all(unix, feature = "chmod"))]
5581 #[test]
5582 fn test_ls_perm_io_errors() {
5583 let scene = TestScenario::new(util_name!());
5584 let at = &scene.fixtures;
5585 at.mkdir("d");
5586 at.symlink_file("/", "d/s");
5587 at.touch("d/f");
5588
5589 scene.ccmd("chmod").arg("600").arg("d").succeeds();
5590
5591 scene
5592 .ucmd()
5593 .arg("-l")
5594 .arg("d")
5595 .fails_with_code(1)
5596 .stderr_contains("Permission denied")
5597 .stdout_contains("total 0")
5598 .stdout_contains("l????????? ? ? ? ? ? s")
5599 .stdout_contains("-????????? ? ? ? ? ? f");
5600 }
5601
5602 #[test]
5603 fn test_ls_dired_implies_long() {
5604 let scene = TestScenario::new(util_name!());
5605
5606 scene
5607 .ucmd()
5608 .arg("--dired")
5609 .succeeds()
5610 .stdout_does_not_contain("//DIRED//")
5611 .stdout_contains(" total 0")
5612 .stdout_contains("//DIRED-OPTIONS// --quoting-style");
5613 }
5614
5615 #[test]
5616 fn test_ls_dired_hyperlink() {
5617 // we will have link but not the DIRED output
5618 // note that the order matters
5619 let scene = TestScenario::new(util_name!());
5620 let at = &scene.fixtures;
5621 at.mkdir("dir");
5622 at.touch("dir/a");
5623 scene
5624 .ucmd()
5625 .arg("--dired")
5626 .arg("--hyperlink")
5627 .arg("-R")
5628 .succeeds()
5629 .stdout_contains("file://")
5630 .stdout_contains("-rw") // we should have the long output
5631 // even if dired isn't actually run
5632 .stdout_does_not_contain("//DIRED//");
5633 // dired is passed after hyperlink
5634 // so we will have DIRED output
5635 scene
5636 .ucmd()
5637 .arg("--hyperlink")
5638 .arg("--dired")
5639 .arg("-R")
5640 .succeeds()
5641 .stdout_does_not_contain("file://")
5642 .stdout_contains("//DIRED//");
5643 }
5644
5645 #[test]
5646 fn test_ls_dired_order_format() {
5647 let scene = TestScenario::new(util_name!());
5648 let at = &scene.fixtures;
5649 at.mkdir("dir");
5650 at.touch("dir/a");
5651 scene
5652 .ucmd()
5653 .arg("--dired")
5654 .arg("--format=vertical")
5655 .arg("-R")
5656 .succeeds()
5657 .stdout_does_not_contain("//DIRED//");
5658 scene
5659 .ucmd()
5660 .arg("--format=vertical")
5661 .arg("--dired")
5662 .arg("-R")
5663 .succeeds()
5664 .stdout_contains("//DIRED//");
5665 }
5666
5667 #[test]
5668 fn test_ls_dired_and_zero_are_incompatible() {
5669 let scene = TestScenario::new(util_name!());
5670
5671 scene
5672 .ucmd()
5673 .arg("--dired")
5674 .arg("-l")
5675 .arg("--zero")
5676 .fails_with_code(2)
5677 .stderr_contains("--dired and --zero are incompatible");
5678 }
5679
5680 #[test]
5681 fn test_ls_dired_recursive() {
5682 let scene = TestScenario::new(util_name!());
5683
5684 scene
5685 .ucmd()
5686 .arg("--dired")
5687 .arg("-l")
5688 .arg("-R")
5689 .succeeds()
5690 .stdout_does_not_contain("//DIRED//")
5691 .stdout_contains(" total 0")
5692 .stdout_contains("//SUBDIRED// 2 3")
5693 .stdout_contains("//DIRED-OPTIONS// --quoting-style");
5694 }
5695
5696 #[test]
5697 fn test_ls_dired_subdired_multiple_dirs_non_recursive() {
5698 let scene = TestScenario::new(util_name!());
5699 let at = &scene.fixtures;
5700
5701 at.mkdir("dir1");
5702 at.mkdir("dir2");
5703 at.touch("dir1/a");
5704 at.touch("dir2/b");
5705
5706 let result = scene
5707 .ucmd()
5708 .arg("--dired")
5709 .arg("dir1")
5710 .arg("dir2")
5711 .succeeds();
5712
5713 let output = result.stdout_str().to_string();
5714 let subdired_line = output
5715 .lines()
5716 .find(|&line| line.starts_with("//SUBDIRED//"))
5717 .unwrap();
5718 let positions: Vec<usize> = subdired_line
5719 .split_whitespace()
5720 .skip(1)
5721 .map(|s| s.parse().unwrap())
5722 .collect();
5723
5724 assert_eq!(positions.len() % 2, 0); // Ensure there's an even number of positions
5725
5726 let dirnames: Vec<String> = positions
5727 .chunks(2)
5728 .map(|chunk| {
5729 let start_pos = chunk[0];
5730 let end_pos = chunk[1];
5731 String::from_utf8(output.as_bytes()[start_pos..end_pos].to_vec())
5732 .unwrap()
5733 .trim()
5734 .to_string()
5735 })
5736 .collect();
5737
5738 assert_eq!(dirnames, vec!["dir1", "dir2"]);
5739 }
5740
5741 #[test]
5742 fn test_ls_dired_outputs_parent_offset() {
5743 let scene = TestScenario::new(util_name!());
5744 let at = &scene.fixtures;
5745 at.mkdir("dir");
5746 at.mkdir("dir/a");
5747 scene
5748 .ucmd()
5749 .arg("--dired")
5750 .arg("dir")
5751 .arg("-R")
5752 .succeeds()
5753 .stdout_contains("//DIRED//");
5754 }
5755
5756 #[test]
5757 fn test_ls_dired_outputs_same_date_time_format() {
5758 let scene = TestScenario::new(util_name!());
5759 let at = &scene.fixtures;
5760 at.mkdir("dir");
5761 at.mkdir("dir/a");
5762 let binding = scene.ucmd().arg("-l").arg("dir").succeeds();
5763 let long_output_str = binding.stdout_str();
5764 let split_lines: Vec<&str> = long_output_str.split('\n').collect();
5765 // the second line should contain the long output which includes date
5766 let list_line = split_lines.get(1).unwrap();
5767 // should be same as the dired output
5768 scene
5769 .ucmd()
5770 .arg("--dired")
5771 .arg("dir")
5772 .arg("-R")
5773 .succeeds()
5774 .stdout_contains(list_line);
5775 }
5776
5777 #[test]
5778 fn test_ls_dired_recursive_multiple() {
5779 let scene = TestScenario::new(util_name!());
5780 let at = &scene.fixtures;
5781
5782 at.mkdir("d");
5783 at.mkdir("d/d1");
5784 at.mkdir("d/d2");
5785 at.touch("d/d2/a");
5786 at.touch("d/d2/c2");
5787 at.touch("d/d1/f1");
5788 at.touch("d/d1/file-long");
5789
5790 let mut cmd = scene.ucmd();
5791 cmd.arg("--dired").arg("-l").arg("-R").arg("d");
5792
5793 let result = cmd.succeeds();
5794
5795 let output = result.stdout_str().to_string();
5796 println!("Output:\n{output}");
5797
5798 let dired_line = output
5799 .lines()
5800 .find(|&line| line.starts_with("//DIRED//"))
5801 .unwrap();
5802 let positions: Vec<usize> = dired_line
5803 .split_whitespace()
5804 .skip(1)
5805 .map(|s| s.parse().unwrap())
5806 .collect();
5807 println!("Parsed byte positions: {positions:?}");
5808 assert_eq!(positions.len() % 2, 0); // Ensure there's an even number of positions
5809
5810 let filenames: Vec<String> = positions
5811 .chunks(2)
5812 .map(|chunk| {
5813 let start_pos = chunk[0];
5814 let end_pos = chunk[1];
5815 let filename = String::from_utf8(output.as_bytes()[start_pos..end_pos].to_vec())
5816 .unwrap()
5817 .trim()
5818 .to_string();
5819 println!("Extracted filename: {filename}");
5820 filename
5821 })
5822 .collect();
5823
5824 println!("Extracted filenames: {filenames:?}");
5825 assert_eq!(filenames, vec!["d1", "d2", "f1", "file-long", "a", "c2"]);
5826 }
5827
5828 #[test]
5829 fn test_ls_dired_simple() {
5830 let scene = TestScenario::new(util_name!());
5831 let at = &scene.fixtures;
5832 scene
5833 .ucmd()
5834 .arg("--dired")
5835 .arg("-l")
5836 .succeeds()
5837 .stdout_contains(" total 0");
5838
5839 at.mkdir("d");
5840 at.touch("d/a1");
5841 let mut cmd = scene.ucmd();
5842 cmd.arg("--dired").arg("-l").arg("d");
5843 let result = cmd.succeeds();
5844 result.stdout_contains(" total 0");
5845 println!(" result.stdout = {:#?}", result.stdout_str());
5846
5847 let dired_line = result
5848 .stdout_str()
5849 .lines()
5850 .find(|&line| line.starts_with("//DIRED//"))
5851 .unwrap();
5852 let positions: Vec<usize> = dired_line
5853 .split_whitespace()
5854 .skip(1)
5855 .map(|s| s.parse().unwrap())
5856 .collect();
5857
5858 assert_eq!(positions.len(), 2);
5859
5860 let start_pos = positions[0];
5861 let end_pos = positions[1];
5862
5863 // Extract the filename using the positions
5864 let filename =
5865 String::from_utf8(result.stdout_str().as_bytes()[start_pos..end_pos].to_vec()).unwrap();
5866
5867 assert_eq!(filename, "a1");
5868 }
5869
5870 #[test]
5871 fn test_ls_dired_symlink_name_only() {
5872 let scene = TestScenario::new(util_name!());
5873 let at = &scene.fixtures;
5874
5875 at.mkdir("d");
5876 at.touch("d/target");
5877 at.relative_symlink_file("target", "d/link");
5878
5879 let result = scene
5880 .ucmd()
5881 .arg("--dired")
5882 .arg("-l")
5883 .arg("--color=never")
5884 .arg("d")
5885 .succeeds();
5886
5887 let output = result.stdout_str().to_string();
5888 assert!(output.contains("link -> target"));
5889
5890 let dired_line = output
5891 .lines()
5892 .find(|&line| line.starts_with("//DIRED//"))
5893 .unwrap();
5894 let positions: Vec<usize> = dired_line
5895 .split_whitespace()
5896 .skip(1)
5897 .map(|s| s.parse().unwrap())
5898 .collect();
5899
5900 assert_eq!(positions.len() % 2, 0);
5901
5902 let filenames: Vec<String> = positions
5903 .chunks(2)
5904 .map(|chunk| {
5905 let start_pos = chunk[0];
5906 let end_pos = chunk[1];
5907 String::from_utf8(output.as_bytes()[start_pos..end_pos].to_vec())
5908 .unwrap()
5909 .trim()
5910 .to_string()
5911 })
5912 .collect();
5913
5914 assert_eq!(filenames, vec!["link", "target"]);
5915 }
5916
5917 /// Extracts the file names delimited by the //DIRED// byte offsets.
5918 fn dired_names(output: &str) -> Vec<String> {
5919 let dired_line = output
5920 .lines()
5921 .find(|&line| line.starts_with("//DIRED//"))
5922 .unwrap();
5923 let positions: Vec<usize> = dired_line
5924 .split_whitespace()
5925 .skip(1)
5926 .map(|s| s.parse().unwrap())
5927 .collect();
5928 assert_eq!(positions.len() % 2, 0);
5929 positions
5930 .chunks(2)
5931 .map(|chunk| String::from_utf8(output.as_bytes()[chunk[0]..chunk[1]].to_vec()).unwrap())
5932 .collect()
5933 }
5934
5935 #[test]
5936 fn test_ls_dired_name_boundaries() {
5937 let scene = TestScenario::new(util_name!());
5938 let at = &scene.fixtures;
5939
5940 at.mkdir("d");
5941 at.touch("d/target");
5942 at.relative_symlink_file("target", "d/link");
5943 at.mkdir("d/sub");
5944 at.touch("d/with space");
5945
5946 let quoted = ["link", "sub", "target", "'with space'"];
5947 let literal = ["link", "sub", "target", "with space"];
5948 // The quoting style is spelled out in every case: it decides both how the
5949 // names are rendered and whether they get padded, so leaving it to the
5950 // default would make the expectations depend on stdout being a terminal.
5951 let cases: [(&[&str], [&str; 4]); 4] = [
5952 // The color escapes wrapped around a name are not part of it,
5953 (&["--quoting-style=literal", "--color=always"], literal),
5954 // neither is the indicator character appended by -F,
5955 (&["--quoting-style=literal", "-F", "--color=never"], literal),
5956 (
5957 &["--quoting-style=literal", "-F", "--color=always"],
5958 literal,
5959 ),
5960 // nor the space padding unquoted names to align with quoted ones.
5961 (&["--quoting-style=shell-escape"], quoted),
5962 ];
5963
5964 for (args, expected) in cases {
5965 let result = scene
5966 .ucmd()
5967 .arg("--dired")
5968 .arg("-l")
5969 .args(args)
5970 .arg("d")
5971 .succeeds();
5972 assert_eq!(dired_names(result.stdout_str()), expected, "with {args:?}");
5973 }
5974 }
5975
5976 #[test]
5977 fn test_ls_dired_leading_info_offsets() {
5978 let scene = TestScenario::new(util_name!());
5979 let at = &scene.fixtures;
5980
5981 at.mkdir("bay");
5982 at.touch("bay/quill");
5983 at.touch("bay/parchment");
5984
5985 // -i and -s prepend an inode / block-size column to every long line; those
5986 // bytes shift the names and must be reflected in the //DIRED// offsets.
5987 for args in [&["-i"][..], &["-s"][..], &["-i", "-s"][..]] {
5988 let result = scene
5989 .ucmd()
5990 .arg("--dired")
5991 .arg("-l")
5992 .arg("--quoting-style=literal")
5993 .args(args)
5994 .arg("bay")
5995 .succeeds();
5996 assert_eq!(
5997 dired_names(result.stdout_str()),
5998 ["parchment", "quill"],
5999 "with {args:?}"
6000 );
6001 }
6002 }
6003
6004 #[test]
6005 fn test_ls_dired_normal_style_offsets() {
6006 let scene = TestScenario::new(util_name!());
6007 let at = &scene.fixtures;
6008
6009 at.mkdir("d");
6010 at.touch("d/note");
6011 at.mkdir("d/box");
6012
6013 // A `no` style makes ls emit a reset before the very first line; those
6014 // bytes count towards the //DIRED// offsets like any other output.
6015 let result = scene
6016 .ucmd()
6017 .env("LS_COLORS", "no=35:di=36")
6018 .arg("--dired")
6019 .arg("-l")
6020 .arg("--quoting-style=literal")
6021 .arg("--color=always")
6022 .arg("d")
6023 .succeeds();
6024
6025 assert!(result.stdout_str().starts_with("\x1b["));
6026 assert_eq!(dired_names(result.stdout_str()), ["box", "note"]);
6027 }
6028
6029 #[test]
6030 fn test_ls_dired_complex() {
6031 let scene = TestScenario::new(util_name!());
6032 let at = &scene.fixtures;
6033
6034 at.mkdir("d");
6035 at.mkdir("d/d");
6036 at.touch("d/a1");
6037 at.touch("d/a22");
6038 at.touch("d/a333");
6039 at.touch("d/a4444");
6040
6041 let mut cmd = scene.ucmd();
6042 cmd.arg("--dired").arg("-l").arg("d");
6043 let result = cmd.succeeds();
6044
6045 // Number of blocks. We run this test only if the default size of a newly created directory is
6046 // 4096 bytes to prevent it from failing where this is not the case (e.g. using tmpfs for /tmp).
6047 #[cfg(target_os = "linux")]
6048 if at.metadata("d/d").len() == 4096 {
6049 result.stdout_contains(" total 4");
6050 }
6051
6052 let output = result.stdout_str().to_string();
6053 println!("Output:\n{output}");
6054
6055 let dired_line = output
6056 .lines()
6057 .find(|&line| line.starts_with("//DIRED//"))
6058 .unwrap();
6059 let positions: Vec<usize> = dired_line
6060 .split_whitespace()
6061 .skip(1)
6062 .map(|s| s.parse().unwrap())
6063 .collect();
6064 println!("{positions:?}");
6065 println!("Parsed byte positions: {positions:?}");
6066 assert_eq!(positions.len() % 2, 0); // Ensure there's an even number of positions
6067
6068 let filenames: Vec<String> = positions
6069 .chunks(2)
6070 .map(|chunk| {
6071 let start_pos = chunk[0];
6072 let end_pos = chunk[1];
6073 let filename = String::from_utf8(output.as_bytes()[start_pos..end_pos].to_vec())
6074 .unwrap()
6075 .trim()
6076 .to_string();
6077 println!("Extracted filename: {filename}");
6078 filename
6079 })
6080 .collect();
6081
6082 println!("Extracted filenames: {filenames:?}");
6083 assert_eq!(filenames, vec!["a1", "a22", "a333", "a4444", "d"]);
6084 }
6085
6086 #[test]
6087 fn test_ls_subdired_complex() {
6088 let scene = TestScenario::new(util_name!());
6089 let at = &scene.fixtures;
6090
6091 at.mkdir("dir1");
6092 at.mkdir("dir1/d");
6093 at.mkdir("dir1/c2");
6094 at.touch("dir1/a1");
6095 at.touch("dir1/a22");
6096 at.touch("dir1/a333");
6097 at.touch("dir1/c2/a4444");
6098
6099 let mut cmd = scene.ucmd();
6100 cmd.arg("--dired").arg("-l").arg("-R").arg("dir1");
6101 let result = cmd.succeeds();
6102
6103 let output = result.stdout_str().to_string();
6104 println!("Output:\n{output}");
6105
6106 let dired_line = output
6107 .lines()
6108 .find(|&line| line.starts_with("//SUBDIRED//"))
6109 .unwrap();
6110 let positions: Vec<usize> = dired_line
6111 .split_whitespace()
6112 .skip(1)
6113 .map(|s| s.parse().unwrap())
6114 .collect();
6115 println!("Parsed byte positions: {positions:?}");
6116 assert_eq!(positions.len() % 2, 0); // Ensure there's an even number of positions
6117
6118 let dirnames: Vec<String> = positions
6119 .chunks(2)
6120 .map(|chunk| {
6121 let start_pos = chunk[0];
6122 let end_pos = chunk[1];
6123 let dirname =
6124 String::from_utf8(output.as_bytes()[start_pos..end_pos].to_vec()).unwrap();
6125 println!("Extracted dirname: {dirname}");
6126 dirname
6127 })
6128 .collect();
6129
6130 println!("Extracted dirnames: {dirnames:?}");
6131 #[cfg(unix)]
6132 assert_eq!(dirnames, vec!["dir1", "dir1/c2", "dir1/d"]);
6133 #[cfg(windows)]
6134 assert_eq!(dirnames, vec!["dir1", "dir1\\c2", "dir1\\d"]);
6135 }
6136
6137 #[test]
6138 fn test_ls_cf_output_should_be_delimited_by_tab() {
6139 let (at, mut ucmd) = at_and_ucmd!();
6140
6141 at.mkdir("e");
6142 at.mkdir("e/a2345");
6143 at.mkdir("e/b");
6144
6145 ucmd.args(&["-CF", "e"])
6146 .succeeds()
6147 .stdout_is("a2345/\tb/\n");
6148 }
6149
6150 #[cfg(all(unix, feature = "dd"))]
6151 #[test]
6152 #[cfg(not(target_os = "openbsd"))]
6153 fn test_posixly_correct_and_block_size_env_vars() {
6154 let scene = TestScenario::new(util_name!());
6155
6156 scene
6157 .ccmd("dd")
6158 .arg("if=/dev/zero")
6159 .arg("of=file")
6160 .arg("bs=1024")
6161 .arg("count=1")
6162 .succeeds();
6163
6164 scene
6165 .ucmd()
6166 .arg("-l")
6167 .succeeds()
6168 .stdout_contains_line("total 4")
6169 .stdout_contains(" 1024 ");
6170
6171 scene
6172 .ucmd()
6173 .arg("-l")
6174 .env("POSIXLY_CORRECT", "some_value")
6175 .succeeds()
6176 .stdout_contains_line("total 8")
6177 .stdout_contains(" 1024 ");
6178
6179 scene
6180 .ucmd()
6181 .arg("-l")
6182 .env("LS_BLOCK_SIZE", "512")
6183 .succeeds()
6184 .stdout_contains_line("total 8")
6185 .stdout_contains(" 2 ");
6186
6187 scene
6188 .ucmd()
6189 .arg("-l")
6190 .env("BLOCK_SIZE", "512")
6191 .succeeds()
6192 .stdout_contains_line("total 8")
6193 .stdout_contains(" 2 ");
6194
6195 scene
6196 .ucmd()
6197 .arg("-l")
6198 .env("BLOCKSIZE", "512")
6199 .succeeds()
6200 .stdout_contains_line("total 8")
6201 .stdout_contains(" 1024 ");
6202 }
6203
6204 #[cfg(all(unix, feature = "dd"))]
6205 #[test]
6206 #[cfg(not(target_os = "openbsd"))]
6207 fn test_posixly_correct_and_block_size_env_vars_with_k() {
6208 let scene = TestScenario::new(util_name!());
6209
6210 scene
6211 .ccmd("dd")
6212 .arg("if=/dev/zero")
6213 .arg("of=file")
6214 .arg("bs=1024")
6215 .arg("count=1")
6216 .succeeds();
6217
6218 scene
6219 .ucmd()
6220 .arg("-l")
6221 .arg("-k")
6222 .env("POSIXLY_CORRECT", "some_value")
6223 .succeeds()
6224 .stdout_contains_line("total 4")
6225 .stdout_contains(" 1024 ");
6226
6227 scene
6228 .ucmd()
6229 .arg("-l")
6230 .arg("-k")
6231 .env("LS_BLOCK_SIZE", "512")
6232 .succeeds()
6233 .stdout_contains_line("total 4")
6234 .stdout_contains(" 2 ");
6235
6236 scene
6237 .ucmd()
6238 .arg("-l")
6239 .arg("-k")
6240 .env("BLOCK_SIZE", "512")
6241 .succeeds()
6242 .stdout_contains_line("total 4")
6243 .stdout_contains(" 2 ");
6244
6245 scene
6246 .ucmd()
6247 .arg("-l")
6248 .arg("-k")
6249 .env("BLOCKSIZE", "512")
6250 .succeeds()
6251 .stdout_contains_line("total 4")
6252 .stdout_contains(" 1024 ");
6253 }
6254
6255 #[test]
6256 fn test_ls_invalid_block_size() {
6257 new_ucmd!()
6258 .arg("--block-size=invalid")
6259 .fails_with_code(2)
6260 .no_stdout()
6261 .stderr_is("ls: invalid --block-size argument 'invalid'\n");
6262
6263 new_ucmd!()
6264 .arg("--block-size=0")
6265 .fails_with_code(2)
6266 .no_stdout()
6267 .stderr_is("ls: invalid --block-size argument '0'\n");
6268 }
6269
6270 #[cfg(all(unix, feature = "dd"))]
6271 #[test]
6272 #[cfg(not(target_os = "openbsd"))]
6273 fn test_ls_invalid_block_size_in_env_var() {
6274 let scene = TestScenario::new(util_name!());
6275
6276 scene
6277 .ccmd("dd")
6278 .arg("if=/dev/zero")
6279 .arg("of=file")
6280 .arg("bs=1024")
6281 .arg("count=1")
6282 .succeeds();
6283
6284 scene
6285 .ucmd()
6286 .arg("-og")
6287 .env("LS_BLOCK_SIZE", "invalid")
6288 .succeeds()
6289 .stdout_contains_line("total 4")
6290 .stdout_contains(" 1 1 "); // hardlink count + file size
6291
6292 scene
6293 .ucmd()
6294 .arg("-og")
6295 .env("BLOCK_SIZE", "invalid")
6296 .succeeds()
6297 .stdout_contains_line("total 4")
6298 .stdout_contains(" 1 1 "); // hardlink count + file size
6299
6300 scene
6301 .ucmd()
6302 .arg("-og")
6303 .env("BLOCKSIZE", "invalid")
6304 .succeeds()
6305 .stdout_contains_line("total 4")
6306 .stdout_contains(" 1024 ");
6307
6308 scene
6309 .ucmd()
6310 .arg("-og")
6311 .env("BLOCKSIZE", "0")
6312 .succeeds()
6313 .stdout_contains_line("total 4")
6314 .stdout_contains(" 1024 ");
6315 }
6316
6317 #[cfg(all(unix, feature = "dd"))]
6318 #[test]
6319 #[cfg(not(target_os = "openbsd"))]
6320 fn test_ls_block_size_override() {
6321 let scene = TestScenario::new(util_name!());
6322
6323 scene
6324 .ccmd("dd")
6325 .arg("if=/dev/zero")
6326 .arg("of=file")
6327 .arg("bs=1024")
6328 .arg("count=1")
6329 .succeeds();
6330
6331 // --si "wins"
6332 scene
6333 .ucmd()
6334 .arg("-s")
6335 .arg("--block-size=512")
6336 .arg("--si")
6337 .succeeds()
6338 .stdout_contains_line("total 4.1k");
6339
6340 // --block-size "wins"
6341 scene
6342 .ucmd()
6343 .arg("-s")
6344 .arg("--si")
6345 .arg("--block-size=512")
6346 .succeeds()
6347 .stdout_contains_line("total 8");
6348
6349 // --human-readable "wins"
6350 scene
6351 .ucmd()
6352 .arg("-s")
6353 .arg("--block-size=512")
6354 .arg("--human-readable")
6355 .succeeds()
6356 .stdout_contains_line("total 4.0K");
6357
6358 // --block-size "wins"
6359 scene
6360 .ucmd()
6361 .arg("-s")
6362 .arg("--human-readable")
6363 .arg("--block-size=512")
6364 .succeeds()
6365 .stdout_contains_line("total 8");
6366 }
6367
6368 #[cfg(unix)]
6369 #[test]
6370 #[cfg(not(target_os = "openbsd"))]
6371 fn test_ls_block_size_si_file_size() {
6372 // Verify --si and --block-size interaction for file size display in -l
6373 let scene = TestScenario::new(util_name!());
6374 let at = &scene.fixtures;
6375
6376 at.write_bytes("file", &[0u8; 1024]);
6377
6378 // --si last: file size shown as human-readable SI
6379 scene
6380 .ucmd()
6381 .arg("-l")
6382 .arg("--block-size=512")
6383 .arg("--si")
6384 .succeeds()
6385 .stdout_contains("1.1k");
6386
6387 // --block-size last: file size shown in 512-byte blocks
6388 scene
6389 .ucmd()
6390 .arg("-l")
6391 .arg("--si")
6392 .arg("--block-size=512")
6393 .succeeds()
6394 .stdout_contains(" 2 ");
6395
6396 // --human-readable last: file size shown as human-readable IEC
6397 scene
6398 .ucmd()
6399 .arg("-l")
6400 .arg("--block-size=512")
6401 .arg("--human-readable")
6402 .succeeds()
6403 .stdout_contains("1.0K");
6404
6405 // --block-size last: file size shown in 512-byte blocks
6406 scene
6407 .ucmd()
6408 .arg("-l")
6409 .arg("--human-readable")
6410 .arg("--block-size=512")
6411 .succeeds()
6412 .stdout_contains(" 2 ");
6413 }
6414
6415 #[test]
6416 fn test_ls_block_size_override_self() {
6417 new_ucmd!()
6418 .arg("--block-size=512")
6419 .arg("--block-size=512")
6420 .succeeds();
6421
6422 new_ucmd!()
6423 .arg("--human-readable")
6424 .arg("--human-readable")
6425 .succeeds();
6426
6427 new_ucmd!().arg("--si").arg("--si").succeeds();
6428 }
6429
6430 #[test]
6431 fn test_ls_hyperlink() {
6432 let scene = TestScenario::new(util_name!());
6433 let at = &scene.fixtures;
6434 let file = "a.txt";
6435
6436 at.touch(file);
6437
6438 let path = at.root_dir_resolved();
6439 let separator = std::path::MAIN_SEPARATOR_STR;
6440
6441 let result = scene.ucmd().arg("--hyperlink").succeeds();
6442 assert!(result.stdout_str().contains("\x1b]8;;file://"));
6443 assert!(result.stdout_str().contains(&format!(
6444 "{path}{separator}{file}\x1b\\{file}\x1b]8;;\x1b\\"
6445 )));
6446
6447 let result = scene.ucmd().arg("--hyperlink=always").succeeds();
6448 assert!(result.stdout_str().contains("\x1b]8;;file://"));
6449 assert!(result.stdout_str().contains(&format!(
6450 "{path}{separator}{file}\x1b\\{file}\x1b]8;;\x1b\\"
6451 )));
6452
6453 for argument in [
6454 "--hyperlink=never",
6455 "--hyperlink=neve", // spell-checker:disable-line
6456 "--hyperlink=ne",
6457 "--hyperlink=n",
6458 ] {
6459 scene
6460 .ucmd()
6461 .arg(argument)
6462 .succeeds()
6463 .stdout_is(format!("{file}\n"));
6464 }
6465 }
6466
6467 // spell-checker: disable
6468 #[test]
6469 fn test_ls_hyperlink_encode_link() {
6470 let (at, mut ucmd) = at_and_ucmd!();
6471
6472 #[cfg(not(windows))]
6473 {
6474 at.touch("back\\slash");
6475 at.touch("ques?tion");
6476 }
6477 at.touch("encoded%3Fquestion");
6478 at.touch("sp ace");
6479
6480 let result = ucmd.arg("--hyperlink").succeeds();
6481 #[cfg(not(windows))]
6482 {
6483 assert!(
6484 result
6485 .stdout_str()
6486 .contains("back%5cslash\x1b\\back\\slash\x1b]8;;\x1b\\")
6487 );
6488 assert!(
6489 result
6490 .stdout_str()
6491 .contains("ques%3ftion\x1b\\ques?tion\x1b]8;;\x1b\\")
6492 );
6493 }
6494 assert!(
6495 result
6496 .stdout_str()
6497 .contains("encoded%253Fquestion\x1b\\encoded%3Fquestion\x1b]8;;\x1b\\")
6498 );
6499 assert!(
6500 result
6501 .stdout_str()
6502 .contains("sp%20ace\x1b\\sp ace\x1b]8;;\x1b\\")
6503 );
6504 }
6505 // spell-checker: enable
6506
6507 #[test]
6508 fn test_ls_hyperlink_dirs() {
6509 let scene = TestScenario::new(util_name!());
6510 let at = &scene.fixtures;
6511 let dir_a = "a";
6512 let dir_b = "b";
6513
6514 at.mkdir(dir_a);
6515 at.mkdir(dir_b);
6516
6517 let path = at.root_dir_resolved();
6518 let separator = std::path::MAIN_SEPARATOR_STR;
6519
6520 let result = scene
6521 .ucmd()
6522 .arg("--hyperlink")
6523 .arg(dir_a)
6524 .arg(dir_b)
6525 .succeeds();
6526
6527 assert!(result.stdout_str().contains("\x1b]8;;file://"));
6528 assert!(
6529 result
6530 .stdout_str()
6531 .lines()
6532 .next()
6533 .unwrap()
6534 .contains(&format!(
6535 "{path}{separator}{dir_a}\x1b\\{dir_a}\x1b]8;;\x1b\\:"
6536 ))
6537 );
6538 assert_eq!(result.stdout_str().lines().nth(1).unwrap(), "");
6539 assert!(
6540 result
6541 .stdout_str()
6542 .lines()
6543 .nth(2)
6544 .unwrap()
6545 .contains(&format!(
6546 "{path}{separator}{dir_b}\x1b\\{dir_b}\x1b]8;;\x1b\\:"
6547 ))
6548 );
6549 }
6550
6551 #[test]
6552 fn test_ls_hyperlink_recursive_dirs() {
6553 let scene = TestScenario::new(util_name!());
6554 let at = &scene.fixtures;
6555 let path = at.root_dir_resolved();
6556 let separator = std::path::MAIN_SEPARATOR_STR;
6557
6558 let dir_a = "a";
6559 let dir_b = "b";
6560 at.mkdir(dir_a);
6561 at.mkdir(format!("{dir_a}/{dir_b}"));
6562
6563 let result = scene
6564 .ucmd()
6565 .arg("--hyperlink")
6566 .arg("--recursive")
6567 .arg(dir_a)
6568 .succeeds();
6569
6570 macro_rules! assert_hyperlink {
6571 ($line:expr, $expected:expr) => {
6572 assert!(matches!($line, Some(l) if l.starts_with("\x1b]8;;file://") && l.ends_with($expected)));
6573 };
6574 }
6575
6576 let mut lines = result.stdout_str().lines();
6577 assert_hyperlink!(
6578 lines.next(),
6579 &format!("{path}{separator}{dir_a}\x1b\\{dir_a}\x1b]8;;\x1b\\:")
6580 );
6581 assert_hyperlink!(
6582 lines.next(),
6583 &format!("{path}{separator}{dir_a}{separator}{dir_b}\x1b\\{dir_b}\x1b]8;;\x1b\\")
6584 );
6585 assert!(matches!(lines.next(), Some(l) if l.is_empty()));
6586 assert_hyperlink!(
6587 lines.next(),
6588 &format!(
6589 "{path}{separator}{dir_a}{separator}{dir_b}\x1b\\{dir_a}{separator}{dir_b}\x1b]8;;\x1b\\:"
6590 )
6591 );
6592 }
6593
6594 #[test]
6595 fn test_ls_hyperlink_symlink_target_handling() {
6596 let scene = TestScenario::new(util_name!());
6597 let at = &scene.fixtures;
6598
6599 at.mkdir("target_dir");
6600 at.touch("target_file.txt");
6601 at.symlink_file("target_file.txt", "link_to_file");
6602 at.symlink_dir("target_dir", "link_to_dir");
6603 at.symlink_file("nonexistent", "link_to_missing");
6604
6605 let result = scene
6606 .ucmd()
6607 .args(&["-l", "--hyperlink", "--color", "--file-type"])
6608 .succeeds();
6609 let output = result.stdout_str();
6610
6611 assert!(output.contains("\x1b]8;;file://"));
6612 assert!(!output.contains('\x07'));
6613 assert!(output.contains("\x1b\\"));
6614
6615 let file_link_line = output
6616 .lines()
6617 .find(|line| line.contains("link_to_file"))
6618 .unwrap();
6619 assert!(file_link_line.contains(" -> "));
6620 let target_part = file_link_line.split(" -> ").nth(1).unwrap();
6621 assert!(!target_part.contains("\x1b["));
6622 assert!(!target_part.ends_with("\x1b[K"));
6623
6624 let dir_link_line = output
6625 .lines()
6626 .find(|line| line.contains("link_to_dir"))
6627 .unwrap();
6628 assert!(dir_link_line.contains(" -> "));
6629 let target_part = dir_link_line.split(" -> ").nth(1).unwrap();
6630 assert!(target_part.contains("\x1b["));
6631
6632 let missing_link_line = output
6633 .lines()
6634 .find(|line| line.contains("link_to_missing"))
6635 .unwrap();
6636 assert!(missing_link_line.contains(" -> "));
6637 let missing_target_part = missing_link_line.split(" -> ").nth(1).unwrap();
6638 assert!(missing_target_part.contains("\x1b["));
6639 }
6640
6641 #[test]
6642 fn test_ls_hyperlink_utf8_encoding() {
6643 let scene = TestScenario::new(util_name!());
6644 let at = &scene.fixtures;
6645
6646 at.touch("café.txt");
6647 #[cfg(not(windows))]
6648 at.touch("file:with:colons.txt");
6649 #[cfg(windows)]
6650 at.touch("file-with-colons.txt");
6651 at.touch("file with spaces.txt");
6652
6653 let result = scene.ucmd().args(&["--hyperlink"]).succeeds();
6654 let output = result.stdout_str();
6655
6656 assert!(output.contains("caf%c3%a9.txt"));
6657 #[cfg(not(windows))]
6658 assert!(output.contains("file%3awith%3acolons.txt"));
6659 #[cfg(windows)]
6660 assert!(output.contains("file-with-colons.txt"));
6661 assert!(output.contains("file%20with%20spaces.txt"));
6662
6663 let hyperlink_count = output.matches("\x1b]8;;file://").count();
6664 let terminator_count = output.matches("\x1b\\").count();
6665 assert_eq!(terminator_count, hyperlink_count * 2);
6666 }
6667
6668 #[test]
6669 fn test_ls_color_do_not_reset() {
6670 let scene: TestScenario = TestScenario::new(util_name!());
6671 let at = &scene.fixtures;
6672 at.mkdir("example");
6673 at.mkdir("example/a");
6674 at.mkdir("example/b");
6675
6676 let result = scene
6677 .ucmd()
6678 .arg("--color=always")
6679 .arg("example/")
6680 .succeeds();
6681 // the second color code should not have a reset
6682 assert_eq!(
6683 result.stdout_str().escape_default().to_string(),
6684 "\\u{1b}[0m\\u{1b}[01;34ma\\u{1b}[0m\\n\\u{1b}[01;34mb\\u{1b}[0m\\n"
6685 );
6686 }
6687
6688 #[cfg(all(unix, feature = "chmod"))]
6689 #[test]
6690 fn test_term_colorterm() {
6691 let scene = TestScenario::new(util_name!());
6692 let at = &scene.fixtures;
6693 at.touch("exe");
6694 scene.ccmd("chmod").arg("+x").arg("exe").succeeds();
6695
6696 // Should show colors
6697 let result = scene
6698 .ucmd()
6699 .arg("--color=always")
6700 .env("LS_COLORS", "")
6701 .env("TERM", "")
6702 .succeeds();
6703 assert_eq!(
6704 result.stdout_str().trim().escape_default().to_string(),
6705 "\\u{1b}[0m\\u{1b}[01;32mexe\\u{1b}[0m"
6706 );
6707
6708 // Should show colors
6709 let result = scene
6710 .ucmd()
6711 .arg("--color=always")
6712 .env("LS_COLORS", "")
6713 .env("COLORTERM", "")
6714 .succeeds();
6715 assert_eq!(
6716 result.stdout_str().trim().escape_default().to_string(),
6717 "\\u{1b}[0m\\u{1b}[01;32mexe\\u{1b}[0m"
6718 );
6719
6720 // No colors
6721 let result = scene
6722 .ucmd()
6723 .arg("--color=always")
6724 .env("LS_COLORS", "")
6725 .env("TERM", "")
6726 .env("COLORTERM", "")
6727 .succeeds();
6728 assert_eq!(
6729 result.stdout_str().trim().escape_default().to_string(),
6730 "exe"
6731 );
6732
6733 // No colors
6734 let result = scene
6735 .ucmd()
6736 .arg("--color=always")
6737 .env("LS_COLORS", "")
6738 .env("TERM", "dumb")
6739 .env("COLORTERM", "")
6740 .succeeds();
6741 assert_eq!(
6742 result.stdout_str().trim().escape_default().to_string(),
6743 "exe"
6744 );
6745 }
6746
6747 #[cfg(all(unix, not(target_vendor = "apple")))]
6748 #[test]
6749 fn test_acl_display() {
6750 use std::process::Command;
6751
6752 let scene = TestScenario::new(util_name!());
6753 let at = &scene.fixtures;
6754
6755 at.mkdir("with_acl");
6756 let path_with_acl = at.plus_as_string("with_acl");
6757 at.mkdir("without_acl");
6758
6759 // calling the command directly. xattr requires some dev packages to be installed
6760 // and it adds a complex dependency just for a test
6761 match Command::new("setfacl")
6762 .args(["-d", "-m", "group::rwx", &path_with_acl])
6763 .status()
6764 .map(|status| status.code())
6765 {
6766 Ok(Some(0)) => {}
6767 Ok(_) => {
6768 println!("test skipped: setfacl failed");
6769 return;
6770 }
6771 Err(e) => {
6772 println!("test skipped: setfacl failed with {e}");
6773 return;
6774 }
6775 }
6776
6777 // Expected output (we just look for `+` presence and absence in the first column):
6778 // ...
6779 // drwxr-xr-x+ 2 user group 40 Apr 21 12:44 with_acl
6780 // drwxr-xr-x 2 user group 40 Apr 21 12:44 without_acl
6781 let re_with_acl = Regex::new(r"[a-z-]*\+ .*with_acl").unwrap();
6782 let re_without_acl = Regex::new(r"[a-z-]* .*without_acl").unwrap();
6783
6784 scene
6785 .ucmd()
6786 .args(&["-la", &at.as_string()])
6787 .succeeds()
6788 .stdout_matches(&re_with_acl)
6789 .stdout_matches(&re_without_acl);
6790
6791 // Verify that it also works if the current dir is different from the ucmd temporary dir
6792 scene
6793 .ucmd()
6794 .current_dir("/")
6795 .args(&["-la", &at.as_string()])
6796 .succeeds()
6797 .stdout_matches(&re_with_acl)
6798 .stdout_matches(&re_without_acl);
6799 }
6800
6801 // Regression test for https://github.com/uutils/coreutils/issues/10980
6802 // Each file with an ACL must not inflate the link-count column width.
6803 #[cfg(all(unix, not(target_vendor = "apple")))]
6804 #[test]
6805 fn test_acl_padding_not_inflated() {
6806 use std::process::Command;
6807
6808 let scene = TestScenario::new(util_name!());
6809 let at = &scene.fixtures;
6810
6811 let uid = rustix::process::getuid().as_raw();
6812 let names = ["file1", "file2", "file3", "file4", "file5"];
6813 for name in &names {
6814 at.touch(name);
6815 let status = Command::new("setfacl")
6816 .args(["-m", &format!("u:{uid}:rw"), &at.plus_as_string(name)])
6817 .status()
6818 .map(|s| s.code());
6819 if !matches!(status, Ok(Some(0))) {
6820 println!("test skipped: setfacl failed");
6821 return;
6822 }
6823 }
6824
6825 let out = scene
6826 .ucmd()
6827 .current_dir(at.as_string())
6828 .arg("-l")
6829 .succeeds()
6830 .stdout_move_str();
6831
6832 // Each line with an ACL file should look like:
6833 // -rw-------+ 1 user group 0 <date> fileN
6834 // i.e. single space between the `+` and the link count `1`.
6835 // The bug inflates that gap to one extra space per ACL file.
6836 let mut checked = 0;
6837 for line in out.lines() {
6838 if line.starts_with('-') && line.contains('+') {
6839 let after_plus = line.split('+').nth(1).unwrap();
6840 let leading_spaces = after_plus.len() - after_plus.trim_start().len();
6841 assert_eq!(
6842 leading_spaces, 1,
6843 "expected exactly 1 space between '+' and link count, got {leading_spaces} in line: {line:?}"
6844 );
6845 checked += 1;
6846 }
6847 }
6848 assert!(checked > 0, "no ACL lines were validated");
6849 }
6850
6851 // Make sure that "ls --color" correctly applies color "normal" to text and
6852 // files. Specifically, it should use the NORMAL setting to format non-file name
6853 // output and file names that don't have a designated color (unless the FILE
6854 // setting is also configured).
6855 #[cfg(unix)]
6856 #[test]
6857 #[cfg(not(feature = "selinux"))]
6858 // Disabled on the SELinux runner for now
6859 fn test_ls_color_norm() {
6860 let scene = TestScenario::new(util_name!());
6861 let at = &scene.fixtures;
6862 at.touch("exe");
6863 at.set_mode("exe", 0o755);
6864 at.touch("no_color");
6865 at.set_mode("no_color", 0o444);
6866 let colors = "no=7:ex=01;32";
6867 let strip = |input: &str| {
6868 let re = Regex::new(r"-r.*norm").unwrap();
6869 re.replace_all(input, "norm").to_string()
6870 };
6871
6872 // Uncolored file names should inherit NORMAL attributes.
6873 let expected = "\x1b[0m\x1b[07mnorm \x1b[0m\x1b[01;32mexe\x1b[0m\n\x1b[07mnorm no_color\x1b[0m"; // spell-checker:disable-line
6874 scene
6875 .ucmd()
6876 .env("LS_COLORS", colors)
6877 .env("TIME_STYLE", "+norm")
6878 .arg("-gGU")
6879 .arg("--color")
6880 .arg("exe")
6881 .arg("no_color")
6882 .succeeds()
6883 .stdout_str_apply(strip)
6884 .stdout_contains(expected);
6885
6886 let expected = "\x1b[0m\x1b[07m\x1b[0m\x1b[01;32mexe\x1b[0m \x1b[07mno_color\x1b[0m\n"; // spell-checker:disable-line
6887 scene
6888 .ucmd()
6889 .env("LS_COLORS", colors)
6890 .env("TIME_STYLE", "+norm")
6891 .arg("-xU")
6892 .arg("--color")
6893 .arg("exe")
6894 .arg("no_color")
6895 .succeeds()
6896 .stdout_contains(expected);
6897
6898 let expected =
6899 "\x1b[0m\x1b[07mnorm no_color\x1b[0m\n\x1b[07mnorm \x1b[0m\x1b[01;32mexe\x1b[0m\n"; // spell-checker:disable-line
6900
6901 scene
6902 .ucmd()
6903 .env("LS_COLORS", colors)
6904 .env("TIME_STYLE", "+norm")
6905 .arg("-gGU")
6906 .arg("--color")
6907 .arg("no_color")
6908 .arg("exe")
6909 .succeeds()
6910 .stdout_str_apply(strip)
6911 .stdout_contains(expected);
6912
6913 let expected = "\x1b[0m\x1b[07mno_color\x1b[0m \x1b[07m\x1b[0m\x1b[01;32mexe\x1b[0m"; // spell-checker:disable-line
6914 scene
6915 .ucmd()
6916 .env("LS_COLORS", colors)
6917 .env("TIME_STYLE", "+norm")
6918 .arg("-xU")
6919 .arg("--color")
6920 .arg("no_color")
6921 .arg("exe")
6922 .succeeds()
6923 .stdout_contains(expected);
6924
6925 // NORMAL does not override FILE
6926 let expected = "\x1b[0m\x1b[07mnorm \x1b[0m\x1b[01mno_color\x1b[0m\n\x1b[07mnorm \x1b[0m\x1b[01;32mexe\x1b[0m\n"; // spell-checker:disable-line
6927 scene
6928 .ucmd()
6929 .env("LS_COLORS", format!("{colors}:fi=1"))
6930 .env("TIME_STYLE", "+norm")
6931 .arg("-gGU")
6932 .arg("--color")
6933 .arg("no_color")
6934 .arg("exe")
6935 .succeeds()
6936 .stdout_str_apply(strip)
6937 .stdout_contains(expected);
6938
6939 // uncolored ordinary files that do _not_ inherit from NORMAL.
6940 let expected =
6941 "\x1b[0m\x1b[07mnorm \x1b[0mno_color\x1b[0m\n\x1b[07mnorm \x1b[0m\x1b[01;32mexe\x1b[0m\n"; // spell-checker:disable-line
6942 scene
6943 .ucmd()
6944 .env("LS_COLORS", format!("{colors}:fi="))
6945 .env("TIME_STYLE", "+norm")
6946 .arg("-gGU")
6947 .arg("--color")
6948 .arg("no_color")
6949 .arg("exe")
6950 .succeeds()
6951 .stdout_str_apply(strip)
6952 .stdout_contains(expected);
6953
6954 let expected =
6955 "\x1b[0m\x1b[07mnorm \x1b[0mno_color\x1b[0m\n\x1b[07mnorm \x1b[0m\x1b[01;32mexe\x1b[0m\n"; // spell-checker:disable-line
6956 scene
6957 .ucmd()
6958 .env("LS_COLORS", format!("{colors}:fi=0"))
6959 .env("TIME_STYLE", "+norm")
6960 .arg("-gGU")
6961 .arg("--color")
6962 .arg("no_color")
6963 .arg("exe")
6964 .succeeds()
6965 .stdout_str_apply(strip)
6966 .stdout_contains(expected);
6967
6968 // commas (-m), indicator chars (-F) and the "total" line, do not currently
6969 // use NORMAL attributes
6970 let expected = "\x1b[0m\x1b[07mno_color\x1b[0m, \x1b[07m\x1b[0m\x1b[01;32mexe\x1b[0m\n"; // spell-checker:disable-line
6971 scene
6972 .ucmd()
6973 .env("LS_COLORS", colors)
6974 .env("TIME_STYLE", "+norm")
6975 .arg("-mU")
6976 .arg("--color")
6977 .arg("no_color")
6978 .arg("exe")
6979 .succeeds()
6980 .stdout_contains(expected);
6981 }
6982
6983 // A style that renders to an empty ANSI sequence, such as the default
6984 // foreground color, used to make `ls --color` panic while stripping the
6985 // trailing reset from the style code.
6986 #[test]
6987 fn test_ls_color_empty_style() {
6988 let scene = TestScenario::new(util_name!());
6989 let at = &scene.fixtures;
6990 at.touch("f");
6991
6992 scene
6993 .ucmd()
6994 .env("LS_COLORS", "no=39")
6995 .arg("--color=always")
6996 .arg("f")
6997 .succeeds()
6998 .stdout_only("\u{1b}[0mf\u{1b}[0m\n");
6999 }
7000
7001 #[test]
7002 fn test_ls_color_clear_to_eol() {
7003 let scene = TestScenario::new(util_name!());
7004 let at = &scene.fixtures;
7005 // we create file with a long name
7006 at.touch("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.foo");
7007 let result = scene
7008 .ucmd()
7009 .env("TERM", "xterm")
7010 // set the columns to something small so that the text would wrap around
7011 .env("COLUMNS", "80")
7012 // set the background to green and text to red
7013 .env("LS_COLORS", "*.foo=0;31;42")
7014 .env("TIME_STYLE", "+T")
7015 .arg("-og")
7016 .arg("--color")
7017 .arg("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.foo")
7018 .succeeds();
7019 // check that the wrapped name contains clear to end of line code
7020 // cspell:disable-next-line
7021 result.stdout_contains("\x1b[0m\x1b[31;42mzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.foo\x1b[0m\x1b[K");
7022 }
7023
7024 #[test]
7025 fn test_suffix_case_sensitivity() {
7026 let scene = TestScenario::new(util_name!());
7027 let at = &scene.fixtures;
7028 at.touch("img1.jpg");
7029 at.touch("IMG2.JPG");
7030 at.touch("img3.JpG");
7031 at.touch("file1.z");
7032 at.touch("file2.Z");
7033
7034 // *.jpg is specified only once so any suffix that has .jpg should match
7035 // without caring about the letter case
7036 let result = scene
7037 .ucmd()
7038 .env("LS_COLORS", "*.jpg=01;35:*.Z=01;31")
7039 .arg("-U1")
7040 .arg("--color=always")
7041 .arg("img1.jpg")
7042 .arg("IMG2.JPG")
7043 .arg("file1.z")
7044 .arg("file2.Z")
7045 .succeeds();
7046 result.stdout_contains(
7047 /* cSpell:disable */
7048 "\x1b[0m\x1b[01;35mimg1.jpg\x1b[0m\n\
7049 \x1b[01;35mIMG2.JPG\x1b[0m\n\
7050 \x1b[01;31mfile1.z\x1b[0m\n\
7051 \x1b[01;31mfile2.Z\x1b[0m",
7052 /* cSpell:enable */
7053 );
7054
7055 // *.jpg is specified more than once with different cases and style, so
7056 // case should matter here
7057 let result = scene
7058 .ucmd()
7059 .env("LS_COLORS", "*.jpg=01;35:*.JPG=01;35;46")
7060 .arg("-U1")
7061 .arg("--color=always")
7062 .arg("img1.jpg")
7063 .arg("IMG2.JPG")
7064 .arg("img3.JpG")
7065 .succeeds();
7066 result.stdout_contains(
7067 /* cSpell:disable */
7068 "\x1b[0m\x1b[01;35mimg1.jpg\x1b[0m\n\
7069 \x1b[01;35;46mIMG2.JPG\x1b[0m\n\
7070 img3.JpG",
7071 /* cSpell:enable */
7072 );
7073
7074 // *.jpg is specified more than once with different cases but style is same, so
7075 // case can ignored
7076 let result = scene
7077 .ucmd()
7078 .env("LS_COLORS", "*.jpg=01;35:*.JPG=01;35")
7079 .arg("-U1")
7080 .arg("--color=always")
7081 .arg("img1.jpg")
7082 .arg("IMG2.JPG")
7083 .arg("img3.JpG")
7084 .succeeds();
7085 result.stdout_contains(
7086 /* cSpell:disable */
7087 "\x1b[0m\x1b[01;35mimg1.jpg\x1b[0m\n\
7088 \x1b[01;35mIMG2.JPG\x1b[0m\n\
7089 \x1b[01;35mimg3.JpG\x1b[0m",
7090 /* cSpell:enable */
7091 );
7092
7093 // last *.jpg gets more priority resulting in same style across
7094 // different cases specified, so case can ignored
7095 let result = scene
7096 .ucmd()
7097 .env("LS_COLORS", "*.jpg=01;35:*.jpg=01;35;46:*.JPG=01;35;46")
7098 .arg("-U1")
7099 .arg("--color=always")
7100 .arg("img1.jpg")
7101 .arg("IMG2.JPG")
7102 .arg("img3.JpG")
7103 .succeeds();
7104 result.stdout_contains(
7105 /* cSpell:disable */
7106 "\x1b[0m\x1b[01;35;46mimg1.jpg\x1b[0m\n\
7107 \x1b[01;35;46mIMG2.JPG\x1b[0m\n\
7108 \x1b[01;35;46mimg3.JpG\x1b[0m",
7109 /* cSpell:enable */
7110 );
7111
7112 // last *.jpg gets more priority resulting in different style across
7113 // different cases specified, so case matters
7114 let result = scene
7115 .ucmd()
7116 .env("LS_COLORS", "*.jpg=01;35;46:*.jpg=01;35:*.JPG=01;35;46")
7117 .arg("-U1")
7118 .arg("--color=always")
7119 .arg("img1.jpg")
7120 .arg("IMG2.JPG")
7121 .arg("img3.JpG")
7122 .succeeds();
7123 result.stdout_contains(
7124 /* cSpell:disable */
7125 "\x1b[0m\x1b[01;35mimg1.jpg\x1b[0m\n\
7126 \x1b[01;35;46mIMG2.JPG\x1b[0m\n\
7127 img3.JpG",
7128 /* cSpell:enable */
7129 );
7130 }
7131
7132 #[cfg(all(unix, target_os = "linux"))]
7133 #[test]
7134 fn test_ls_capabilities() {
7135 let scene = TestScenario::new(util_name!());
7136 let at = &scene.fixtures;
7137
7138 // Test must be run as root (or with `sudo -E`)
7139 // fakeroot setcap cap_net_bind_service=ep /tmp/file_name
7140 // doesn't trigger an error and fails silently
7141 if scene.cmd("whoami").run().stdout_str() != "root\n" {
7142 return;
7143 }
7144 at.mkdir("test");
7145 at.mkdir("test/dir");
7146 at.touch("test/cap_pos.txt");
7147 at.touch("test/dir/cap_neg.txt");
7148 at.touch("test/dir/cap_pos.txt");
7149
7150 let files = ["test/cap_pos.txt", "test/dir/cap_pos.txt"];
7151 for file in &files {
7152 scene
7153 .cmd("sudo")
7154 .args(&[
7155 "-E",
7156 "--non-interactive",
7157 "setcap",
7158 "cap_net_bind_service=ep",
7159 at.plus(file).to_str().unwrap(),
7160 ])
7161 .succeeds();
7162 }
7163
7164 let ls_colors = "di=:ca=30;41";
7165
7166 scene
7167 .ucmd()
7168 .env("LS_COLORS", ls_colors)
7169 .arg("--color=always")
7170 .arg("test/cap_pos.txt")
7171 .arg("test/dir")
7172 .succeeds()
7173 .stdout_contains("\x1b[30;41mtest/cap_pos.txt") // spell-checker:disable-line
7174 .stdout_contains("\x1b[30;41mcap_pos.txt") // spell-checker:disable-line
7175 .stdout_does_not_contain("0;41mcap_neg.txt"); // spell-checker:disable-line
7176
7177 // If ca= is not defined, ensure the specific style (.txt) for the file is used
7178 let ls_colors = "di=:no=30;41:*.txt=31;41";
7179
7180 scene
7181 .ucmd()
7182 .env("LS_COLORS", ls_colors)
7183 .arg("--color=always")
7184 .arg("test/cap_pos.txt")
7185 .succeeds()
7186 .stdout_contains("\x1b[31;41mtest/cap_pos.txt"); // spell-checker:disable-line
7187 }
7188
7189 #[cfg(feature = "test_risky_names")]
7190 #[test]
7191 fn test_non_unicode_names() {
7192 // more extensive unit tests for correct escaping etc. are in the quoting_style module
7193 let scene = TestScenario::new(util_name!());
7194 let target_file = uucore::os_str_from_bytes(b"some-dir1/\xC0.file")
7195 .expect("Only unix platforms can test non-unicode names");
7196 let target_dir = uucore::os_str_from_bytes(b"some-dir1/\xC0.dir")
7197 .expect("Only unix platforms can test non-unicode names");
7198 let at = &scene.fixtures;
7199 at.mkdir("some-dir1");
7200 at.touch(target_file);
7201 at.mkdir(target_dir);
7202
7203 scene
7204 .ucmd()
7205 .arg("--quoting-style=shell-escape")
7206 .arg("some-dir1")
7207 .succeeds()
7208 .stdout_contains("''$'\\300''.dir'")
7209 .stdout_contains("''$'\\300''.file'");
7210
7211 scene
7212 .ucmd()
7213 .arg("--quoting-style=literal")
7214 .arg("--show-control-chars")
7215 .arg("some-dir1")
7216 .succeeds()
7217 .stdout_is_bytes(b"\xC0.dir\n\xC0.file\n");
7218 }
7219
7220 #[test]
7221 fn test_time_style_timezone_name() {
7222 let re_custom_format = Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d* UTC f\n").unwrap();
7223 let (at, mut ucmd) = at_and_ucmd!();
7224 at.touch("f");
7225 ucmd.env("TZ", "UTC0")
7226 .args(&["-l", "--time-style=+%Z"])
7227 .succeeds()
7228 .stdout_matches(&re_custom_format);
7229 }
7230
7231 #[test]
7232 fn test_unknown_format_specifier() {
7233 let re_custom_format = Regex::new(r"[a-z-]* \d* [\w.]* [\w.]* \d+ \d{4} %0 \d{9} f\n").unwrap();
7234 let (at, mut ucmd) = at_and_ucmd!();
7235 at.touch("f");
7236 ucmd.args(&["-l", "--time-style=+%Y %0 %N"])
7237 .succeeds()
7238 .stdout_matches(&re_custom_format);
7239 }
7240
7241 #[cfg(all(unix, not(target_vendor = "apple")))]
7242 #[test]
7243 fn test_acl_display_symlink() {
7244 use std::process::Command;
7245
7246 let scene = TestScenario::new(util_name!());
7247 let at = &scene.fixtures;
7248
7249 let dir_name = "dir";
7250 let link_name = "link";
7251 at.mkdir(dir_name);
7252
7253 // calling the command directly. xattr requires some dev packages to be installed
7254 // and it adds a complex dependency just for a test
7255 match Command::new("setfacl")
7256 .args(["-d", "-m", "u:bin:rwx", &at.plus_as_string(dir_name)])
7257 .status()
7258 .map(|status| status.code())
7259 {
7260 Ok(Some(0)) => {}
7261 Ok(_) => {
7262 println!("test skipped: setfacl failed");
7263 return;
7264 }
7265 Err(e) => {
7266 println!("test skipped: setfacl failed with {e}");
7267 return;
7268 }
7269 }
7270
7271 at.symlink_dir(dir_name, link_name);
7272
7273 let re_with_acl = Regex::new(r"[a-z-]*\+\s\d+\s.*link").unwrap();
7274
7275 scene
7276 .ucmd()
7277 .arg("-lLd")
7278 .arg(link_name)
7279 .succeeds()
7280 .stdout_matches(&re_with_acl);
7281
7282 let test2: uutests::util::CmdResult = scene.ucmd().arg("-l").succeeds();
7283
7284 let mut iter = test2
7285 .stdout()
7286 .split(|b| b == &b'\n')
7287 .skip(1)
7288 .filter_map(|line: &[u8]| line.iter().position(|b: &u8| b.is_ascii_digit()));
7289
7290 let first = iter.next().unwrap();
7291
7292 assert!(iter.all(|i| i == first));
7293 }
7294
7295 #[cfg(all(unix, not(target_os = "macos")))]
7296 #[test]
7297 fn test_acl_display_symlink_without_dereference() {
7298 use std::process::Command;
7299
7300 let scene = TestScenario::new(util_name!());
7301 let at = &scene.fixtures;
7302
7303 let dir_name = "dir";
7304 let link_name = "link";
7305 at.mkdir(dir_name);
7306
7307 match Command::new("setfacl")
7308 .args(["-d", "-m", "u:bin:rwx", &at.plus_as_string(dir_name)])
7309 .status()
7310 .map(|status| status.code())
7311 {
7312 Ok(Some(0)) => {}
7313 Ok(_) => {
7314 println!("test skipped: setfacl failed");
7315 return;
7316 }
7317 Err(e) => {
7318 println!("test skipped: setfacl failed with {e}");
7319 return;
7320 }
7321 }
7322
7323 at.symlink_dir(dir_name, link_name);
7324
7325 scene
7326 .ucmd()
7327 .arg("-ld")
7328 .arg(link_name)
7329 .succeeds()
7330 .stdout_does_not_contain("+");
7331 }
7332
7333 #[test]
7334 fn ls_emoji_alignment() {
7335 let scene = TestScenario::new(util_name!());
7336 let at = &scene.fixtures;
7337
7338 at.touch("a");
7339 at.touch("💐");
7340 at.touch("漢");
7341 scene
7342 .ucmd()
7343 .succeeds()
7344 .stdout_contains("a")
7345 .stdout_contains("💐")
7346 .stdout_contains("漢");
7347 }
7348
7349 // Additional tests for TIME_STYLE and time sorting compatibility with GNU
7350 #[test]
7351 fn test_ls_time_style_env_full_iso() {
7352 let scene = TestScenario::new(util_name!());
7353 let at = &scene.fixtures;
7354 at.touch("t1");
7355
7356 let out = scene
7357 .ucmd()
7358 .env("TZ", "UTC")
7359 .env("TIME_STYLE", "full-iso")
7360 .arg("-l")
7361 .arg("t1")
7362 .succeeds();
7363
7364 // Expect an ISO-like timestamp in output (YYYY-MM-DD HH:MM)
7365 let re = Regex::new(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}").unwrap();
7366 assert!(
7367 re.is_match(out.stdout_str()),
7368 "unexpected timestamp: {}",
7369 out.stdout_str()
7370 );
7371 }
7372
7373 #[test]
7374 fn test_ls_time_style_iso_recent_and_older() {
7375 let scene = TestScenario::new(util_name!());
7376 let at = &scene.fixtures;
7377 // Recent file (now)
7378 at.touch("recent");
7379
7380 // Recent format for --time-style=iso is %m-%d %H:%M
7381 let recent = scene
7382 .ucmd()
7383 .env("TZ", "UTC")
7384 .arg("-l")
7385 .arg("--time-style=iso")
7386 .arg("recent")
7387 .succeeds();
7388 let re_recent = Regex::new(r"(^|\n).*\d{2}-\d{2} \d{2}:\d{2} ").unwrap();
7389 assert!(
7390 re_recent.is_match(recent.stdout_str()),
7391 "recent not matched: {}",
7392 recent.stdout_str()
7393 );
7394
7395 // Older format appends a full ISO date padded (year present)
7396 let f = at.make_file("older");
7397 f.set_modified(std::time::UNIX_EPOCH).unwrap();
7398
7399 let older = scene
7400 .ucmd()
7401 .arg("-l")
7402 .arg("--time-style=iso")
7403 .arg("older")
7404 .succeeds();
7405 let re_older = Regex::new(r"(^|\n).*\d{4}-\d{2}-\d{2} +").unwrap();
7406 assert!(
7407 re_older.is_match(older.stdout_str()),
7408 "older not matched: {}",
7409 older.stdout_str()
7410 );
7411 }
7412
7413 #[test]
7414 fn test_ls_time_style_posix_locale_override() {
7415 let scene = TestScenario::new(util_name!());
7416 let at = &scene.fixtures;
7417 at.touch("p1");
7418
7419 // With LC_ALL=POSIX and TIME_STYLE=posix-full-iso, GNU falls back to locale format like "%b %e %H:%M"
7420 let out = scene
7421 .ucmd()
7422 .env("TZ", "UTC")
7423 .env("LC_ALL", "POSIX")
7424 .env("TIME_STYLE", "posix-full-iso")
7425 .arg("-l")
7426 .arg("p1")
7427 .succeeds();
7428 // Expect month name rather than ISO dashes
7429 let re_locale = Regex::new(r" [A-Z][a-z]{2} +\d{1,2} +\d{2}:\d{2} ").unwrap();
7430 assert!(
7431 re_locale.is_match(out.stdout_str()),
7432 "locale format not matched: {}",
7433 out.stdout_str()
7434 );
7435 }
7436
7437 #[test]
7438 fn test_ls_time_style_precedence_last_wins() {
7439 let scene = TestScenario::new(util_name!());
7440 let at = &scene.fixtures;
7441 at.touch("timefile");
7442
7443 // time-style first, full-time last -> expect full-iso-like (seconds)
7444 let out1 = scene
7445 .ucmd()
7446 .arg("--time-style=long-iso")
7447 .arg("--full-time")
7448 .arg("-l")
7449 .arg("timefile")
7450 .succeeds();
7451 let has_seconds = Regex::new(r"\d{2}:\d{2}:\d{2}")
7452 .unwrap()
7453 .is_match(out1.stdout_str());
7454 assert!(
7455 has_seconds,
7456 "expected seconds in full-time: {}",
7457 out1.stdout_str()
7458 );
7459
7460 // full-time first, time-style last -> expect style override (no seconds for long-iso)
7461 let out2 = scene
7462 .ucmd()
7463 .arg("--full-time")
7464 .arg("--time-style=long-iso")
7465 .arg("-l")
7466 .arg("timefile")
7467 .succeeds();
7468 let no_seconds = !Regex::new(r"\d{2}:\d{2}:\d{2}")
7469 .unwrap()
7470 .is_match(out2.stdout_str());
7471 assert!(
7472 no_seconds,
7473 "expected no seconds in long-iso: {}",
7474 out2.stdout_str()
7475 );
7476 }
7477
7478 #[test]
7479 fn test_ls_time_sort_without_long() {
7480 let scene = TestScenario::new(util_name!());
7481
7482 // Create two files with deterministic, distinct modification times
7483 let at = &scene.fixtures;
7484 let f = at.make_file("a");
7485 f.set_modified(std::time::UNIX_EPOCH).unwrap();
7486 at.touch("b");
7487
7488 // Compare default (name order) vs time-sorted (-t) order; they should differ
7489 let default_out = scene.ucmd().succeeds();
7490 let t_out = scene.ucmd().arg("-t").succeeds();
7491
7492 let def = default_out.stdout_str();
7493 let t = t_out.stdout_str();
7494 assert_ne!(def, t);
7495 }
7496
7497 // Tests for -f flag implementation
7498 #[test]
7499 fn test_f_flag_enables_all() {
7500 // Test that -f enables -a (shows all files including . and ..)
7501 let scene = TestScenario::new(util_name!());
7502 let at = &scene.fixtures;
7503 at.touch("visible");
7504 at.touch(".hidden");
7505
7506 scene
7507 .ucmd()
7508 .arg("-f")
7509 .succeeds()
7510 .stdout_contains("visible")
7511 .stdout_contains(".hidden");
7512 }
7513
7514 #[test]
7515 fn test_f_flag_disables_sorting() {
7516 // Test that -f disables sorting by verifying it matches -U behavior
7517 // and that explicitly sorting after -f works (proving sorting was disabled)
7518 let scene = TestScenario::new(util_name!());
7519 let at = &scene.fixtures;
7520 at.touch("zebra");
7521 at.touch("apple");
7522 at.touch("banana");
7523
7524 // Get outputs with different flags
7525 let out_f = scene
7526 .ucmd()
7527 .arg("-f")
7528 .arg("-1")
7529 .succeeds()
7530 .stdout_move_str();
7531 let out_u_all = scene
7532 .ucmd()
7533 .arg("-U")
7534 .arg("-a")
7535 .arg("-1")
7536 .succeeds()
7537 .stdout_move_str();
7538
7539 // Test that explicit sorting after -f works (proves -f disabled sorting)
7540 let out_f_then_sort = scene
7541 .ucmd()
7542 .arg("-f")
7543 .arg("--sort=name")
7544 .arg("-1")
7545 .succeeds()
7546 .stdout_move_str();
7547
7548 // Get sorted output for comparison
7549 let out_sorted = scene
7550 .ucmd()
7551 .arg("-a")
7552 .arg("-1")
7553 .succeeds()
7554 .stdout_move_str();
7555
7556 // -f output should match -U output (both use directory order)
7557 assert_eq!(out_f, out_u_all, "-f should match unsorted -U behavior");
7558
7559 // Explicit --sort after -f should enable sorting
7560 assert_eq!(
7561 out_f_then_sort, out_sorted,
7562 "--sort after -f should enable sorting"
7563 );
7564 }
7565
7566 #[test]
7567 fn test_f_flag_disables_implicit_color() {
7568 // Test that -f disables implicit color (not explicitly set)
7569 let scene = TestScenario::new(util_name!());
7570 let at = &scene.fixtures;
7571 at.mkdir("dir");
7572 at.touch("file.txt");
7573
7574 // -f without explicit --color: should not have color
7575 let result = scene.ucmd().arg("-f").succeeds().stdout_move_str();
7576 assert!(
7577 !result.contains("\x1b["),
7578 "Color should be disabled with -f alone"
7579 );
7580 }
7581
7582 #[test]
7583 fn test_explicit_color_always_works_with_f() {
7584 // Test that explicit --color always enables color, regardless of -f
7585 let scene = TestScenario::new(util_name!());
7586 let at = &scene.fixtures;
7587 at.mkdir("dir");
7588 at.touch("file.txt");
7589
7590 // --color then -f: explicit --color should still enable color
7591 let result1 = scene
7592 .ucmd()
7593 .arg("--color=always")
7594 .arg("-f")
7595 .succeeds()
7596 .stdout_move_str();
7597 assert!(
7598 result1.contains("\x1b["),
7599 "Explicit --color should work even with -f after"
7600 );
7601
7602 // -f then --color: explicit --color should enable color
7603 let result2 = scene
7604 .ucmd()
7605 .arg("-f")
7606 .arg("--color=always")
7607 .succeeds()
7608 .stdout_move_str();
7609 assert!(
7610 result2.contains("\x1b["),
7611 "Explicit --color should work even with -f before"
7612 );
7613 }
7614
7615 #[test]
7616 fn test_f_overrides_big_a() {
7617 // Test last-flag-wins between -f and -A using .. as discriminator
7618 // -f shows .. (all files including . and ..)
7619 // -A hides .. (almost all, excluding . and ..)
7620 let scene = TestScenario::new(util_name!());
7621 let at = &scene.fixtures;
7622 at.touch("visible");
7623 at.touch(".hidden");
7624
7625 // -A then -f: -f wins, should show ..
7626 let out_a_f = scene
7627 .ucmd()
7628 .arg("-A")
7629 .arg("-f")
7630 .arg("-1")
7631 .succeeds()
7632 .stdout_move_str();
7633 assert!(
7634 out_a_f.lines().any(|l| l == ".."),
7635 "-f should win and show .."
7636 );
7637
7638 // -f then -A: -A wins, should NOT show ..
7639 let out_f_a = scene
7640 .ucmd()
7641 .arg("-f")
7642 .arg("-A")
7643 .arg("-1")
7644 .succeeds()
7645 .stdout_move_str();
7646 assert!(
7647 !out_f_a.lines().any(|l| l == ".."),
7648 "-A should win and hide .."
7649 );
7650 }
7651
7652 #[test]
7653 fn test_f_overrides_sort_flags() {
7654 // Test last-flag-wins using size-based sorting for determinism
7655 let scene = TestScenario::new(util_name!());
7656 let at = &scene.fixtures;
7657
7658 // Create files with different sizes for predictable sort order
7659 at.write("small.txt", "a"); // 1 byte
7660 at.write("medium.txt", "bb"); // 2 bytes
7661 at.write("large.txt", "ccc"); // 3 bytes
7662
7663 // Get baseline outputs (include -a to match -f behavior which shows all files)
7664 let out_s = scene
7665 .ucmd()
7666 .arg("-S")
7667 .arg("-a")
7668 .arg("-1")
7669 .succeeds()
7670 .stdout_move_str();
7671 let out_u = scene
7672 .ucmd()
7673 .arg("-U")
7674 .arg("-a")
7675 .arg("-1")
7676 .succeeds()
7677 .stdout_move_str();
7678
7679 // -f then -S: -S wins, should be sorted by size
7680 let out_f_s = scene
7681 .ucmd()
7682 .arg("-f")
7683 .arg("-S")
7684 .arg("-1")
7685 .succeeds()
7686 .stdout_move_str();
7687 assert_eq!(
7688 out_f_s, out_s,
7689 "-S should win: output should be size-sorted"
7690 );
7691
7692 // -S then -f: -f wins, should be unsorted
7693 let out_s_f = scene
7694 .ucmd()
7695 .arg("-S")
7696 .arg("-f")
7697 .arg("-1")
7698 .succeeds()
7699 .stdout_move_str();
7700 assert_eq!(
7701 out_s_f, out_u,
7702 "-f should win: output should match unsorted -U"
7703 );
7704 }
7705
7706 #[test]
7707 fn test_a_overrides_f_files() {
7708 // Test that -a after -f still shows all files
7709 let scene = TestScenario::new(util_name!());
7710 let at = &scene.fixtures;
7711 at.touch("visible");
7712 at.touch(".hidden");
7713
7714 scene
7715 .ucmd()
7716 .arg("-f")
7717 .arg("-a")
7718 .succeeds()
7719 .stdout_contains(".hidden")
7720 .stdout_contains("visible");
7721 }
7722
7723 #[test]
7724 fn test_big_u_participates_in_sort_flag_wins() {
7725 // Test that -U participates in last-flag-wins with sorting flags
7726 // -U disables sorting (like -f), but can be overridden by other sort flags
7727 let scene = TestScenario::new(util_name!());
7728 let at = &scene.fixtures;
7729
7730 // Create files with different sizes for predictable sort order
7731 at.write("small.txt", "a"); // 1 byte
7732 at.write("medium.txt", "bb"); // 2 bytes
7733 at.write("large.txt", "ccc"); // 3 bytes
7734
7735 // Get baseline outputs
7736 let out_s = scene
7737 .ucmd()
7738 .arg("-S")
7739 .arg("-1")
7740 .succeeds()
7741 .stdout_move_str();
7742 let out_u = scene
7743 .ucmd()
7744 .arg("-U")
7745 .arg("-1")
7746 .succeeds()
7747 .stdout_move_str();
7748
7749 // -U then -S: -S wins, should be sorted by size
7750 let out_u_s = scene
7751 .ucmd()
7752 .arg("-U")
7753 .arg("-S")
7754 .arg("-1")
7755 .succeeds()
7756 .stdout_move_str();
7757 assert_eq!(
7758 out_u_s, out_s,
7759 "-S should win: output should be size-sorted"
7760 );
7761
7762 // -S then -U: -U wins, should match plain -U output
7763 let out_s_u = scene
7764 .ucmd()
7765 .arg("-S")
7766 .arg("-U")
7767 .arg("-1")
7768 .succeeds()
7769 .stdout_move_str();
7770 assert_eq!(
7771 out_s_u, out_u,
7772 "-U should win: output should match plain -U"
7773 );
7774
7775 // Verify size-sorted output is in correct order (this is deterministic)
7776 let lines: Vec<&str> = out_s.lines().collect();
7777 assert_eq!(lines[0], "large.txt", "First file should be largest");
7778 assert_eq!(lines[1], "medium.txt", "Second file should be medium");
7779 assert_eq!(lines[2], "small.txt", "Third file should be smallest");
7780 }
7781
7782 #[test]
7783 fn test_f_flag_combined_behavior() {
7784 // Test that -f behaves correctly with all its effects together
7785 let scene = TestScenario::new(util_name!());
7786 let at = &scene.fixtures;
7787 at.touch("zebra.txt");
7788 at.touch(".hidden");
7789 at.touch("apple.txt");
7790 at.mkdir("directory");
7791
7792 let result = scene.ucmd().arg("-f").succeeds().stdout_move_str();
7793
7794 // Should show hidden files
7795 assert!(result.contains(".hidden"));
7796 // Should show all files
7797 assert!(result.contains("zebra.txt"));
7798 assert!(result.contains("apple.txt"));
7799 assert!(result.contains("directory"));
7800 // Should not contain ANSI color codes
7801 assert!(!result.contains("\x1b["));
7802 }
7803
7804 #[test]
7805 fn test_f_with_long_format() {
7806 // Test that -f works with long format (-l)
7807 let scene = TestScenario::new(util_name!());
7808 let at = &scene.fixtures;
7809 at.touch("file1");
7810 at.touch(".hidden");
7811
7812 let result = scene
7813 .ucmd()
7814 .arg("-f")
7815 .arg("-l")
7816 .succeeds()
7817 .stdout_move_str();
7818
7819 // Should show hidden files in long format
7820 assert!(result.contains(".hidden"));
7821 assert!(result.contains("file1"));
7822 // Long format should still work (contains permissions, etc.)
7823 assert!(result.contains("-rw"));
7824 }
7825
7826 #[test]
7827 #[cfg(target_os = "linux")]
7828 fn test_ls_proc_self_fd_no_errors() {
7829 // Regression test: ReadDir must stay alive until metadata() is called
7830 // to prevent "cannot access '/proc/self/fd/3'" errors.
7831 let scene = TestScenario::new(util_name!());
7832
7833 scene
7834 .ucmd()
7835 .arg("-l")
7836 .arg("/proc/self/fd")
7837 .succeeds()
7838 .stderr_does_not_contain("cannot access");
7839 }
7840
7841 #[test]
7842 #[cfg(unix)]
7843 fn test_ls_recursive_no_fd_leak() {
7844 let scene = TestScenario::new(util_name!());
7845 let at = &scene.fixtures;
7846
7847 let deep_path: String = (1..=30)
7848 .map(|i| i.to_string())
7849 .collect::<Vec<_>>()
7850 .join("/");
7851 at.mkdir_all(&deep_path);
7852
7853 scene
7854 .ucmd()
7855 .arg("-R")
7856 .arg("1")
7857 .limit(Resource::NOFILE, 20, 20)
7858 .succeeds()
7859 .no_stderr();
7860 }
7861
7862 #[test]
7863 #[cfg(all(unix, not(target_vendor = "apple")))]
7864 fn test_ls_non_utf8_hidden() {
7865 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
7866 let scene = TestScenario::new(util_name!());
7867 let at = &scene.fixtures;
7868
7869 at.touch(OsStr::from_bytes(b".hidden\x80"));
7870
7871 scene.ucmd().succeeds().stdout_does_not_contain(".hidden");
7872 }
7873
7874 #[test]
7875 #[cfg(target_os = "wasi")]
7876 fn test_ls_a_dotdot_no_error_on_wasi() {
7877 // On WASI the sandbox may block access to ".." at the preopened root.
7878 // ls -a should still succeed and show ".." without an error message.
7879 let scene = TestScenario::new(util_name!());
7880 scene
7881 .ucmd()
7882 .arg("-a")
7883 .arg("-1")
7884 .succeeds()
7885 .stdout_contains("..")
7886 .no_stderr();
7887 }
7888
7889 #[test]
7890 #[cfg(target_os = "wasi")]
7891 fn test_ls_al_no_capabilities_insufficient_on_wasi() {
7892 // `ls -al` reads metadata for every entry including "..". Without the
7893 // WASI fallback, stat on ".." at the preopened root returns
7894 // ERRNO_NOTCAPABLE, which surfaces to the user as "Capabilities
7895 // insufficient". Guard against that regression here.
7896 let scene = TestScenario::new(util_name!());
7897 let out = scene.ucmd().arg("-al").succeeds();
7898 out.no_stderr();
7899 assert!(
7900 !out.stdout_str().contains("Capabilities insufficient"),
7901 "ls -al stdout leaked a WASI capability error: {}",
7902 out.stdout_str()
7903 );
7904 }
7905
7906 // https://github.com/uutils/coreutils/issues/13280
7907 // options `--sort`, `--format`, `--time`, and `--blocksize` may be detached
7908 #[test]
7909 fn test_long_options_detached() {
7910 new_ucmd!().arg("--sort").arg("name").succeeds();
7911 new_ucmd!().arg("--format").arg("single-column").succeeds();
7912 new_ucmd!().arg("--time").arg("mtime").succeeds();
7913 new_ucmd!().arg("--block-size").arg("512").succeeds();
7914 }
7915
7916 // Without -R a directory can never be revisited, so ls should not spend a stat
7917 // recording it for the loop detection that only recursion consults.
7918 #[test]
7919 #[cfg(target_os = "linux")]
7920 fn test_no_extra_stat_without_recursion() {
7921 use std::process::Command;
7922
7923 let scene = TestScenario::new(util_name!());
7924 scene.fixtures.mkdir("some-dir");
7925
7926 let stats_of_some_dir = |args: &[&str]| -> Option<usize> {
7927 let output = Command::new("strace")
7928 .args(["-qq", "-e", "trace=stat,statx,lstat,newfstatat"])
7929 .arg(&scene.bin_path)
7930 .arg(scene.util_name.as_str())
7931 .args(args)
7932 .current_dir(scene.fixtures.as_string())
7933 .output()
7934 .ok()?;
7935 let trace = String::from_utf8_lossy(&output.stderr);
7936 // No syscalls traced at all means strace could not do its job here.
7937 if !trace.contains('(') {
7938 return None;
7939 }
7940 Some(trace.lines().filter(|l| l.contains("\"some-dir\"")).count())
7941 };
7942
7943 let Some(count) = stats_of_some_dir(&["-F", "--color=always", "some-dir"]) else {
7944 return; // strace unavailable, e.g. restricted ptrace in a container
7945 };
7946 assert_eq!(count, 1, "expected a single stat of the directory operand");
7947 }
7948
7949 #[cfg(target_os = "linux")]
7950 #[test]
7951 fn test_write_error() {
7952 let ts = TestScenario::new(util_name!());
7953
7954 ts.fixtures.touch("dummy_file.txt");
7955
7956 let dev_full = std::fs::OpenOptions::new()
7957 .write(true)
7958 .open("/dev/full")
7959 .unwrap();
7960
7961 ts.ucmd()
7962 .set_stdout(dev_full)
7963 .fails_with_code(2)
7964 .stderr_is("ls: write error: No space left on device\n");
7965 }
7966
7967 #[cfg(target_os = "linux")]
7968 #[test]
7969 fn test_dired_write_error() {
7970 let ts = TestScenario::new(util_name!());
7971
7972 let dev_full = std::fs::OpenOptions::new()
7973 .write(true)
7974 .open("/dev/full")
7975 .unwrap();
7976
7977 // Nothing is buffered for a failing operand, so the trailer is the first
7978 // thing written: it must report the error rather than panic.
7979 ts.ucmd()
7980 .args(&["--dired", "nonexistent"])
7981 .set_stdout(dev_full)
7982 .fails_with_code(2)
7983 .stderr_is(concat!(
7984 "ls: cannot access 'nonexistent': No such file or directory\n",
7985 "ls: write error: No space left on device\n",
7986 ));
7987 }
7988
7989 #[cfg(unix)]
7990 #[test]
7991 fn test_ls_long_stat_failure_is_reported() {
7992 use rustix::process::geteuid;
7993 use std::os::unix::fs::PermissionsExt;
7994
7995 // root bypasses the directory search permission check this relies on
7996 if geteuid().is_root() {
7997 return;
7998 }
7999
8000 let (at, mut ucmd) = at_and_ucmd!();
8001 at.mkdir("dir");
8002 at.touch("dir/file");
8003 at.symlink_file("/", "dir/link");
8004 // readable but not searchable: read_dir() succeeds while stat() on the
8005 // entries fails with EACCES
8006 at.set_mode("dir", 0o600);
8007
8008 ucmd.args(&["-l", "dir"])
8009 .fails_with_code(1)
8010 .stdout_contains("? file")
8011 .stdout_contains("? link")
8012 .stderr_contains("cannot access 'dir/file': Permission denied")
8013 .stderr_contains("cannot access 'dir/link': Permission denied");
8014
8015 // restore so that the test directory can be cleaned up
8016 std::fs::set_permissions(at.plus("dir"), std::fs::Permissions::from_mode(0o700)).unwrap();
8017 }
8018
8019 #[cfg(all(feature = "feat_diagnostics", not(wasi_runner)))]
8020 mod diagnostics {
8021 use super::*;
8022
8023 #[cfg(unix)]
8024 #[test]
8025 fn test_snippet_points_at_the_unknown_unit_of_block_size() {
8026 let result = new_ucmd!()
8027 .terminal_sim_stderr()
8028 .arg("--block-size=1fb")
8029 .fails_with_code(2);
8030
8031 assert_eq!(
8032 result.stderr_as_displayed(),
8033 "\
8034 ls: invalid --block-size argument '1fb'
8035 ╭─[ ls:1:18 ]
8036 │
8037 1 │ ls --block-size=1fb
8038 │ ─┬
8039 │ ╰── not a known unit
8040 │
8041 │ Help: a size is a number and an optional unit: K, M, G and so on for 1024, KB, MB, GB for 1000
8042 ───╯"
8043 );
8044 }
8045
8046 #[cfg(unix)]
8047 #[test]
8048 fn test_snippet_underlines_a_zero_block_size() {
8049 let result = new_ucmd!()
8050 .terminal_sim_stderr()
8051 .args(&["--block-size", "0"])
8052 .fails_with_code(2);
8053 let stderr = result.stderr_as_displayed();
8054
8055 assert_eq!(result.caret_column(), Some(17));
8056 assert!(!stderr.contains("not a known unit"), "{stderr}");
8057 }
8058
8059 #[test]
8060 fn test_plain_message_when_stderr_is_a_pipe() {
8061 new_ucmd!()
8062 .arg("--block-size=1fb")
8063 .fails_with_code(2)
8064 .stderr_is("ls: invalid --block-size argument '1fb'\n");
8065 }
8066 }