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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
#[cfg(not(unix))]
fn main() {
    eprintln!("chmod: only available on Unix");
    std::process::exit(1);
}

// fchmod -- change file mode bits
//
// Usage: chmod [OPTION]... MODE[,MODE]... FILE...
//   or:  chmod [OPTION]... OCTAL-MODE FILE...
//   or:  chmod [OPTION]... --reference=RFILE FILE...

#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(unix)]
use std::process;

#[cfg(unix)]
const TOOL_NAME: &str = "chmod";
#[cfg(unix)]
const VERSION: &str = env!("CARGO_PKG_VERSION");

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

    let mut config = coreutils_rs::chmod::ChmodConfig::default();
    let mut reference: Option<String> = None;
    let mut mode_str: Option<String> = None;
    let mut files: Vec<String> = Vec::new();
    let mut saw_dashdash = false;
    // Track if the mode was supplied as a dash-prefixed arg before '--'.
    // GNU chmod only emits the umask-blocked warning in this case.
    let mut mode_looks_like_option = 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 {
            // After --, first non-option arg is still the mode if we haven't
            // seen one yet (GNU behaviour: -- only stops option parsing, the
            // mode is always the first non-option operand).
            if mode_str.is_none() && reference.is_none() {
                mode_str = Some(arg.clone());
            } else {
                files.push(arg.clone());
            }
            i += 1;
            continue;
        }
        match arg.as_str() {
            "--help" => {
                print_help();
                return;
            }
            "--version" => {
                println!("{} (fcoreutils) {}", TOOL_NAME, VERSION);
                return;
            }
            "--" => saw_dashdash = true,
            "-c" | "--changes" => config.changes = true,
            "-f" | "--silent" | "--quiet" => config.quiet = true,
            "-v" | "--verbose" => config.verbose = true,
            "--no-preserve-root" => config.preserve_root = false,
            "--preserve-root" => config.preserve_root = true,
            "-R" | "--recursive" => config.recursive = true,
            s if s.starts_with("--reference=") => {
                reference = Some(s["--reference=".len()..].to_string());
            }
            "--reference" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("{}: option '--reference' requires an argument", TOOL_NAME);
                    eprintln!("Try '{} --help' for more information.", TOOL_NAME);
                    process::exit(1);
                }
                reference = Some(args[i].clone());
            }
            s if s.starts_with('-') && s.len() > 1 && !s.starts_with("--") => {
                // Could be combined short flags like -Rvc, OR a symbolic mode like -rwx
                // Try to parse as flags first
                let chars: Vec<char> = s[1..].chars().collect();
                let all_flags = chars.iter().all(|c| matches!(c, 'c' | 'f' | 'v' | 'R'));
                if all_flags {
                    for ch in &chars {
                        match ch {
                            'c' => config.changes = true,
                            'f' => config.quiet = true,
                            'v' => config.verbose = true,
                            'R' => config.recursive = true,
                            _ => unreachable!(),
                        }
                    }
                } else {
                    // Treat as mode string (e.g. "-rwx" means remove rwx)
                    if mode_str.is_none() {
                        mode_str = Some(arg.clone());
                        // This mode was passed as a dash-prefixed arg, not after --
                        mode_looks_like_option = true;
                    } else {
                        files.push(arg.clone());
                    }
                }
            }
            _ => {
                // First non-option argument is the mode (unless --reference is used)
                if mode_str.is_none() && reference.is_none() {
                    mode_str = Some(arg.clone());
                } else {
                    files.push(arg.clone());
                }
            }
        }
        i += 1;
    }

    // If --reference is used, we don't need a mode string
    if reference.is_none() && mode_str.is_none() {
        eprintln!("{}: missing operand", TOOL_NAME);
        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
        process::exit(1);
    }

    if files.is_empty() {
        if reference.is_some() {
            eprintln!("{}: missing operand", TOOL_NAME);
        } else {
            eprintln!(
                "{}: missing operand after '{}'",
                TOOL_NAME,
                mode_str.as_deref().unwrap_or("")
            );
        }
        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
        process::exit(1);
    }

    // Get mode from reference file if specified
    let effective_mode_str: String = if let Some(ref rfile) = reference {
        match std::fs::metadata(rfile) {
            Ok(meta) => {
                let m = meta.mode() & 0o7777;
                format!("{:o}", m)
            }
            Err(e) => {
                eprintln!(
                    "{}: failed to get attributes of '{}': {}",
                    TOOL_NAME,
                    rfile,
                    coreutils_rs::common::io_error_msg(&e)
                );
                process::exit(1);
            }
        }
    } else {
        mode_str.unwrap()
    };

    let mut exit_code = 0;

    for file in &files {
        let path = std::path::Path::new(file);

        if config.recursive {
            if config.preserve_root && path == std::path::Path::new("/") {
                eprintln!(
                    "{}: it is dangerous to operate recursively on '/'",
                    TOOL_NAME
                );
                eprintln!(
                    "{}: use --no-preserve-root to override this failsafe",
                    TOOL_NAME
                );
                exit_code = 1;
                continue;
            }

            if let Err(e) = coreutils_rs::chmod::chmod_recursive(path, &effective_mode_str, &config)
            {
                if !config.quiet {
                    eprintln!("{}: {}", TOOL_NAME, e);
                }
                exit_code = 1;
            }
        } else {
            // Get current mode
            let metadata = match std::fs::symlink_metadata(path) {
                Ok(m) => m,
                Err(e) => {
                    if !config.quiet {
                        eprintln!(
                            "{}: cannot access '{}': {}",
                            TOOL_NAME,
                            file,
                            coreutils_rs::common::io_error_msg(&e)
                        );
                    }
                    exit_code = 1;
                    continue;
                }
            };

            // Handle symlinks: GNU chmod tries to follow symlinks by default.
            // For dangling symlinks, stat() fails, so chmod errors out.
            if metadata.file_type().is_symlink() {
                // Try to follow the symlink
                match std::fs::metadata(path) {
                    Ok(_) => {
                        // Symlink target exists - use target metadata instead
                        // (fall through to normal processing)
                    }
                    Err(e) => {
                        // Dangling symlink - error like GNU chmod
                        if !config.quiet {
                            eprintln!(
                                "{}: cannot operate on dangling symlink '{}': {}",
                                TOOL_NAME,
                                file,
                                coreutils_rs::common::io_error_msg(&e)
                            );
                        }
                        exit_code = 1;
                        continue;
                    }
                }
            }

            let current_mode = metadata.mode();
            let (mut new_mode, umask_blocked) = match coreutils_rs::chmod::parse_mode_check_umask(
                &effective_mode_str,
                current_mode,
            ) {
                Ok(r) => r,
                Err(e) => {
                    eprintln!("{}: {}", TOOL_NAME, e);
                    process::exit(1);
                }
            };

            // GNU chmod: for directories, preserve setuid/setgid bits when the octal
            // mode doesn't explicitly specify them (i.e., <= 4 octal digits).
            // "0755" (4 digits) -> preserves, "00755" (5 digits) -> clears.
            if metadata.is_dir()
                && !effective_mode_str.is_empty()
                && effective_mode_str
                    .bytes()
                    .all(|b| b.is_ascii_digit() && b < b'8')
                && effective_mode_str.len() <= 4
            {
                let existing_special = current_mode & 0o7000;
                new_mode |= existing_special;
            }

            if let Err(e) = coreutils_rs::chmod::chmod_file(path, new_mode, &config) {
                if !config.quiet {
                    eprintln!(
                        "{}: changing permissions of '{}': {}",
                        TOOL_NAME,
                        file,
                        coreutils_rs::common::io_error_msg(&e)
                    );
                }
                exit_code = 1;
            } else if umask_blocked && mode_looks_like_option {
                // GNU chmod warns when umask prevents the requested mode from
                // being fully applied, but ONLY when the mode string was supplied
                // as a dash-prefixed argument (not after '--').
                let actual_sym = coreutils_rs::chmod::format_symbolic_for_warning(new_mode);
                // Compute the mode that would have been set without umask
                let unmasked_mode = match coreutils_rs::chmod::parse_mode_no_umask(
                    &effective_mode_str,
                    current_mode,
                ) {
                    Ok(m) => m,
                    Err(_) => new_mode,
                };
                let requested_sym = coreutils_rs::chmod::format_symbolic_for_warning(unmasked_mode);
                eprintln!(
                    "{}: {}: new permissions are {}, not {}",
                    TOOL_NAME, file, actual_sym, requested_sym
                );
                exit_code = 1;
            }
        }
    }

    if exit_code != 0 {
        process::exit(exit_code);
    }
}

#[cfg(unix)]
fn print_help() {
    println!("Usage: {} [OPTION]... MODE[,MODE]... FILE...", TOOL_NAME);
    println!("  or:  {} [OPTION]... OCTAL-MODE FILE...", TOOL_NAME);
    println!("  or:  {} [OPTION]... --reference=RFILE FILE...", TOOL_NAME);
    println!();
    println!("Change the mode of each FILE to MODE.");
    println!("With --reference, change the mode of each FILE to that of RFILE.");
    println!();
    println!("  -c, --changes          like verbose but report only when a change is made");
    println!("  -f, --silent, --quiet   suppress most error messages");
    println!("  -v, --verbose          output a diagnostic for every file processed");
    println!("      --no-preserve-root  do not treat '/' specially (the default)");
    println!("      --preserve-root    fail to operate recursively on '/'");
    println!("      --reference=RFILE  use RFILE's mode instead of MODE values");
    println!("  -R, --recursive        change files and directories recursively");
    println!("      --help     display this help and exit");
    println!("      --version  output version information and exit");
    println!();
    println!("Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+'.");
}

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

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("fchmod");
        Command::new(path)
    }
    #[test]
    fn test_missing_operand() {
        let output = cmd().output().unwrap();
        assert_eq!(output.status.code(), Some(1));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("missing operand"));
    }

    #[test]
    fn test_missing_file() {
        let output = cmd().arg("755").output().unwrap();
        assert_eq!(output.status.code(), Some(1));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("missing operand"));
    }

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

        let output = cmd()
            .args(["755", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success(), "chmod 755 should succeed");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let meta = std::fs::metadata(&file).unwrap();
            let mode = meta.permissions().mode() & 0o777;
            assert_eq!(mode, 0o755, "mode should be 0755, got {:o}", mode);
        }
    }

    #[test]
    fn test_symbolic_mode() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("sym.txt");
        std::fs::write(&file, "test").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
        }

        let output = cmd()
            .args(["u+x", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let meta = std::fs::metadata(&file).unwrap();
            let mode = meta.permissions().mode() & 0o777;
            assert_eq!(mode, 0o744, "mode should be 0744, got {:o}", mode);
        }
    }

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

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
        }

        let output = cmd()
            .args(["-R", "755", dir.path().to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let meta = std::fs::metadata(&file).unwrap();
            let mode = meta.permissions().mode() & 0o777;
            assert_eq!(mode, 0o755, "mode should be 0755, got {:o}", mode);
        }
    }

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

        let output = cmd()
            .args(["-v", "755", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        // GNU chmod sends verbose output to stdout
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains("mode of"),
            "verbose should report mode change on stdout: {}",
            stdout
        );
    }

    #[test]
    fn test_reference_file() {
        let dir = tempfile::tempdir().unwrap();
        let ref_file = dir.path().join("ref.txt");
        let target = dir.path().join("target.txt");
        std::fs::write(&ref_file, "ref").unwrap();
        std::fs::write(&target, "target").unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&ref_file, std::fs::Permissions::from_mode(0o751)).unwrap();
            std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644)).unwrap();
        }

        let output = cmd()
            .args([
                &format!("--reference={}", ref_file.to_str().unwrap()),
                target.to_str().unwrap(),
            ])
            .output()
            .unwrap();
        assert!(output.status.success());

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let meta = std::fs::metadata(&target).unwrap();
            let mode = meta.permissions().mode() & 0o777;
            assert_eq!(mode, 0o751, "mode should match reference, got {:o}", mode);
        }
    }

    #[test]
    fn test_nonexistent_file() {
        let output = cmd()
            .args(["755", "/nonexistent_file_12345"])
            .output()
            .unwrap();
        assert_ne!(output.status.code(), Some(0));
    }

    #[test]
    fn test_quiet_suppresses_errors() {
        let output = cmd()
            .args(["-f", "755", "/nonexistent_file_12345"])
            .output()
            .unwrap();
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.is_empty(),
            "quiet mode should suppress errors: {}",
            stderr
        );
    }

    #[test]
    fn test_preserve_root() {
        let output = cmd()
            .args(["-R", "--preserve-root", "755", "/"])
            .output()
            .unwrap();
        assert_ne!(output.status.code(), Some(0));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("dangerous"),
            "should warn about root: {}",
            stderr
        );
    }

    #[test]
    fn test_double_dash_mode() {
        // After --, the first arg should be treated as mode, not file
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("dd.txt");
        std::fs::write(&file, "test").unwrap();

        let output = cmd()
            .args(["--", "755", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "chmod -- 755 file should succeed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let meta = std::fs::metadata(&file).unwrap();
            let mode = meta.permissions().mode() & 0o777;
            assert_eq!(mode, 0o755, "mode should be 0755, got {:o}", mode);
        }
    }

    #[test]
    fn test_double_dash_minus_mode() {
        // After --, -rwx should be treated as a mode string
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("ddm.txt");
        std::fs::write(&file, "test").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o777)).unwrap();
        }

        let output = cmd()
            .args(["--", "-rwx", file.to_str().unwrap()])
            .output()
            .unwrap();
        // After --, no umask warning should be emitted
        assert!(
            output.status.success(),
            "chmod -- -rwx file should succeed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn test_verbose_includes_symbolic() {
        // GNU chmod includes symbolic mode in parentheses
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("vs.txt");
        std::fs::write(&file, "test").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
        }

        let output = cmd()
            .args(["-v", "755", file.to_str().unwrap()])
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains("(rw-r--r--)"),
            "verbose should include symbolic old mode: {}",
            stdout
        );
        assert!(
            stdout.contains("(rwxr-xr-x)"),
            "verbose should include symbolic new mode: {}",
            stdout
        );
    }

    #[test]
    fn test_chmod_go_minus_rwx() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "test").unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o777)).unwrap();

        let output = cmd()
            .args(["go-rwx", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());

        let meta = std::fs::metadata(&file).unwrap();
        let mode = meta.permissions().mode() & 0o777;
        assert_eq!(mode, 0o700, "mode should be 0700, got {:o}", mode);
    }

    #[test]
    fn test_chmod_multiple_modes() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "test").unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o000)).unwrap();

        let output = cmd()
            .args(["u+rw,g+r", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());

        let meta = std::fs::metadata(&file).unwrap();
        let mode = meta.permissions().mode() & 0o777;
        assert_eq!(mode, 0o640, "mode should be 0640, got {:o}", mode);
    }

    #[test]
    fn test_chmod_a_plus_x() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "test").unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();

        let output = cmd()
            .args(["a+x", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());

        let meta = std::fs::metadata(&file).unwrap();
        let mode = meta.permissions().mode() & 0o777;
        assert_eq!(mode, 0o755, "mode should be 0755, got {:o}", mode);
    }

    #[test]
    fn test_chmod_set_exact() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "test").unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o777)).unwrap();

        let output = cmd()
            .args(["u=rw,go=", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());

        let meta = std::fs::metadata(&file).unwrap();
        let mode = meta.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "mode should be 0600, got {:o}", mode);
    }

    #[test]
    fn test_chmod_changes_flag() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "test").unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();

        // --changes should only report if mode actually changed
        let output = cmd()
            .args(["--changes", "644", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        // No change, so stdout should be empty
        assert!(
            output.stdout.is_empty(),
            "no-change should produce no output with --changes"
        );
    }

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

        let output = cmd()
            .args(["zzz", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(!output.status.success());
    }

    #[test]
    fn test_chmod_multiple_files() {
        let dir = tempfile::tempdir().unwrap();
        let f1 = dir.path().join("a.txt");
        let f2 = dir.path().join("b.txt");
        std::fs::write(&f1, "a").unwrap();
        std::fs::write(&f2, "b").unwrap();

        let output = cmd()
            .args(["600", f1.to_str().unwrap(), f2.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());

        use std::os::unix::fs::PermissionsExt;
        assert_eq!(
            std::fs::metadata(&f1).unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert_eq!(
            std::fs::metadata(&f2).unwrap().permissions().mode() & 0o777,
            0o600
        );
    }
}