1use std::fs;
2use std::path::{Path, PathBuf};
3use std::time::Instant;
4
5use rayon::prelude::*;
6use walkdir::WalkDir;
7
8use crate::entry::Entry;
9use crate::error::{Error, Result};
10use crate::filter::filter_entries;
11use crate::ignore::{apply_ignore_set, load_ignore_set, IgnoreSet};
12use crate::options::{CliSymlinkMode, ListOptions};
13use crate::sort::sort_entries;
14
15#[derive(Debug, Clone, Default, PartialEq, Eq)]
17pub struct ListTiming {
18 pub readdir_ms: u128,
20 pub stat_ms: u128,
22 pub sort_ms: u128,
24}
25
26impl ListTiming {
27 pub fn add_assign(&mut self, other: &ListTiming) {
29 self.readdir_ms = self.readdir_ms.saturating_add(other.readdir_ms);
30 self.stat_ms = self.stat_ms.saturating_add(other.stat_ms);
31 self.sort_ms = self.sort_ms.saturating_add(other.sort_ms);
32 }
33}
34
35#[derive(Debug, Clone)]
37pub struct Listing {
38 pub root: PathBuf,
40 pub root_is_dir: bool,
42 pub entries: Vec<Entry>,
44 pub minor_errors: usize,
47 pub timing: Option<ListTiming>,
49}
50
51impl Listing {
52 fn new(root: PathBuf, root_is_dir: bool, entries: Vec<Entry>) -> Self {
53 Self {
54 root,
55 root_is_dir,
56 entries,
57 minor_errors: 0,
58 timing: None,
59 }
60 }
61
62 fn with_timing(mut self, timing: Option<ListTiming>) -> Self {
63 self.timing = timing;
64 self
65 }
66}
67
68fn follow_cli_path(path: &Path, opts: &ListOptions) -> bool {
70 if opts.follow_links {
71 return true;
72 }
73 match opts.cli_symlink {
74 CliSymlinkMode::Never => false,
75 CliSymlinkMode::Always => {
76 fs::symlink_metadata(path)
78 .map(|m| m.file_type().is_symlink())
79 .unwrap_or(false)
80 }
81 CliSymlinkMode::DirOnly => {
82 let is_link = fs::symlink_metadata(path)
84 .map(|m| m.file_type().is_symlink())
85 .unwrap_or(false);
86 if !is_link {
87 return false;
88 }
89 fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false)
90 }
91 }
92}
93
94pub fn list_path(path: &Path, opts: &ListOptions) -> Result<Listing> {
98 let path = if path.as_os_str().is_empty() {
99 Path::new(".")
100 } else {
101 path
102 };
103
104 let follow = follow_cli_path(path, opts);
105
106 let meta = if follow {
107 fs::metadata(path)
108 } else {
109 fs::symlink_metadata(path)
110 }
111 .map_err(|source| {
112 if source.kind() == std::io::ErrorKind::NotFound {
113 Error::NotFound(path.to_path_buf())
114 } else {
115 Error::Metadata {
116 path: path.to_path_buf(),
117 source,
118 }
119 }
120 })?;
121
122 if opts.directory || !meta.is_dir() {
124 let fill = meta_fill_from(opts);
125 let entry = if follow {
126 Entry::from_path_follow_with(path, 0, fill)?
127 } else {
128 Entry::from_path_and_meta_with(path, &meta, 0, fill)?
129 };
130 return Ok(Listing::new(path.to_path_buf(), meta.is_dir(), vec![entry]));
131 }
132
133 if opts.recursive {
134 list_recursive(path, opts)
135 } else {
136 list_directory(path, opts)
137 }
138}
139
140fn meta_fill_from(opts: &ListOptions) -> crate::entry::MetaFill {
141 crate::entry::MetaFill {
142 resolve_names: opts.resolve_owner_group,
143 read_context: opts.read_selinux,
144 }
145}
146
147fn entry_from_dir_entry(
149 item: &fs::DirEntry,
150 follow_links: bool,
151 fill: crate::entry::MetaFill,
152 prefer_statx: bool,
153) -> Option<Entry> {
154 let entry_path = item.path();
155 if follow_links {
156 return Entry::from_path_follow_with(&entry_path, 0, fill).ok();
157 }
158 #[cfg(target_os = "linux")]
159 {
160 if prefer_statx {
161 if let Ok(e) = crate::linux_statx::entry_from_statx(&entry_path, 0, fill) {
162 return Some(e);
163 }
164 }
165 }
166 #[cfg(not(target_os = "linux"))]
167 {
168 let _ = prefer_statx;
169 }
170 let meta = item
171 .metadata()
172 .or_else(|_| fs::symlink_metadata(&entry_path));
173 match meta {
174 Ok(m) => Entry::from_path_and_meta_with(&entry_path, &m, 0, fill).ok(),
175 Err(_) => None,
176 }
177}
178
179fn stat_dir_entries(dir_entries: &[fs::DirEntry], opts: &ListOptions) -> Vec<Entry> {
181 let follow = opts.follow_links;
182 let fill = meta_fill_from(opts);
183 let prefer_statx = opts.linux_statx;
184 let map_one = |item: &fs::DirEntry| entry_from_dir_entry(item, follow, fill, prefer_statx);
185
186 #[cfg(all(target_os = "linux", feature = "io-uring"))]
188 {
189 if opts.io_uring
190 && !follow
191 && dir_entries.len() >= crate::io_uring_stat::IO_URING_THRESHOLD
192 && !fill.resolve_names
193 && !fill.read_context
194 {
195 let paths: Vec<_> = dir_entries.iter().map(|d| d.path()).collect();
196 if let Some(entries) = crate::io_uring_stat::entries_from_paths_uring(&paths, fill) {
197 if entries.len() * 10 >= paths.len() * 8 {
199 return entries;
200 }
201 }
202 }
203 }
204
205 if !opts.use_parallel_stat(dir_entries.len()) {
206 return dir_entries.iter().filter_map(map_one).collect();
207 }
208
209 let collect = || dir_entries.par_iter().filter_map(map_one).collect();
210
211 if opts.threads > 1 {
212 match rayon::ThreadPoolBuilder::new()
213 .num_threads(opts.threads)
214 .build()
215 {
216 Ok(pool) => pool.install(collect),
217 Err(_) => collect(),
218 }
219 } else {
220 collect()
221 }
222}
223
224pub fn list_directory(path: &Path, opts: &ListOptions) -> Result<Listing> {
226 let collect_timing = opts.collect_timing;
227 let mut timing = ListTiming::default();
228
229 let mut entries = Vec::new();
230
231 let fill = meta_fill_from(opts);
232 if opts.all {
234 if let Ok(dot) = Entry::from_path_with(path, 0, fill) {
235 let mut e = dot;
236 e.name = ".".to_string();
237 entries.push(e);
238 }
239 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
240 if let Ok(mut e) = Entry::from_path_with(parent, 0, fill) {
241 e.name = "..".to_string();
242 e.path = parent.to_path_buf();
243 entries.push(e);
244 }
245 } else if let Ok(mut e) = Entry::from_path_with(path, 0, fill) {
246 e.name = "..".to_string();
248 entries.push(e);
249 }
250 }
251
252 let t_readdir = if collect_timing {
253 Some(Instant::now())
254 } else {
255 None
256 };
257
258 let read = fs::read_dir(path).map_err(|source| Error::ReadDir {
259 path: path.to_path_buf(),
260 source,
261 })?;
262
263 let mut dir_entries = Vec::new();
264 for item in read {
265 let item = item.map_err(|source| Error::ReadDir {
266 path: path.to_path_buf(),
267 source,
268 })?;
269 dir_entries.push(item);
270 }
271
272 if let Some(t0) = t_readdir {
273 timing.readdir_ms = t0.elapsed().as_millis();
274 }
275
276 let t_stat = if collect_timing {
277 Some(Instant::now())
278 } else {
279 None
280 };
281
282 let children = stat_dir_entries(&dir_entries, opts);
283 entries.extend(children);
284
285 if let Some(t0) = t_stat {
286 timing.stat_ms = t0.elapsed().as_millis();
287 }
288
289 let t_sort = if collect_timing {
290 Some(Instant::now())
291 } else {
292 None
293 };
294
295 filter_entries(&mut entries, opts);
296 if opts.use_ignore_files {
297 let set = load_ignore_set(path);
298 apply_ignore_set(&mut entries, &set);
299 }
300 sort_entries(&mut entries, opts);
302
303 if let Some(t0) = t_sort {
304 timing.sort_ms = t0.elapsed().as_millis();
305 }
306
307 Ok(
308 Listing::new(path.to_path_buf(), true, entries).with_timing(if collect_timing {
309 Some(timing)
310 } else {
311 None
312 }),
313 )
314}
315
316struct Walked {
318 path: PathBuf,
319 depth: usize,
320 is_dir: bool,
321}
322
323pub fn list_recursive(path: &Path, opts: &ListOptions) -> Result<Listing> {
325 let collect_timing = opts.collect_timing;
326 let mut timing = ListTiming::default();
327
328 let mut minor_errors = 0usize;
329 let max_depth = opts.max_depth.unwrap_or(usize::MAX);
330
331 let root_ignore = if opts.use_ignore_files {
332 Some(load_ignore_set(path))
333 } else {
334 None
335 };
336
337 let t_walk = if collect_timing {
338 Some(Instant::now())
339 } else {
340 None
341 };
342
343 let walker = WalkDir::new(path)
346 .follow_links(opts.follow_links)
347 .max_depth(max_depth)
348 .sort_by_file_name();
349
350 let mut walked: Vec<Walked> = Vec::new();
351 for item in walker {
352 let item = match item {
353 Ok(i) => i,
354 Err(_) => {
355 minor_errors += 1;
356 continue;
357 }
358 };
359 let depth = item.depth();
360 if depth == 0 {
361 continue; }
363 walked.push(Walked {
364 path: item.path().to_path_buf(),
365 depth,
366 is_dir: item.file_type().is_dir(),
367 });
368 }
369
370 if let Some(t0) = t_walk {
371 timing.readdir_ms = t0.elapsed().as_millis();
372 }
373
374 let fill = meta_fill_from(opts);
375 let t_stat = if collect_timing {
376 Some(Instant::now())
377 } else {
378 None
379 };
380
381 let use_parallel = opts.use_parallel_stat(walked.len().max(1));
383 let built: Vec<Option<Entry>> = if use_parallel {
384 let map = |w: &Walked| {
385 Entry::from_path_with(&w.path, w.depth, fill)
386 .ok()
387 .filter(|e| crate::filter::should_show(e, opts))
388 };
389 if opts.threads > 1 {
390 match rayon::ThreadPoolBuilder::new()
391 .num_threads(opts.threads)
392 .build()
393 {
394 Ok(pool) => pool.install(|| walked.par_iter().map(map).collect()),
395 Err(_) => walked.par_iter().map(map).collect(),
396 }
397 } else {
398 walked.par_iter().map(map).collect()
399 }
400 } else {
401 walked
402 .iter()
403 .map(|w| {
404 Entry::from_path_with(&w.path, w.depth, fill)
405 .ok()
406 .filter(|e| crate::filter::should_show(e, opts))
407 })
408 .collect()
409 };
410
411 if let Some(t0) = t_stat {
412 timing.stat_ms = t0.elapsed().as_millis();
413 }
414
415 let mut ignore_by_dir: Vec<(PathBuf, IgnoreSet)> = Vec::new();
417 let mut entries: Vec<Entry> = Vec::with_capacity(built.len().saturating_add(16));
418
419 if opts.emit_dir_headers {
420 entries.push(Entry::dir_header(path, 0));
421 }
422
423 for (w, maybe) in walked.iter().zip(built) {
424 let Some(e) = maybe else {
425 continue;
426 };
427 if ignored_by_sets(&e, opts, root_ignore.as_ref(), &mut ignore_by_dir) {
428 continue;
429 }
430 if opts.emit_dir_headers && w.is_dir {
431 entries.push(e);
433 entries.push(Entry::dir_header(&w.path, w.depth));
434 } else {
435 entries.push(e);
436 }
437 }
438
439 let t_sort = if collect_timing {
440 Some(Instant::now())
441 } else {
442 None
443 };
444
445 if opts.emit_dir_headers {
446 sort_recursive_sections(&mut entries, opts);
447 } else {
448 if !matches!(opts.sort_by, crate::options::SortBy::Name) || opts.reverse {
451 sort_tree_preorder(&mut entries, opts);
452 }
453 }
454
455 if let Some(t0) = t_sort {
456 timing.sort_ms = t0.elapsed().as_millis();
457 }
458
459 let mut listing = Listing::new(path.to_path_buf(), true, entries)
460 .with_timing(if collect_timing { Some(timing) } else { None });
461 listing.minor_errors = minor_errors;
462 Ok(listing)
463}
464
465fn sort_tree_preorder(entries: &mut [Entry], opts: &ListOptions) {
469 if entries.is_empty() {
470 return;
471 }
472 let mut i = 0;
477 while i < entries.len() {
478 let depth = entries[i].depth;
479 let parent = entries[i].path.parent().map(Path::to_path_buf);
482 let mut j = i + 1;
483 while j < entries.len() {
484 if entries[j].depth < depth {
485 break;
486 }
487 if entries[j].depth == depth {
488 let p = entries[j].path.parent().map(Path::to_path_buf);
489 if p != parent {
490 break;
491 }
492 }
493 j += 1;
494 }
495 let sib: Vec<usize> = (i..j).filter(|&k| entries[k].depth == depth).collect();
497 if sib.len() > 1 {
498 let mut blocks: Vec<Vec<Entry>> = Vec::with_capacity(sib.len());
501 for (bi, &start) in sib.iter().enumerate() {
502 let end = sib.get(bi + 1).copied().unwrap_or(j);
503 blocks.push(entries[start..end].to_vec());
504 }
505 blocks.sort_by(|a, b| crate::sort::cmp_entry(&a[0], &b[0], opts));
507 let mut out = Vec::with_capacity(j - i);
508 for b in blocks {
509 out.extend(b);
510 }
511 entries[i..j].clone_from_slice(&out);
512 }
513 i = if j > i { j } else { i + 1 };
514 }
515}
516
517fn ignored_by_sets(
519 entry: &Entry,
520 opts: &ListOptions,
521 root_ignore: Option<&IgnoreSet>,
522 cache: &mut Vec<(PathBuf, IgnoreSet)>,
523) -> bool {
524 if !opts.use_ignore_files {
525 return false;
526 }
527 if let Some(root) = root_ignore {
528 if root.ignores(entry) {
529 return true;
530 }
531 }
532 let Some(parent) = entry.path.parent() else {
533 return false;
534 };
535 if let Some(root) = root_ignore {
536 if parent == root.base {
537 return false;
538 }
539 }
540 if let Some((_, set)) = cache.iter().find(|(p, _)| p == parent) {
541 return set.ignores(entry);
542 }
543 let set = load_ignore_set(parent);
544 let ignored = set.ignores(entry);
545 cache.push((parent.to_path_buf(), set));
546 ignored
547}
548
549fn sort_recursive_sections(entries: &mut [Entry], opts: &ListOptions) {
550 let mut start = 0;
551 while start < entries.len() {
552 if entries[start].is_dir_header {
554 let section_start = start + 1;
555 let mut end = section_start;
556 while end < entries.len() && !entries[end].is_dir_header {
557 end += 1;
558 }
559 sort_entries(&mut entries[section_start..end], opts);
560 start = end;
561 } else {
562 let mut end = start;
564 while end < entries.len() && !entries[end].is_dir_header {
565 end += 1;
566 }
567 sort_entries(&mut entries[start..end], opts);
568 start = end;
569 }
570 }
571}
572
573#[derive(Debug)]
575pub struct ListOutcome {
576 pub listings: Vec<Listing>,
577 pub path_errors: Vec<Error>,
579 pub minor_errors: usize,
581}
582
583impl ListOutcome {
584 pub fn exit_code(&self) -> i32 {
586 if !self.path_errors.is_empty() {
587 2
588 } else if self.minor_errors > 0 || self.listings.iter().any(|l| l.minor_errors > 0) {
589 1
590 } else {
591 0
592 }
593 }
594
595 pub fn total_timing(&self) -> ListTiming {
597 let mut total = ListTiming::default();
598 for l in &self.listings {
599 if let Some(ref t) = l.timing {
600 total.add_assign(t);
601 }
602 }
603 total
604 }
605}
606
607pub fn list_paths(paths: &[PathBuf], opts: &ListOptions) -> Result<Vec<Listing>> {
612 let outcome = list_paths_with_errors(paths, opts);
613 if let Some(err) = outcome.path_errors.into_iter().next() {
614 return Err(err);
616 }
617 Ok(outcome.listings)
618}
619
620pub fn list_paths_with_errors(paths: &[PathBuf], opts: &ListOptions) -> ListOutcome {
622 let owned: Vec<PathBuf>;
623 let paths: &[PathBuf] = if paths.is_empty() {
624 owned = vec![PathBuf::from(".")];
625 &owned
626 } else {
627 paths
628 };
629
630 let mut listings = Vec::with_capacity(paths.len());
631 let mut path_errors = Vec::new();
632 let mut minor_errors = 0usize;
633
634 for p in paths {
635 match list_path(p, opts) {
636 Ok(l) => {
637 minor_errors += l.minor_errors;
638 listings.push(l);
639 }
640 Err(e) => path_errors.push(e),
641 }
642 }
643
644 ListOutcome {
645 listings,
646 path_errors,
647 minor_errors,
648 }
649}
650
651#[cfg(test)]
652mod tests {
653 use super::*;
654 use std::fs;
655
656 fn temp_dir() -> PathBuf {
657 use std::sync::atomic::{AtomicU64, Ordering};
658 static N: AtomicU64 = AtomicU64::new(0);
659 let base = std::env::temp_dir().join(format!(
660 "f00-core-list-{}-{}-{}",
661 std::process::id(),
662 std::time::SystemTime::now()
663 .duration_since(std::time::UNIX_EPOCH)
664 .map(|d| d.as_nanos())
665 .unwrap_or(0),
666 N.fetch_add(1, Ordering::Relaxed)
667 ));
668 fs::create_dir_all(&base).unwrap();
669 base
670 }
671
672 #[test]
673 fn list_paths_with_errors_partial_success() {
674 let dir = temp_dir();
675 fs::write(dir.join("a.txt"), b"x").unwrap();
676 let missing = dir.join("gone");
677 let opts = ListOptions::default();
678 let outcome = list_paths_with_errors(&[dir.clone(), missing], &opts);
679 assert_eq!(outcome.listings.len(), 1);
680 assert_eq!(outcome.path_errors.len(), 1);
681 assert_eq!(outcome.exit_code(), 2);
682 let _ = fs::remove_dir_all(&dir);
683 }
684
685 #[test]
686 fn list_paths_ok_exit_0() {
687 let dir = temp_dir();
688 fs::write(dir.join("a.txt"), b"x").unwrap();
689 let opts = ListOptions::default();
690 let outcome = list_paths_with_errors(std::slice::from_ref(&dir), &opts);
691 assert!(outcome.path_errors.is_empty());
692 assert_eq!(outcome.exit_code(), 0);
693 let _ = fs::remove_dir_all(&dir);
694 }
695
696 #[test]
697 fn list_directory_honors_ignore_files() {
698 let dir = temp_dir();
699 fs::write(dir.join("keep.txt"), b"k").unwrap();
700 fs::write(dir.join("skip.o"), b"o").unwrap();
701 fs::write(dir.join(".gitignore"), "*.o\n").unwrap();
702
703 let opts = ListOptions {
704 use_ignore_files: true,
705 ..Default::default()
706 };
707 let listing = list_directory(&dir, &opts).unwrap();
708 let names: Vec<_> = listing.entries.iter().map(|e| e.name.as_str()).collect();
709 assert!(names.contains(&"keep.txt"));
710 assert!(!names.contains(&"skip.o"));
711
712 let opts_off = ListOptions {
713 use_ignore_files: false,
714 ..Default::default()
715 };
716 let listing = list_directory(&dir, &opts_off).unwrap();
717 let names: Vec<_> = listing.entries.iter().map(|e| e.name.as_str()).collect();
718 assert!(names.contains(&"skip.o"));
719
720 let _ = fs::remove_dir_all(&dir);
721 }
722
723 #[test]
724 fn parallel_list_same_names_as_sequential() {
725 let dir = temp_dir();
726 let mut expected = Vec::new();
728 for i in 0..64 {
729 let name = format!("file_{i:03}.txt");
730 fs::write(dir.join(&name), b"x").unwrap();
731 expected.push(name);
732 }
733 fs::create_dir(dir.join("subdir")).unwrap();
734 expected.push("subdir".into());
735 expected.sort();
736
737 let sequential = ListOptions {
738 parallel: false,
739 threads: 1,
740 ..Default::default()
741 };
742 let seq = list_directory(&dir, &sequential).unwrap();
743 let mut seq_names: Vec<_> = seq.entries.iter().map(|e| e.name.clone()).collect();
744 seq_names.sort();
745 assert_eq!(
746 seq_names, expected,
747 "listing must include every created entry"
748 );
749
750 if !cfg!(target_os = "freebsd") {
752 let parallel = ListOptions {
753 parallel: true,
754 threads: 0,
755 ..Default::default()
756 };
757 let par = list_directory(&dir, ¶llel).unwrap();
758 let mut par_names: Vec<_> = par.entries.iter().map(|e| e.name.clone()).collect();
759 par_names.sort();
760 assert_eq!(
761 seq_names, par_names,
762 "parallel and sequential must produce identical ordered names"
763 );
764 }
765
766 let _ = fs::remove_dir_all(&dir);
767 }
768
769 #[test]
770 fn collect_timing_fills_phases() {
771 let dir = temp_dir();
772 for i in 0..8 {
773 fs::write(dir.join(format!("f{i}")), b"x").unwrap();
774 }
775 let opts = ListOptions {
776 collect_timing: true,
777 parallel: false,
778 threads: 1,
779 ..Default::default()
780 };
781 let listing = list_directory(&dir, &opts).unwrap();
782 let t = listing.timing.expect("timing present");
783 let _ = (t.readdir_ms, t.stat_ms, t.sort_ms);
785 let _ = fs::remove_dir_all(&dir);
786 }
787
788 #[test]
789 fn threads_one_forces_serial_path() {
790 let dir = temp_dir();
791 for i in 0..40 {
792 fs::write(dir.join(format!("n{i}")), b"x").unwrap();
793 }
794 let opts = ListOptions {
795 parallel: true,
796 threads: 1,
797 ..Default::default()
798 };
799 assert!(!opts.use_parallel_stat(40));
800 let listing = list_directory(&dir, &opts).unwrap();
801 assert_eq!(listing.entries.len(), 40);
802 let _ = fs::remove_dir_all(&dir);
803 }
804}