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
7pub struct DuConfig {
9 pub all: bool,
11 pub apparent_size: bool,
13 pub block_size: u64,
15 pub human_readable: bool,
17 pub si: bool,
19 pub total: bool,
21 pub max_depth: Option<usize>,
23 pub summarize: bool,
25 pub one_file_system: bool,
27 pub dereference: bool,
29 pub dereference_args: bool,
31 pub separate_dirs: bool,
33 pub count_links: bool,
35 pub null_terminator: bool,
37 pub threshold: Option<i64>,
39 pub show_time: bool,
41 pub time_style: String,
43 pub exclude_patterns: Vec<String>,
45 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
75pub struct DuEntry {
77 pub size: u64,
79 pub path: PathBuf,
81 pub mtime: Option<i64>,
83}
84
85pub 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
92pub 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
105fn 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
122fn 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 if is_excluded(path, config) {
135 return Ok(0);
136 }
137
138 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 if let Some(dev) = root_dev {
147 if meta.dev() != dev && config.one_file_system {
148 return Ok(0);
149 }
150 }
151
152 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 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 let mut subtree_size: u64 = size;
176 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 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 if is_excluded(&child_path, config) {
217 continue;
218 }
219
220 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 } else {
236 display_size += child_size;
237 }
238 }
239
240 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 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
264fn should_report_dir(config: &DuConfig, depth: usize) -> bool {
266 if config.summarize {
267 return depth == 0;
268 }
269 within_depth(config, depth)
270}
271
272fn within_depth(config: &DuConfig, depth: usize) -> bool {
274 match config.max_depth {
275 Some(max) => depth <= max,
276 None => true,
277 }
278}
279
280pub 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
288fn match_bracket_class(pat: &[char], start: usize, ch: char) -> Option<(bool, usize)> {
292 let mut i = start + 1; if i >= pat.len() {
294 return None;
295 }
296
297 let negate = if pat[i] == '^' || pat[i] == '!' {
299 i += 1;
300 true
301 } else {
302 false
303 };
304
305 let mut found = false;
307 let mut first = true;
308 while i < pat.len() {
309 if pat[i] == ']' && !first {
310 let matched = if negate { !found } else { found };
312 return Some((matched, i + 1));
313 }
314 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 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 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 }
352 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
382pub 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 let scaled = (raw_bytes + config.block_size - 1) / config.block_size;
393 scaled.to_string()
394 }
395}
396
397fn 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 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
430pub fn format_time(epoch_secs: i64, style: &str) -> String {
432 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 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 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 format!("{:04}-{:02}-{:02} {:02}:{:02}", year, mon, day, hour, min)
464 }
465 }
466}
467
468pub fn print_entry<W: Write>(out: &mut W, entry: &DuEntry, config: &DuConfig) -> io::Result<()> {
470 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
503pub 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
544pub 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
567pub 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
582fn 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}