fcoreutils 0.22.0

High-performance GNU coreutils replacement with SIMD and parallelism
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#[cfg(not(unix))]
fn main() {
    eprintln!("du: only available on Unix");
    std::process::exit(1);
}

#[cfg(unix)]
use std::io::{self, BufWriter, Write};
#[cfg(unix)]
use std::process;

#[cfg(unix)]
use coreutils_rs::du::{
    DuConfig, DuEntry, du_path_with_seen, parse_block_size, parse_threshold, print_entry,
    read_exclude_file,
};

#[cfg(unix)]
const TOOL_NAME: &str = "du";

#[cfg(unix)]
fn usage() {
    eprintln!(
        "Usage: {} [OPTION]... [FILE]...
  or:  {} [OPTION]... --files0-from=F
Summarize device usage of the set of FILEs, recursively for directories.

  -0, --null            end each output line with NUL, not newline
  -a, --all             write counts for all files, not just directories
      --apparent-size   print apparent sizes rather than device usage
  -B, --block-size=SIZE scale sizes by SIZE before printing them
  -b, --bytes           equivalent to --apparent-size --block-size=1
  -c, --total           produce a grand total
  -D, -H, --dereference-args  dereference only symlinks that are listed on the
                        command line
  -d, --max-depth=N     print the total for a directory only if it is N or
                        fewer levels below the command line argument
      --exclude=PATTERN exclude files that match PATTERN
  -h, --human-readable  print sizes in human readable format (e.g., 1K 234M 2G)
      --inodes          list inode usage information instead of block usage
  -k                    like --block-size=1K
  -L, --dereference     dereference all symbolic links
  -l, --count-links     count sizes many times if hard linked
  -m                    like --block-size=1M
  -P, --no-dereference  don't follow any symbolic links (this is the default)
  -S, --separate-dirs   for directories do not include size of subdirectories
      --si              like -h, but use powers of 1000 not 1024
  -s, --summarize       display only a total for each argument
  -t, --threshold=SIZE  exclude entries smaller than SIZE if positive,
                        or entries greater than SIZE if negative
      --time            show time of the last modification of any file in the
                        directory, or any of its subdirectories
      --time-style=STYLE show times using STYLE: full-iso, long-iso, iso
  -X, --exclude-from=FILE  exclude files that match any pattern in FILE
  -x, --one-file-system    skip directories on different file systems
      --help            display this help and exit
      --version         output version information and exit",
        TOOL_NAME, TOOL_NAME
    );
}

#[cfg(unix)]
fn version() {
    eprintln!("{} (fcoreutils) {}", TOOL_NAME, env!("CARGO_PKG_VERSION"));
}

/// Parse command-line arguments manually (matching the project's style for sort, touch, etc.).
#[cfg(unix)]
fn parse_args() -> (DuConfig, Vec<String>) {
    let mut config = DuConfig::default();
    let mut files = Vec::new();

    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];

        if arg == "--" {
            // Everything after -- is a file argument.
            files.extend_from_slice(&args[i + 1..]);
            break;
        }

        if arg.starts_with("--") {
            // Long options.
            if arg == "--help" {
                usage();
                process::exit(0);
            } else if arg == "--version" {
                version();
                process::exit(0);
            } else if arg == "--null" {
                config.null_terminator = true;
            } else if arg == "--all" {
                config.all = true;
            } else if arg == "--apparent-size" {
                config.apparent_size = true;
            } else if arg == "--bytes" {
                config.apparent_size = true;
                config.block_size = 1;
            } else if arg == "--total" {
                config.total = true;
            } else if arg == "--summarize" {
                config.summarize = true;
            } else if arg == "--human-readable" {
                config.human_readable = true;
            } else if arg == "--si" {
                config.si = true;
            } else if arg == "--inodes" {
                config.inodes = true;
            } else if arg == "--dereference" {
                config.dereference = true;
            } else if arg == "--dereference-args" {
                config.dereference_args = true;
            } else if arg == "--no-dereference" {
                config.dereference = false;
            } else if arg == "--count-links" {
                config.count_links = true;
            } else if arg == "--separate-dirs" {
                config.separate_dirs = true;
            } else if arg == "--one-file-system" {
                config.one_file_system = true;
            } else if arg == "--time" {
                config.show_time = true;
            } else if let Some(val) = arg.strip_prefix("--block-size=") {
                match parse_block_size(val) {
                    Ok(bs) => config.block_size = bs,
                    Err(e) => {
                        eprintln!("{}: {}", TOOL_NAME, e);
                        process::exit(1);
                    }
                }
            } else if let Some(val) = arg.strip_prefix("--max-depth=") {
                match val.parse::<usize>() {
                    Ok(d) => config.max_depth = Some(d),
                    Err(_) => {
                        eprintln!("{}: invalid maximum depth '{}'", TOOL_NAME, val);
                        process::exit(1);
                    }
                }
            } else if let Some(val) = arg.strip_prefix("--threshold=") {
                match parse_threshold(val) {
                    Ok(t) => config.threshold = Some(t),
                    Err(e) => {
                        eprintln!("{}: {}", TOOL_NAME, e);
                        process::exit(1);
                    }
                }
            } else if let Some(val) = arg.strip_prefix("--exclude=") {
                config.exclude_patterns.push(val.to_string());
            } else if let Some(val) = arg.strip_prefix("--exclude-from=") {
                match read_exclude_file(val) {
                    Ok(pats) => config.exclude_patterns.extend(pats),
                    Err(e) => {
                        eprintln!("{}: cannot read '{}': {}", TOOL_NAME, val, e);
                        process::exit(1);
                    }
                }
            } else if let Some(val) = arg.strip_prefix("--time-style=") {
                config.time_style = val.to_string();
            } else if let Some(val) = arg.strip_prefix("--time=") {
                // --time=WORD: we accept it and enable time display.
                let _ = val; // currently we only show mtime
                config.show_time = true;
            } else {
                eprintln!("{}: unrecognized option '{}'", TOOL_NAME, arg);
                eprintln!("Try '{} --help' for more information.", TOOL_NAME);
                process::exit(1);
            }
        } else if arg.starts_with('-') && arg.len() > 1 {
            // Short options (can be combined, e.g., -shc).
            let chars: Vec<char> = arg[1..].chars().collect();
            let mut j = 0;
            while j < chars.len() {
                match chars[j] {
                    '0' => config.null_terminator = true,
                    'a' => config.all = true,
                    'b' => {
                        config.apparent_size = true;
                        config.block_size = 1;
                    }
                    'c' => config.total = true,
                    'h' => config.human_readable = true,
                    'k' => config.block_size = 1024,
                    'l' => config.count_links = true,
                    'm' => config.block_size = 1024 * 1024,
                    'D' | 'H' => config.dereference_args = true,
                    'L' => config.dereference = true,
                    'P' => config.dereference = false,
                    'S' => config.separate_dirs = true,
                    // Note: GNU du does not have -A as short for --apparent-size
                    's' => config.summarize = true,
                    'x' => config.one_file_system = true,
                    'd' => {
                        // -d N (next chars or next arg)
                        let rest: String = chars[j + 1..].iter().collect();
                        let val_str = if rest.is_empty() {
                            i += 1;
                            if i >= args.len() {
                                eprintln!("{}: option requires an argument -- 'd'", TOOL_NAME);
                                process::exit(1);
                            }
                            args[i].clone()
                        } else {
                            j = chars.len(); // consume rest
                            rest
                        };
                        match val_str.parse::<usize>() {
                            Ok(d) => config.max_depth = Some(d),
                            Err(_) => {
                                eprintln!("{}: invalid maximum depth '{}'", TOOL_NAME, val_str);
                                process::exit(1);
                            }
                        }
                    }
                    'B' => {
                        let rest: String = chars[j + 1..].iter().collect();
                        let val_str = if rest.is_empty() {
                            i += 1;
                            if i >= args.len() {
                                eprintln!("{}: option requires an argument -- 'B'", TOOL_NAME);
                                process::exit(1);
                            }
                            args[i].clone()
                        } else {
                            j = chars.len();
                            rest
                        };
                        match parse_block_size(&val_str) {
                            Ok(bs) => config.block_size = bs,
                            Err(e) => {
                                eprintln!("{}: {}", TOOL_NAME, e);
                                process::exit(1);
                            }
                        }
                    }
                    't' => {
                        let rest: String = chars[j + 1..].iter().collect();
                        let val_str = if rest.is_empty() {
                            i += 1;
                            if i >= args.len() {
                                eprintln!("{}: option requires an argument -- 't'", TOOL_NAME);
                                process::exit(1);
                            }
                            args[i].clone()
                        } else {
                            j = chars.len();
                            rest
                        };
                        match parse_threshold(&val_str) {
                            Ok(t) => config.threshold = Some(t),
                            Err(e) => {
                                eprintln!("{}: {}", TOOL_NAME, e);
                                process::exit(1);
                            }
                        }
                    }
                    'X' => {
                        let rest: String = chars[j + 1..].iter().collect();
                        let val_str = if rest.is_empty() {
                            i += 1;
                            if i >= args.len() {
                                eprintln!("{}: option requires an argument -- 'X'", TOOL_NAME);
                                process::exit(1);
                            }
                            args[i].clone()
                        } else {
                            j = chars.len();
                            rest
                        };
                        match read_exclude_file(&val_str) {
                            Ok(pats) => config.exclude_patterns.extend(pats),
                            Err(e) => {
                                eprintln!("{}: cannot read '{}': {}", TOOL_NAME, val_str, e);
                                process::exit(1);
                            }
                        }
                    }
                    _ => {
                        eprintln!("{}: invalid option -- '{}'", TOOL_NAME, chars[j]);
                        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
                        process::exit(1);
                    }
                }
                j += 1;
            }
        } else {
            // Positional argument (file path).
            files.push(arg.clone());
        }

        i += 1;
    }

    // Default to current directory if no files specified.
    if files.is_empty() {
        files.push(".".to_string());
    }

    (config, files)
}

#[cfg(unix)]
fn main() {
    coreutils_rs::common::reset_sigpipe();

    let (config, files) = parse_args();

    let stdout = io::stdout();
    let mut out = BufWriter::with_capacity(256 * 1024, stdout.lock());
    let mut had_error = false;
    let mut grand_total: u64 = 0;
    let mut seen_inodes = std::collections::HashSet::new();

    for file in &files {
        let path = std::path::Path::new(file);
        match du_path_with_seen(path, &config, &mut seen_inodes, &mut had_error) {
            Ok(entries) => {
                for entry in &entries {
                    if let Err(e) = print_entry(&mut out, entry, &config) {
                        eprintln!("{}: write error: {}", TOOL_NAME, e);
                        process::exit(1);
                    }
                }
                // The last entry for a path is the root's total.
                if let Some(last) = entries.last() {
                    grand_total += last.size;
                }
            }
            Err(e) => {
                eprintln!(
                    "{}: cannot access '{}': {}",
                    TOOL_NAME,
                    file,
                    format_io_error(&e)
                );
                had_error = true;
            }
        }
    }

    // Print grand total if requested.
    if config.total {
        let total_entry = DuEntry {
            size: grand_total,
            path: std::path::PathBuf::from("total"),
            mtime: None,
        };
        if let Err(e) = print_entry(&mut out, &total_entry, &config) {
            eprintln!("{}: write error: {}", TOOL_NAME, e);
            process::exit(1);
        }
    }

    let _ = out.flush();

    if had_error {
        process::exit(1);
    }
}

/// Format an IO error without the "(os error N)" suffix.
#[cfg(unix)]
fn format_io_error(e: &io::Error) -> String {
    if let Some(raw) = e.raw_os_error() {
        let os_err = io::Error::from_raw_os_error(raw);
        let msg = format!("{}", os_err);
        msg.replace(&format!(" (os error {})", raw), "")
    } else {
        format!("{}", e)
    }
}

#[cfg(test)]
mod tests {
    use std::process::Command;

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("fdu");
        Command::new(path)
    }
    #[cfg(unix)]
    #[test]
    fn test_du_current_dir() {
        let output = cmd().output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(!stdout.is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn test_du_specific_dir() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("file.txt"), "some content here\n").unwrap();
        let output = cmd().arg(dir.path().to_str().unwrap()).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains(dir.path().to_str().unwrap()));
    }

    #[cfg(unix)]
    #[test]
    fn test_du_summarize() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("sub")).unwrap();
        std::fs::write(dir.path().join("sub").join("f.txt"), "data\n").unwrap();
        let output = cmd()
            .args(["-s", dir.path().to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let lines: Vec<&str> = stdout.lines().collect();
        assert_eq!(lines.len(), 1, "summarize should produce only one line");
    }

    #[cfg(unix)]
    #[test]
    fn test_du_human_readable() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("file.txt"), "content\n").unwrap();
        let output = cmd()
            .args(["-h", dir.path().to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // Human readable should have a suffix like K, M, G or be a small number
        assert!(!stdout.is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn test_du_bytes() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("f.txt"), "data").unwrap();
        let output = cmd()
            .args(["-b", dir.path().to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
    }

    #[cfg(unix)]
    #[test]
    fn test_du_nonexistent() {
        let output = cmd().arg("/nonexistent/path/xyz").output().unwrap();
        assert!(!output.status.success());
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("cannot") || stderr.contains("No such"));
    }

    #[cfg(unix)]
    #[test]
    fn test_du_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let output = cmd()
            .args(["-s", dir.path().to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
    }

    #[cfg(unix)]
    #[test]
    fn test_du_max_depth() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("a").join("b").join("c")).unwrap();
        std::fs::write(dir.path().join("a").join("b").join("c").join("f.txt"), "x").unwrap();
        let output = cmd()
            .args(["--max-depth=1", dir.path().to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let lines: Vec<&str> = stdout.lines().collect();
        // max-depth=1 should show the dir and immediate subdirs only
        assert!(lines.len() <= 3);
    }

    #[cfg(unix)]
    #[test]
    fn test_du_total() {
        let dir = tempfile::tempdir().unwrap();
        let d1 = dir.path().join("a");
        let d2 = dir.path().join("b");
        std::fs::create_dir(&d1).unwrap();
        std::fs::create_dir(&d2).unwrap();
        std::fs::write(d1.join("f.txt"), "aaa").unwrap();
        std::fs::write(d2.join("f.txt"), "bbb").unwrap();
        let output = cmd()
            .args(["-c", d1.to_str().unwrap(), d2.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("total"));
    }
}