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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// frealpath — print the resolved path
//
// Usage: realpath [OPTION]... FILE...

use std::path::{Component, Path, PathBuf};
use std::process;

const TOOL_NAME: &str = "realpath";
const VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    /// Default: all components must exist, resolve symlinks
    Canonicalize,
    /// -e: all components must exist (explicit)
    CanonicalizeExisting,
    /// -m: no existence requirements
    CanonicalizeMissing,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum SymlinkMode {
    /// -P: resolve symlinks as encountered (default)
    Physical,
    /// -L: resolve '..' components before symlinks
    Logical,
}

fn main() {
    coreutils_rs::common::reset_sigpipe();

    let mut mode = Mode::Canonicalize;
    let mut no_symlinks = false;
    let mut symlink_mode = SymlinkMode::Physical;
    let mut zero = false;
    let mut quiet = false;
    let mut relative_to: Option<String> = None;
    let mut relative_base: Option<String> = None;
    let mut files: Vec<String> = Vec::new();
    let mut saw_dashdash = false;

    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        if saw_dashdash {
            files.push(arg.clone());
            i += 1;
            continue;
        }
        match arg.as_str() {
            "--help" => {
                print_help();
                return;
            }
            "--version" => {
                println!("{} (fcoreutils) {}", TOOL_NAME, VERSION);
                return;
            }
            "-e" | "--canonicalize-existing" => mode = Mode::CanonicalizeExisting,
            "-m" | "--canonicalize-missing" => mode = Mode::CanonicalizeMissing,
            "-s" | "--strip" | "--no-symlinks" => no_symlinks = true,
            "-z" | "--zero" => zero = true,
            "-q" | "--quiet" => quiet = true,
            "-L" | "--logical" => symlink_mode = SymlinkMode::Logical,
            "-P" | "--physical" => symlink_mode = SymlinkMode::Physical,
            "--relative-to" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("{}: option '--relative-to' requires an argument", TOOL_NAME);
                    process::exit(1);
                }
                relative_to = Some(args[i].clone());
            }
            "--relative-base" => {
                i += 1;
                if i >= args.len() {
                    eprintln!(
                        "{}: option '--relative-base' requires an argument",
                        TOOL_NAME
                    );
                    process::exit(1);
                }
                relative_base = Some(args[i].clone());
            }
            s if s.starts_with("--relative-to=") => {
                relative_to = Some(s["--relative-to=".len()..].to_string());
            }
            s if s.starts_with("--relative-base=") => {
                relative_base = Some(s["--relative-base=".len()..].to_string());
            }
            "--" => saw_dashdash = true,
            s if s.starts_with('-') && !s.starts_with("--") && s.len() > 1 => {
                for ch in s[1..].chars() {
                    match ch {
                        'e' => mode = Mode::CanonicalizeExisting,
                        'm' => mode = Mode::CanonicalizeMissing,
                        's' => no_symlinks = true,
                        'z' => zero = true,
                        'q' => quiet = true,
                        'L' => symlink_mode = SymlinkMode::Logical,
                        'P' => symlink_mode = SymlinkMode::Physical,
                        _ => {
                            eprintln!("{}: invalid option -- '{}'", TOOL_NAME, ch);
                            eprintln!("Try '{} --help' for more information.", TOOL_NAME);
                            process::exit(1);
                        }
                    }
                }
            }
            _ => files.push(arg.clone()),
        }
        i += 1;
    }

    if files.is_empty() {
        eprintln!("{}: missing operand", TOOL_NAME);
        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
        process::exit(1);
    }

    // Validate --relative-to and --relative-base are not empty strings
    if let Some(ref val) = relative_to
        && val.is_empty()
    {
        eprintln!("{}: '': No such file or directory", TOOL_NAME);
        process::exit(1);
    }
    if let Some(ref val) = relative_base
        && val.is_empty()
    {
        eprintln!("{}: '': No such file or directory", TOOL_NAME);
        process::exit(1);
    }

    // Resolve relative-to and relative-base directories
    let resolved_relative_to = relative_to.as_ref().map(|d| {
        resolve_path(d, mode, no_symlinks, symlink_mode)
            .unwrap_or_else(|_| make_absolute(Path::new(d)))
    });
    let resolved_relative_base = relative_base.as_ref().map(|d| {
        resolve_path(d, mode, no_symlinks, symlink_mode)
            .unwrap_or_else(|_| make_absolute(Path::new(d)))
    });

    // With -e mode, validate that --relative-to and --relative-base are directories
    if mode == Mode::CanonicalizeExisting {
        if let Some(ref resolved) = resolved_relative_to
            && resolved.exists()
            && !resolved.is_dir()
        {
            if !quiet {
                eprintln!(
                    "{}: {}: Not a directory",
                    TOOL_NAME,
                    relative_to.as_ref().unwrap()
                );
            }
            process::exit(1);
        }
        if let Some(ref resolved) = resolved_relative_base
            && resolved.exists()
            && !resolved.is_dir()
        {
            if !quiet {
                eprintln!(
                    "{}: {}: Not a directory",
                    TOOL_NAME,
                    relative_base.as_ref().unwrap()
                );
            }
            process::exit(1);
        }
    }

    let terminator = if zero { "\0" } else { "\n" };
    let mut exit_code = 0;

    for file in &files {
        // Empty string is an error for all modes (matches GNU)
        if file.is_empty() {
            exit_code = 1;
            if !quiet {
                eprintln!("{}: '': No such file or directory", TOOL_NAME);
            }
            continue;
        }
        match resolve_path(file, mode, no_symlinks, symlink_mode) {
            Ok(resolved) => {
                let output =
                    apply_relative(&resolved, &resolved_relative_to, &resolved_relative_base);
                print!("{}{}", output.to_string_lossy(), terminator);
            }
            Err(e) => {
                exit_code = 1;
                if !quiet {
                    eprintln!(
                        "{}: {}: {}",
                        TOOL_NAME,
                        file,
                        coreutils_rs::common::io_error_msg(&e)
                    );
                }
            }
        }
    }

    process::exit(exit_code);
}

fn resolve_path(
    path: &str,
    mode: Mode,
    no_symlinks: bool,
    symlink_mode: SymlinkMode,
) -> Result<PathBuf, std::io::Error> {
    if no_symlinks {
        // Just normalize the path logically without resolving symlinks
        let abs = make_absolute(Path::new(path));
        let normalized = normalize_path(&abs);
        match mode {
            Mode::CanonicalizeExisting | Mode::Canonicalize => {
                // All components must exist
                if !normalized.exists() {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        "No such file or directory",
                    ));
                }
                Ok(normalized)
            }
            Mode::CanonicalizeMissing => Ok(normalized),
        }
    } else if symlink_mode == SymlinkMode::Logical {
        // Logical mode: resolve .. textually first, then canonicalize remaining
        resolve_logical(path, mode)
    } else {
        // Physical mode (default): resolve symlinks as encountered
        match mode {
            Mode::Canonicalize | Mode::CanonicalizeExisting => std::fs::canonicalize(path),
            Mode::CanonicalizeMissing => canonicalize_missing(Path::new(path)),
        }
    }
}

/// Logical mode (-L): resolve '..' components before symlinks.
/// 1. Make path absolute
/// 2. Collapse . and .. textually
/// 3. Canonicalize the result (resolving symlinks in what remains)
fn resolve_logical(path: &str, mode: Mode) -> Result<PathBuf, std::io::Error> {
    let abs = make_absolute(Path::new(path));
    let normalized = normalize_path(&abs);
    match mode {
        Mode::Canonicalize | Mode::CanonicalizeExisting => std::fs::canonicalize(&normalized),
        Mode::CanonicalizeMissing => canonicalize_missing(&normalized),
    }
}

/// Make a path absolute
fn make_absolute(path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("/"))
            .join(path)
    }
}

/// Normalize a path by resolving . and .. without touching the filesystem
fn normalize_path(path: &Path) -> PathBuf {
    let mut result = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                result.pop();
            }
            c => {
                result.push(c.as_os_str());
            }
        }
    }
    result
}

/// Canonicalize a path where not all components need to exist.
fn canonicalize_missing(path: &Path) -> Result<PathBuf, std::io::Error> {
    let abs = make_absolute(path);

    // Try to canonicalize the whole thing first
    if let Ok(canon) = std::fs::canonicalize(&abs) {
        return Ok(canon);
    }

    let components: Vec<Component<'_>> = abs.components().collect();
    let mut resolved = PathBuf::new();
    let mut remaining_start = 0;

    // Find the longest resolvable prefix
    for i in (0..components.len()).rev() {
        let mut prefix = PathBuf::new();
        for c in &components[..=i] {
            prefix.push(c.as_os_str());
        }
        if let Ok(canon) = std::fs::canonicalize(&prefix) {
            resolved = canon;
            remaining_start = i + 1;
            break;
        }
    }

    if resolved.as_os_str().is_empty() {
        if let Some(Component::RootDir) = components.first() {
            resolved.push("/");
            remaining_start = 1;
        } else {
            resolved = std::env::current_dir()?;
        }
    }

    for c in &components[remaining_start..] {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                resolved.pop();
            }
            Component::Normal(s) => {
                resolved.push(s);
                if resolved.symlink_metadata().is_ok()
                    && let Ok(canon) = std::fs::canonicalize(&resolved)
                {
                    resolved = canon;
                }
            }
            Component::RootDir | Component::Prefix(_) => {
                resolved.push(c.as_os_str());
            }
        }
    }

    Ok(resolved)
}

/// Compute the relative path from `from` to `to`
fn relative_path(from: &Path, to: &Path) -> PathBuf {
    let from_components: Vec<Component<'_>> = from.components().collect();
    let to_components: Vec<Component<'_>> = to.components().collect();

    // Find common prefix length
    let common_len = from_components
        .iter()
        .zip(to_components.iter())
        .take_while(|(a, b)| a == b)
        .count();

    let mut result = PathBuf::new();

    // Add ".." for each remaining component in `from`
    for _ in common_len..from_components.len() {
        result.push("..");
    }

    // Append remaining components of `to`
    for c in &to_components[common_len..] {
        result.push(c.as_os_str());
    }

    if result.as_os_str().is_empty() {
        PathBuf::from(".")
    } else {
        result
    }
}

/// Apply --relative-to and --relative-base logic
fn apply_relative(
    path: &Path,
    relative_to: &Option<PathBuf>,
    relative_base: &Option<PathBuf>,
) -> PathBuf {
    // If --relative-base is given (without --relative-to), output relative if under base, else absolute
    if let Some(base) = relative_base
        && relative_to.is_none()
    {
        // If path starts with base, output relative to base
        if path.starts_with(base) {
            return relative_path(base, path);
        }
        // Otherwise return absolute
        return path.to_path_buf();
    }

    // If --relative-to is given
    if let Some(rel_to) = relative_to {
        // If --relative-base is also given, only make relative if both are under base
        if let Some(base) = relative_base {
            if path.starts_with(base) && rel_to.starts_with(base) {
                return relative_path(rel_to, path);
            }
            return path.to_path_buf();
        }
        return relative_path(rel_to, path);
    }

    path.to_path_buf()
}

fn print_help() {
    println!("Usage: {} [OPTION]... FILE...", TOOL_NAME);
    println!("Print the resolved absolute file name;");
    println!("all but the last component must exist");
    println!();
    println!("  -e, --canonicalize-existing   all components of the path must exist");
    println!("  -m, --canonicalize-missing    no path components need exist or be a directory");
    println!("  -L, --logical                 resolve '..' components before symlinks");
    println!("  -P, --physical                resolve symlinks as encountered (default)");
    println!("  -q, --quiet                   suppress most error messages");
    println!("  -s, --strip, --no-symlinks    don't expand symlinks");
    println!("  -z, --zero                    end each output line with NUL, not newline");
    println!("      --relative-to=DIR         print the resolved path relative to DIR");
    println!("      --relative-base=DIR       print absolute paths unless paths below DIR");
    println!("      --help     display this help and exit");
    println!("      --version  output version information and exit");
}

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

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("frealpath");
        Command::new(path)
    }

    #[test]
    fn test_realpath_absolute() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("file.txt");
        fs::write(&file, "hello").unwrap();

        let output = cmd().arg(file.to_str().unwrap()).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let canon = fs::canonicalize(&file).unwrap();
        assert_eq!(stdout.trim(), canon.to_str().unwrap());
    }

    #[test]
    fn test_realpath_symlinks() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real.txt");
        let link = dir.path().join("sym.txt");
        fs::write(&target, "data").unwrap();
        std::os::unix::fs::symlink(&target, &link).unwrap();

        let output = cmd().arg(link.to_str().unwrap()).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let canon = fs::canonicalize(&target).unwrap();
        assert_eq!(stdout.trim(), canon.to_str().unwrap());
    }

    #[test]
    fn test_realpath_no_symlinks() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real2.txt");
        let link = dir.path().join("sym2.txt");
        fs::write(&target, "data").unwrap();
        std::os::unix::fs::symlink(&target, &link).unwrap();

        let output = cmd().args(["-s", link.to_str().unwrap()]).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // With -s, should NOT resolve the symlink — output should contain the symlink path
        // Use canonicalize on parent dir to handle macOS /var -> /private/var
        let canon_dir = fs::canonicalize(dir.path()).unwrap();
        let abs_link = canon_dir.join("sym2.txt");
        // On macOS, -s won't resolve /var -> /private/var, so compare path components
        let stdout_trimmed = stdout.trim();
        assert!(
            stdout_trimmed == abs_link.to_str().unwrap() || stdout_trimmed.ends_with("/sym2.txt"),
            "Expected path to sym2.txt, got: {}",
            stdout_trimmed
        );
    }

    #[test]
    fn test_realpath_missing() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("nonexistent").join("deep").join("path.txt");

        let output = cmd()
            .args(["-m", missing.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // Should contain the path components even though they don't exist
        assert!(stdout.contains("nonexistent"));
        assert!(stdout.contains("path.txt"));
    }

    #[test]
    fn test_realpath_existing() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("does_not_exist.txt");

        let output = cmd()
            .args(["-e", missing.to_str().unwrap()])
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(1));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("No such file or directory"));
    }

    #[test]
    fn test_realpath_relative_to() {
        let dir = tempfile::tempdir().unwrap();
        let subdir = dir.path().join("sub");
        let file = dir.path().join("file.txt");
        fs::create_dir(&subdir).unwrap();
        fs::write(&file, "test").unwrap();

        let canon_dir = fs::canonicalize(&subdir).unwrap();
        let output = cmd()
            .args([
                &format!("--relative-to={}", canon_dir.to_str().unwrap()),
                file.to_str().unwrap(),
            ])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), "../file.txt");
    }

    #[test]
    fn test_realpath_logical_mode() {
        let dir = tempfile::tempdir().unwrap();
        let canon_dir = fs::canonicalize(dir.path()).unwrap();
        let real_dir = canon_dir.join("real_dir");
        let link = canon_dir.join("link");
        fs::create_dir(&real_dir).unwrap();
        std::os::unix::fs::symlink(&real_dir, &link).unwrap();

        // -L link/.. should resolve to parent of link (not parent of real_dir)
        let link_dotdot = format!("{}/link/..", canon_dir.display());
        let output = cmd().args(["-L", &link_dotdot]).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), canon_dir.to_str().unwrap());
    }

    #[test]
    fn test_realpath_physical_mode() {
        let output = cmd().args(["-P", "/tmp"]).output().unwrap();
        assert!(output.status.success());
    }

    #[test]
    fn test_realpath_combined_flags() {
        let output = cmd().args(["-Pqz", "/tmp"]).output().unwrap();
        assert!(output.status.success());
        let stdout = output.stdout;
        // Should end with NUL, not newline
        assert!(stdout.ends_with(b"\0"), "Expected NUL terminator");
        assert!(!stdout.ends_with(b"\n"), "Should not end with newline");
    }

    #[test]
    fn test_realpath_empty_string_all_modes() {
        // Empty string should fail for ALL modes including -m
        for flag in &["", "-e", "-m"] {
            let mut c = cmd();
            if !flag.is_empty() {
                c.arg(*flag);
            }
            c.arg("");
            let output = c.output().unwrap();
            assert_eq!(
                output.status.code(),
                Some(1),
                "Empty string should fail with flag '{}'",
                flag
            );
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(
                stderr.contains("No such file or directory"),
                "Expected error message with flag '{}', got: {}",
                flag,
                stderr
            );
        }
    }

    #[test]
    fn test_realpath_empty_relative_base() {
        let output = cmd().args(["--relative-base=", "/tmp"]).output().unwrap();
        assert_eq!(output.status.code(), Some(1));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("No such file or directory"));
    }

    #[test]
    fn test_realpath_empty_relative_to() {
        let output = cmd().args(["--relative-to=", "/tmp"]).output().unwrap();
        assert_eq!(output.status.code(), Some(1));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("No such file or directory"));
    }

    #[test]
    fn test_realpath_e_relative_to_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("afile");
        fs::write(&file, "x").unwrap();

        let output = cmd()
            .args([
                "-e",
                &format!("--relative-to={}", file.to_str().unwrap()),
                "/tmp",
            ])
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(1));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("Not a directory"));
    }

    #[test]
    fn test_realpath_slashes() {
        let output = cmd().args(["/", "//", "///"]).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let lines: Vec<&str> = stdout.trim().lines().collect();
        assert_eq!(lines.len(), 3);
        for line in &lines {
            assert_eq!(*line, "/", "Expected '/' but got '{}'", line);
        }
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_realpath_matches_gnu() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("gnu_test.txt");
        fs::write(&file, "hello").unwrap();

        let gnu = Command::new("realpath")
            .arg(file.to_str().unwrap())
            .output();
        if let Ok(gnu) = gnu {
            let ours = cmd().arg(file.to_str().unwrap()).output().unwrap();
            assert_eq!(ours.status.code(), gnu.status.code(), "Exit code mismatch");
            let gnu_out = String::from_utf8_lossy(&gnu.stdout);
            let our_out = String::from_utf8_lossy(&ours.stdout);
            assert_eq!(our_out.trim(), gnu_out.trim(), "Output mismatch");
        }

        // Compare -m on nonexistent path
        let missing = dir.path().join("missing_gnu");
        let gnu_m = Command::new("realpath")
            .args(["-m", missing.to_str().unwrap()])
            .output();
        if let Ok(gnu_m) = gnu_m {
            let ours_m = cmd()
                .args(["-m", missing.to_str().unwrap()])
                .output()
                .unwrap();
            assert_eq!(
                ours_m.status.code(),
                gnu_m.status.code(),
                "Exit code mismatch for -m"
            );
            let gnu_out = String::from_utf8_lossy(&gnu_m.stdout);
            let our_out = String::from_utf8_lossy(&ours_m.stdout);
            assert_eq!(our_out.trim(), gnu_out.trim(), "Output mismatch for -m");
        }
    }
}