Skip to main content

coreutils_rs/du/
core.rs

1use std::collections::HashSet;
2use std::io::{self, BufRead, Write};
3use std::os::unix::fs::MetadataExt;
4use std::path::{Path, PathBuf};
5use std::time::SystemTime;
6
7/// Configuration for the `du` command.
8pub struct DuConfig {
9    /// Show counts for all files, not just directories.
10    pub all: bool,
11    /// Print apparent sizes rather than disk usage.
12    pub apparent_size: bool,
13    /// Block size for output scaling.
14    pub block_size: u64,
15    /// Human-readable output (powers of 1024).
16    pub human_readable: bool,
17    /// Human-readable output (powers of 1000).
18    pub si: bool,
19    /// Produce a grand total.
20    pub total: bool,
21    /// Maximum depth of directory traversal to display.
22    pub max_depth: Option<usize>,
23    /// Only display a total for each argument.
24    pub summarize: bool,
25    /// Stay on the same filesystem.
26    pub one_file_system: bool,
27    /// Dereference all symbolic links.
28    pub dereference: bool,
29    /// Dereference only command-line symlink arguments (-D / -H / --dereference-args).
30    pub dereference_args: bool,
31    /// For directories, do not include size of subdirectories.
32    pub separate_dirs: bool,
33    /// Count sizes of hard-linked files multiple times.
34    pub count_links: bool,
35    /// End output lines with NUL instead of newline.
36    pub null_terminator: bool,
37    /// Exclude entries smaller (or larger if negative) than this threshold.
38    pub threshold: Option<i64>,
39    /// Show modification time of entries.
40    pub show_time: bool,
41    /// Time format style (full-iso, long-iso, iso).
42    pub time_style: String,
43    /// Glob patterns to exclude.
44    pub exclude_patterns: Vec<String>,
45    /// Count inodes instead of sizes.
46    pub inodes: bool,
47}
48
49impl Default for DuConfig {
50    fn default() -> Self {
51        DuConfig {
52            all: false,
53            apparent_size: false,
54            block_size: 1024,
55            human_readable: false,
56            si: false,
57            total: false,
58            max_depth: None,
59            summarize: false,
60            one_file_system: false,
61            dereference: false,
62            dereference_args: false,
63            separate_dirs: false,
64            count_links: false,
65            null_terminator: false,
66            threshold: None,
67            show_time: false,
68            time_style: "long-iso".to_string(),
69            exclude_patterns: Vec::new(),
70            inodes: false,
71        }
72    }
73}
74
75/// A single entry produced by `du` traversal.
76pub struct DuEntry {
77    /// Size in bytes (or inode count if inodes mode).
78    pub size: u64,
79    /// Path of the entry.
80    pub path: PathBuf,
81    /// Modification time (seconds since epoch), if available.
82    pub mtime: Option<i64>,
83}
84
85/// Traverse `path` and collect `DuEntry` results according to `config`.
86pub fn du_path(path: &Path, config: &DuConfig) -> io::Result<Vec<DuEntry>> {
87    let mut seen_inodes: HashSet<(u64, u64)> = HashSet::new();
88    let mut had_error = false;
89    du_path_with_seen(path, config, &mut seen_inodes, &mut had_error)
90}
91
92/// Traverse `path` with a shared inode set (for deduplication across multiple arguments).
93/// Sets `had_error` to true if any permission or access errors are encountered.
94pub fn du_path_with_seen(
95    path: &Path,
96    config: &DuConfig,
97    seen_inodes: &mut HashSet<(u64, u64)>,
98    had_error: &mut bool,
99) -> io::Result<Vec<DuEntry>> {
100    let mut entries = Vec::new();
101    du_recursive(path, config, seen_inodes, &mut entries, 0, None, had_error)?;
102    Ok(entries)
103}
104
105/// Check whether a path should be excluded by any of the exclude patterns.
106/// GNU du matches the pattern against the basename and the full path.
107fn is_excluded(path: &Path, config: &DuConfig) -> bool {
108    if config.exclude_patterns.is_empty() {
109        return false;
110    }
111    let path_str = path.to_string_lossy();
112    let basename = path
113        .file_name()
114        .map(|n| n.to_string_lossy())
115        .unwrap_or_default();
116    config
117        .exclude_patterns
118        .iter()
119        .any(|pat| glob_match(pat, &basename) || glob_match(pat, &path_str))
120}
121
122/// Recursive traversal core. Returns the cumulative size of the subtree at `path`.
123fn du_recursive(
124    path: &Path,
125    config: &DuConfig,
126    seen: &mut HashSet<(u64, u64)>,
127    entries: &mut Vec<DuEntry>,
128    depth: usize,
129    root_dev: Option<u64>,
130    had_error: &mut bool,
131) -> io::Result<u64> {
132    // Check exclude patterns against this path (GNU du applies exclude to all entries
133    // including the root argument itself).
134    if is_excluded(path, config) {
135        return Ok(0);
136    }
137
138    // For depth 0 (command-line arguments), dereference_args means follow symlinks.
139    let meta = if config.dereference || (depth == 0 && config.dereference_args) {
140        std::fs::metadata(path)?
141    } else {
142        std::fs::symlink_metadata(path)?
143    };
144
145    // Check one-file-system: skip entries on different devices.
146    if let Some(dev) = root_dev {
147        if meta.dev() != dev && config.one_file_system {
148            return Ok(0);
149        }
150    }
151
152    // Track hard links: skip files we have already counted (unless --count-links).
153    let ino_key = (meta.dev(), meta.ino());
154    if meta.nlink() > 1 && !config.count_links {
155        if !seen.insert(ino_key) {
156            return Ok(0);
157        }
158    }
159
160    let size = if config.inodes {
161        1
162    } else if config.apparent_size {
163        // GNU du uses 0 for directory entries themselves in apparent-size mode;
164        // only file content sizes are counted.
165        if meta.is_dir() { 0 } else { meta.len() }
166    } else {
167        meta.blocks() * 512
168    };
169
170    let mtime = meta.mtime();
171
172    if meta.is_dir() {
173        // Track the full subtree size (for returning to parent)
174        // and the display size (what we show for this directory).
175        let mut subtree_size: u64 = size;
176        // For separate_dirs, display size only includes this dir + direct files, not subdirs.
177        let mut display_size: u64 = size;
178
179        let read_dir = match std::fs::read_dir(path) {
180            Ok(rd) => rd,
181            Err(e) => {
182                eprintln!(
183                    "du: cannot read directory '{}': {}",
184                    path.display(),
185                    format_io_error(&e)
186                );
187                *had_error = true;
188                // Still report what we can for this directory.
189                if should_report_dir(config, depth) {
190                    entries.push(DuEntry {
191                        size,
192                        path: path.to_path_buf(),
193                        mtime: if config.show_time { Some(mtime) } else { None },
194                    });
195                }
196                return Ok(size);
197            }
198        };
199
200        for entry in read_dir {
201            let entry = match entry {
202                Ok(e) => e,
203                Err(e) => {
204                    eprintln!(
205                        "du: cannot access entry in '{}': {}",
206                        path.display(),
207                        format_io_error(&e)
208                    );
209                    *had_error = true;
210                    continue;
211                }
212            };
213            let child_path = entry.path();
214
215            // Check exclude patterns against both basename and full path (GNU compat).
216            if is_excluded(&child_path, config) {
217                continue;
218            }
219
220            // Check if child is a directory (for separate_dirs logic).
221            let child_is_dir = child_path.symlink_metadata().map_or(false, |m| m.is_dir());
222
223            let child_size = du_recursive(
224                &child_path,
225                config,
226                seen,
227                entries,
228                depth + 1,
229                Some(root_dev.unwrap_or(meta.dev())),
230                had_error,
231            )?;
232            subtree_size += child_size;
233            if config.separate_dirs && child_is_dir {
234                // Don't add subdirectory sizes to display size.
235            } else {
236                display_size += child_size;
237            }
238        }
239
240        // Emit an entry for this directory if within display depth.
241        if should_report_dir(config, depth) {
242            entries.push(DuEntry {
243                size: display_size,
244                path: path.to_path_buf(),
245                mtime: if config.show_time { Some(mtime) } else { None },
246            });
247        }
248
249        Ok(subtree_size)
250    } else {
251        // Regular file / symlink / special file.
252        // Always report top-level arguments (depth 0), or all files if --all.
253        if (depth == 0 || config.all) && within_depth(config, depth) {
254            entries.push(DuEntry {
255                size,
256                path: path.to_path_buf(),
257                mtime: if config.show_time { Some(mtime) } else { None },
258            });
259        }
260        Ok(size)
261    }
262}
263
264/// Whether a directory entry at `depth` should be reported.
265fn should_report_dir(config: &DuConfig, depth: usize) -> bool {
266    if config.summarize {
267        return depth == 0;
268    }
269    within_depth(config, depth)
270}
271
272/// Whether `depth` is within the configured max_depth.
273fn within_depth(config: &DuConfig, depth: usize) -> bool {
274    match config.max_depth {
275        Some(max) => depth <= max,
276        None => true,
277    }
278}
279
280/// Glob matching supporting `*`, `?`, and `[...]`/`[^...]` character classes.
281/// Compatible with fnmatch(3) FNM_PATHNAME-less matching used by GNU du.
282pub fn glob_match(pattern: &str, text: &str) -> bool {
283    let pat: Vec<char> = pattern.chars().collect();
284    let txt: Vec<char> = text.chars().collect();
285    glob_match_inner(&pat, &txt)
286}
287
288/// Try to match a `[...]` or `[^...]` bracket expression starting at `pat[start]` (which is `[`).
289/// Returns `Some((matched_char, end_index))` where `end_index` is the index after `]`,
290/// or `None` if the bracket expression is malformed.
291fn match_bracket_class(pat: &[char], start: usize, ch: char) -> Option<(bool, usize)> {
292    let mut i = start + 1; // skip the opening `[`
293    if i >= pat.len() {
294        return None;
295    }
296
297    // Check for negation: `[^...]` or `[!...]`
298    let negate = if pat[i] == '^' || pat[i] == '!' {
299        i += 1;
300        true
301    } else {
302        false
303    };
304
305    // A `]` immediately after `[` (or `[^`) is treated as a literal character in the class.
306    let mut found = false;
307    let mut first = true;
308    while i < pat.len() {
309        if pat[i] == ']' && !first {
310            // End of bracket expression.
311            let matched = if negate { !found } else { found };
312            return Some((matched, i + 1));
313        }
314        // Check for range: a-z
315        if i + 2 < pat.len() && pat[i + 1] == '-' && pat[i + 2] != ']' {
316            let lo = pat[i];
317            let hi = pat[i + 2];
318            if ch >= lo && ch <= hi {
319                found = true;
320            }
321            i += 3;
322        } else {
323            if pat[i] == ch {
324                found = true;
325            }
326            i += 1;
327        }
328        first = false;
329    }
330
331    // No closing `]` found — malformed bracket expression.
332    None
333}
334
335fn glob_match_inner(pat: &[char], txt: &[char]) -> bool {
336    let mut pi = 0;
337    let mut ti = 0;
338    let mut star_pi = usize::MAX;
339    let mut star_ti = 0;
340
341    while ti < txt.len() {
342        if pi < pat.len() && pat[pi] == '[' {
343            // Try to match a bracket expression.
344            if let Some((matched, end)) = match_bracket_class(pat, pi, txt[ti]) {
345                if matched {
346                    pi = end;
347                    ti += 1;
348                    continue;
349                }
350                // Not matched — fall through to star backtrack.
351            }
352            // Malformed bracket or no match — try star backtrack.
353            if star_pi != usize::MAX {
354                pi = star_pi + 1;
355                star_ti += 1;
356                ti = star_ti;
357            } else {
358                return false;
359            }
360        } else if pi < pat.len() && (pat[pi] == '?' || pat[pi] == txt[ti]) {
361            pi += 1;
362            ti += 1;
363        } else if pi < pat.len() && pat[pi] == '*' {
364            star_pi = pi;
365            star_ti = ti;
366            pi += 1;
367        } else if star_pi != usize::MAX {
368            pi = star_pi + 1;
369            star_ti += 1;
370            ti = star_ti;
371        } else {
372            return false;
373        }
374    }
375
376    while pi < pat.len() && pat[pi] == '*' {
377        pi += 1;
378    }
379    pi == pat.len()
380}
381
382/// Format a size value for display according to the config.
383pub fn format_size(raw_bytes: u64, config: &DuConfig) -> String {
384    if config.human_readable {
385        human_readable(raw_bytes, 1024)
386    } else if config.si {
387        human_readable(raw_bytes, 1000)
388    } else if config.inodes {
389        raw_bytes.to_string()
390    } else {
391        // Scale by block_size, rounding up.
392        let scaled = (raw_bytes + config.block_size - 1) / config.block_size;
393        scaled.to_string()
394    }
395}
396
397/// Format a byte count in human-readable form (e.g., 1.5K, 23M).
398/// GNU du uses ceiling rounding and always shows one decimal for values < 10.
399fn human_readable(bytes: u64, base: u64) -> String {
400    let suffixes = if base == 1024 {
401        &["", "K", "M", "G", "T", "P", "E"]
402    } else {
403        &["", "k", "M", "G", "T", "P", "E"]
404    };
405
406    if bytes < base {
407        return format!("{}", bytes);
408    }
409
410    let mut value = bytes as f64;
411    let mut idx = 0;
412    while value >= base as f64 && idx + 1 < suffixes.len() {
413        value /= base as f64;
414        idx += 1;
415    }
416
417    if value >= 10.0 {
418        format!("{:.0}{}", value.ceil(), suffixes[idx])
419    } else {
420        // Show one decimal place for values < 10 (GNU keeps the .0).
421        let rounded = (value * 10.0).ceil() / 10.0;
422        if rounded >= 10.0 {
423            format!("{:.0}{}", rounded.ceil(), suffixes[idx])
424        } else {
425            format!("{:.1}{}", rounded, suffixes[idx])
426        }
427    }
428}
429
430/// Format a modification time for display.
431pub fn format_time(epoch_secs: i64, style: &str) -> String {
432    // Convert epoch seconds to a broken-down time.
433    let secs = epoch_secs;
434    let st = match SystemTime::UNIX_EPOCH.checked_add(std::time::Duration::from_secs(secs as u64)) {
435        Some(t) => t,
436        None => return String::from("?"),
437    };
438
439    // Use libc localtime_r for correct timezone handling.
440    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
441    let time_t = secs as libc::time_t;
442    unsafe {
443        libc::localtime_r(&time_t, &mut tm);
444    }
445    // Ignore the SystemTime; we use the libc tm directly.
446    let _ = st;
447
448    let year = tm.tm_year + 1900;
449    let mon = tm.tm_mon + 1;
450    let day = tm.tm_mday;
451    let hour = tm.tm_hour;
452    let min = tm.tm_min;
453    let sec = tm.tm_sec;
454
455    match style {
456        "full-iso" => format!(
457            "{:04}-{:02}-{:02} {:02}:{:02}:{:02}.000000000 +0000",
458            year, mon, day, hour, min, sec
459        ),
460        "iso" => format!("{:04}-{:02}-{:02}", year, mon, day),
461        _ => {
462            // long-iso (default)
463            format!("{:04}-{:02}-{:02} {:02}:{:02}", year, mon, day, hour, min)
464        }
465    }
466}
467
468/// Print a single DuEntry.
469pub fn print_entry<W: Write>(out: &mut W, entry: &DuEntry, config: &DuConfig) -> io::Result<()> {
470    // Apply threshold filtering.
471    if let Some(thresh) = config.threshold {
472        let size_signed = entry.size as i64;
473        if thresh >= 0 && size_signed < thresh {
474            return Ok(());
475        }
476        if thresh < 0 && size_signed > thresh.unsigned_abs() as i64 {
477            return Ok(());
478        }
479    }
480
481    let size_str = format_size(entry.size, config);
482
483    if config.show_time {
484        if let Some(mtime) = entry.mtime {
485            let time_str = format_time(mtime, &config.time_style);
486            write!(out, "{}\t{}\t{}", size_str, time_str, entry.path.display())?;
487        } else {
488            write!(out, "{}\t{}", size_str, entry.path.display())?;
489        }
490    } else {
491        write!(out, "{}\t{}", size_str, entry.path.display())?;
492    }
493
494    if config.null_terminator {
495        out.write_all(b"\0")?;
496    } else {
497        out.write_all(b"\n")?;
498    }
499
500    Ok(())
501}
502
503/// Parse a block size string like "1K", "1M", "1G", etc.
504/// Returns the number of bytes per block.
505pub fn parse_block_size(s: &str) -> Result<u64, String> {
506    let s = s.trim();
507    if s.is_empty() {
508        return Err("empty block size".to_string());
509    }
510
511    let mut num_end = 0;
512    for (i, c) in s.char_indices() {
513        if c.is_ascii_digit() {
514            num_end = i + 1;
515        } else {
516            break;
517        }
518    }
519
520    let (num_str, suffix) = s.split_at(num_end);
521    let base_val: u64 = if num_str.is_empty() {
522        1
523    } else {
524        num_str
525            .parse()
526            .map_err(|_| format!("invalid block size: '{}'", s))?
527    };
528
529    let multiplier = match suffix.to_uppercase().as_str() {
530        "" => 1u64,
531        "B" => 1,
532        "K" | "KB" => 1024,
533        "M" | "MB" => 1024 * 1024,
534        "G" | "GB" => 1024 * 1024 * 1024,
535        "T" | "TB" => 1024u64 * 1024 * 1024 * 1024,
536        "P" | "PB" => 1024u64 * 1024 * 1024 * 1024 * 1024,
537        "KB_SI" => 1000,
538        _ => return Err(format!("invalid suffix in block size: '{}'", s)),
539    };
540
541    Ok(base_val * multiplier)
542}
543
544/// Parse a threshold value. Positive means "exclude entries smaller than SIZE".
545/// Negative means "exclude entries larger than -SIZE".
546/// GNU du rejects `--threshold=-0` and `--threshold=0` is allowed (positive zero is fine,
547/// but negative zero is invalid).
548pub fn parse_threshold(s: &str) -> Result<i64, String> {
549    let s = s.trim();
550    let (negative, rest) = if let Some(stripped) = s.strip_prefix('-') {
551        (true, stripped)
552    } else {
553        (false, s)
554    };
555
556    let val = parse_block_size(rest)? as i64;
557    if negative {
558        if val == 0 {
559            return Err(format!("invalid --threshold argument '-{}'", rest));
560        }
561        Ok(-val)
562    } else {
563        Ok(val)
564    }
565}
566
567/// Read exclude patterns from a file (one per line).
568pub fn read_exclude_file(path: &str) -> io::Result<Vec<String>> {
569    let file = std::fs::File::open(path)?;
570    let reader = io::BufReader::new(file);
571    let mut patterns = Vec::new();
572    for line in reader.lines() {
573        let line = line?;
574        let trimmed = line.trim();
575        if !trimmed.is_empty() {
576            patterns.push(trimmed.to_string());
577        }
578    }
579    Ok(patterns)
580}
581
582/// Format an IO error without the "(os error N)" suffix.
583fn format_io_error(e: &io::Error) -> String {
584    if let Some(raw) = e.raw_os_error() {
585        let os_err = io::Error::from_raw_os_error(raw);
586        let msg = format!("{}", os_err);
587        msg.replace(&format!(" (os error {})", raw), "")
588    } else {
589        format!("{}", e)
590    }
591}