rsmultigit 0.1.17

Manage multiple git repositories at once
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
mod cli;
mod commands;
mod config;
mod runner;
mod subprocess_utils;

use std::path::Path;

use anyhow::{Context, Result};
use clap::Parser;

use cli::{
    BranchWhat, BuildWhat, CleanWhat, Cli, Commands, CountWhat, ResetWhat, StashWhat, TagWhat,
};
use config::AppConfig;

fn main() -> Result<()> {
    let cli = Cli::parse();

    // Handle commands that don't need project discovery
    if let Commands::Complete { shell } = &cli.command {
        cli::print_completions(*shell);
        return Ok(());
    }
    if matches!(&cli.command, Commands::Version) {
        println!(
            "rsmultigit {} by {}",
            env!("CARGO_PKG_VERSION"),
            env!("CARGO_PKG_AUTHORS")
        );
        println!("GIT_DESCRIBE: {}", env!("GIT_DESCRIBE"));
        println!("GIT_SHA: {}", env!("GIT_SHA"));
        println!("GIT_BRANCH: {}", env!("GIT_BRANCH"));
        println!("GIT_DIRTY: {}", env!("GIT_DIRTY"));
        println!("RUSTC_SEMVER: {}", env!("RUSTC_SEMVER"));
        println!("RUST_EDITION: {}", env!("RUST_EDITION"));
        println!("BUILD_TIMESTAMP: {}", env!("BUILD_TIMESTAMP"));
        return Ok(());
    }
    if matches!(&cli.command, Commands::ConfigExample) {
        // Doesn't need (and must not require) a config file — this subcommand
        // is how a fresh user bootstraps their ~/.config/rsmultigit/config.toml.
        print!("{}", include_str!("../assets/config-example.toml"));
        return Ok(());
    }

    let config = AppConfig::from(&cli);

    // Repo list comes from ~/.config/rsmultigit/config.toml for every command.
    let config_path = commands::check::default_config_path()?;
    let file_config = commands::check::load_config(&config_path)?;
    let projects = commands::check::resolve_repos(&file_config)?;

    if let Commands::CheckSame {
        checks,
        checks_re,
        only_failed,
        diff,
        copy,
        allow_empty,
        fix_missing,
    } = &cli.command
    {
        let exit_code = run_check_same(
            &config,
            &file_config,
            &projects,
            &CheckSameOpts {
                requested: checks,
                requested_re: checks_re,
                only_failed: *only_failed,
                show_diff: *diff,
                do_copy: *copy,
                allow_empty: *allow_empty,
                do_fix_missing: *fix_missing,
            },
        )?;
        std::process::exit(exit_code);
    }

    match &cli.command {
        // ── do_count ──
        Commands::Count { what } => {
            let test_fn: fn(&Path) -> anyhow::Result<bool> = match what {
                CountWhat::Dirty => commands::count::is_dirty,
                CountWhat::Untracked => commands::count::has_untracked,
                CountWhat::Synchronized => commands::count::non_synchronized,
            };
            runner::do_count(&config, &projects, test_fn)?;
        }

        // ── print_if_data ──
        Commands::Status => {
            // Default: one-line summary of each repo's situation (counts of
            // modified/staged/untracked files, ahead/behind). --verbose switches
            // to the full `git status -s` per-file output.
            if config.verbose {
                runner::print_if_data(&config, &projects, commands::status::do_status)?;
            } else {
                runner::print_if_data(&config, &projects, commands::status::do_status_summary)?;
            }
        }
        Commands::Dirty => {
            runner::print_if_data(&config, &projects, commands::status::do_dirty)?;
        }
        Commands::ListChecks => {
            for rule in &file_config.check {
                println!("{}", rule.name);
            }
        }
        Commands::ListRepos => {
            // Prints one path per line with no header — the project path *is* the data,
            // so the bracketed header would be redundant. --verbose re-enables the
            // standard [project]\n<data> format for consistency with other commands.
            for project in &projects {
                if config.verbose && !config.terse && !config.no_header {
                    println!("[{}]", project.display());
                }
                println!("{}", project.display());
            }
        }
        Commands::Age => {
            runner::print_if_data(&config, &projects, commands::age::do_age)?;
        }
        Commands::Authors => {
            runner::print_if_data(&config, &projects, commands::authors::do_authors)?;
        }
        Commands::Config { key } => {
            let key = key.clone();
            runner::print_if_data(&config, &projects, move |project: &Path| {
                commands::config::do_config(project, &key)
            })?;
        }
        Commands::Size => {
            runner::print_if_data(&config, &projects, commands::size::do_size)?;
        }
        Commands::LastTag => {
            runner::print_if_data(&config, &projects, commands::last_tag::do_last_tag)?;
        }

        // ── do_for_all_projects ──
        Commands::Branch { what } => {
            let branch_fn: fn(&Path) -> anyhow::Result<bool> = match what {
                BranchWhat::Local => commands::branch::branch_local,
                BranchWhat::Remote => commands::branch::branch_remote,
                BranchWhat::Github => commands::branch::branch_github,
            };
            runner::do_for_all_projects(&config, &projects, branch_fn)?;
        }
        Commands::Pull { quiet } => {
            let quiet = *quiet;
            runner::do_for_all_projects(
                &config,
                &projects,
                move |project: &Path| -> anyhow::Result<bool> {
                    commands::pull::do_pull(project, quiet)
                },
            )?;
        }
        Commands::Push => {
            runner::do_for_all_projects(&config, &projects, commands::push::do_push)?;
        }
        Commands::Fetch => {
            runner::do_for_all_projects(&config, &projects, commands::fetch::do_fetch)?;
        }
        Commands::Clean { what } => {
            let clean_fn: fn(&Path) -> anyhow::Result<bool> = match what {
                CleanWhat::Hard => commands::clean::clean_hard,
                CleanWhat::Soft => commands::clean::clean_soft,
                CleanWhat::Make => commands::clean::clean_make,
                CleanWhat::Git => commands::clean::clean_git,
                CleanWhat::Cargo => commands::clean::clean_cargo,
            };
            runner::do_for_all_projects(&config, &projects, clean_fn)?;
        }
        Commands::Stash { what } => {
            let stash_fn: fn(&Path) -> anyhow::Result<bool> = match what {
                StashWhat::Push => commands::stash::stash_push,
                StashWhat::Pop => commands::stash::stash_pop,
            };
            runner::do_for_all_projects(&config, &projects, stash_fn)?;
        }
        Commands::Reset { what } => {
            let reset_fn: fn(&Path) -> anyhow::Result<bool> = match what {
                ResetWhat::Hard => commands::reset::reset_hard,
                ResetWhat::Soft => commands::reset::reset_soft,
                ResetWhat::Mixed => commands::reset::reset_mixed,
            };
            runner::do_for_all_projects(&config, &projects, reset_fn)?;
        }
        Commands::Diff => {
            runner::do_for_all_projects(&config, &projects, commands::diff::do_diff)?;
        }
        Commands::Log { count } => {
            let count = *count;
            runner::do_for_all_projects(
                &config,
                &projects,
                move |project: &Path| -> anyhow::Result<bool> {
                    commands::log::do_log(project, count)
                },
            )?;
        }
        Commands::Tag { what } => match what {
            TagWhat::Local | TagWhat::Remote => {
                let tag_fn: fn(&Path) -> anyhow::Result<bool> = match what {
                    TagWhat::Local => commands::tag::tag_local,
                    TagWhat::Remote => commands::tag::tag_remote,
                    _ => unreachable!(),
                };
                runner::do_for_all_projects(&config, &projects, tag_fn)?;
            }
            TagWhat::HasLocal | TagWhat::HasRemote => {
                let test_fn: fn(&Path) -> anyhow::Result<bool> = match what {
                    TagWhat::HasLocal => commands::tag::tag_has_local,
                    TagWhat::HasRemote => commands::tag::tag_has_remote,
                    _ => unreachable!(),
                };
                runner::do_count(&config, &projects, test_fn)?;
            }
        },
        Commands::Remote => {
            runner::do_for_all_projects(&config, &projects, commands::remote::do_remote)?;
        }
        Commands::Prune => {
            runner::do_for_all_projects(&config, &projects, commands::prune::do_prune)?;
        }
        Commands::Gc => {
            runner::do_for_all_projects(&config, &projects, commands::gc::do_gc)?;
        }
        Commands::Checkout { branch } => {
            let branch = branch.clone();
            runner::do_for_all_projects(
                &config,
                &projects,
                move |project: &Path| -> anyhow::Result<bool> {
                    commands::checkout::do_checkout(project, &branch)
                },
            )?;
        }
        Commands::Commit { message } => {
            let message = message.clone();
            runner::do_for_all_projects(
                &config,
                &projects,
                move |project: &Path| -> anyhow::Result<bool> {
                    commands::commit::do_commit(project, &message)
                },
            )?;
        }
        Commands::SubmoduleUpdate => {
            runner::do_for_all_projects(&config, &projects, commands::submodule::submodule_update)?;
        }
        Commands::Blame { file } => {
            let file = file.clone();
            runner::do_for_all_projects(
                &config,
                &projects,
                move |project: &Path| -> anyhow::Result<bool> {
                    commands::blame::do_blame(project, &file)
                },
            )?;
        }
        Commands::Grep { regexp, files } => {
            let regexp = regexp.clone();
            let files = *files;
            runner::do_for_all_projects(
                &config,
                &projects,
                move |project: &Path| -> anyhow::Result<bool> {
                    commands::grep::do_grep(project, &regexp, files)
                },
            )?;
        }
        Commands::Run { command } => {
            let command = command.clone();
            runner::do_for_all_projects(
                &config,
                &projects,
                move |project: &Path| -> anyhow::Result<bool> {
                    commands::run::do_run(project, &command)
                },
            )?;
        }

        // ── build commands ──
        Commands::Build { what } => {
            type ProjectFn = fn(&Path) -> anyhow::Result<bool>;
            let (check_fn, build_fn): (ProjectFn, ProjectFn) = match what {
                BuildWhat::Bootstrap => (
                    commands::build::check_not_disabled,
                    commands::build::build_bootstrap,
                ),
                BuildWhat::Pydmt => (commands::build::check_pydmt, commands::build::build_pydmt),
                BuildWhat::Make => (
                    commands::build::check_not_disabled,
                    commands::build::build_make,
                ),
                BuildWhat::VenvMake => (
                    commands::build::check_not_disabled,
                    commands::build::build_venv_make,
                ),
                BuildWhat::VenvPydmt => (
                    commands::build::check_pydmt,
                    commands::build::build_venv_pydmt,
                ),
                BuildWhat::PydmtBuildVenv => (
                    commands::build::check_pydmt,
                    commands::build::build_pydmt_build_venv,
                ),
                BuildWhat::Rsconstruct => (
                    commands::build::check_rsconstruct,
                    commands::build::build_rsconstruct,
                ),
                BuildWhat::Cargo => (commands::build::check_cargo, commands::build::build_cargo),
                BuildWhat::CargoPublish => (
                    commands::build::check_cargo,
                    commands::build::build_cargo_publish,
                ),
            };
            runner::do_for_all_projects_with_check(&config, &projects, check_fn, build_fn)?;
        }

        Commands::CheckSame { .. } => unreachable!("handled above"),
        Commands::Complete { .. } => unreachable!("handled above"),
        Commands::ConfigExample => unreachable!("handled above"),
        Commands::Version => unreachable!("handled above"),
    }

    Ok(())
}

/// The check-same flag set, bundled to keep `run_check_same`'s signature small.
struct CheckSameOpts<'a> {
    requested: &'a [String],
    requested_re: &'a [String],
    only_failed: bool,
    show_diff: bool,
    do_copy: bool,
    allow_empty: bool,
    do_fix_missing: bool,
}

/// Run the check-same command. Returns the process exit code.
///
/// `requested` is the (possibly empty) list of rule names from `--checks`;
/// `requested_re` the (possibly empty) list of regexes from `--checks-re`.
/// Both empty → run all enabled rules. Otherwise → run exactly the rules named
/// by `--checks` (in request order) plus, in config order, every rule whose
/// name a regex matches (unanchored search), even if they are `enabled = false`.
/// Any unknown name, invalid regex, or regex matching no rule is a hard error.
///
/// Passing rules print an `ok (N files)` line by default; `only_failed` (and
/// `--terse`) restrict the output to failing rules.
///
/// A rule that matches no files at all fails ("no files matched") unless
/// `allow_empty` is set, in which case it passes as `ok (0 files)`.
///
/// When `copy` is set, interactive prompts are served. In that mode the overall
/// exit code is always 0 regardless of mismatches — `--copy` is a tool to fix
/// drift, not a pass/fail check.
///
/// With the global `--short-circuit` flag, evaluation stops as soon as the first
/// rule is found broken: the remaining rules are neither evaluated nor reported.
fn run_check_same(
    app: &AppConfig,
    file_config: &commands::check::CheckConfig,
    projects: &[std::path::PathBuf],
    opts: &CheckSameOpts<'_>,
) -> Result<i32> {
    use commands::check;
    use commands::interactive;

    let &CheckSameOpts {
        requested,
        requested_re,
        only_failed,
        show_diff,
        do_copy,
        allow_empty,
        do_fix_missing,
    } = opts;

    let rules: Vec<&check::Rule> = if requested.is_empty() && requested_re.is_empty() {
        file_config.check.iter().filter(|r| r.enabled).collect()
    } else {
        let known: std::collections::HashSet<&str> =
            file_config.check.iter().map(|r| r.name.as_str()).collect();
        let unknown: Vec<&String> = requested
            .iter()
            .filter(|name| !known.contains(name.as_str()))
            .collect();
        if !unknown.is_empty() {
            let joined = unknown
                .iter()
                .map(|s| format!("{s:?}"))
                .collect::<Vec<_>>()
                .join(", ");
            anyhow::bail!("unknown check name(s): {joined}");
        }
        let mut selected: Vec<&check::Rule> = requested
            .iter()
            .filter_map(|name| file_config.check.iter().find(|r| &r.name == name))
            .collect();
        for pattern in requested_re {
            let re = regex_lite::Regex::new(pattern)
                .with_context(|| format!("invalid check regex {pattern:?}"))?;
            let mut matched_any = false;
            for rule in &file_config.check {
                if re.is_match(&rule.name) {
                    matched_any = true;
                    if !selected.iter().any(|r| r.name == rule.name) {
                        selected.push(rule);
                    }
                }
            }
            if !matched_any {
                anyhow::bail!("check regex {pattern:?} matches no check name");
            }
        }
        selected
    };

    if rules.is_empty() {
        if app.verbose {
            println!("no rules to check");
        }
        return Ok(0);
    }

    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    let mut any_mismatch = false;
    let mut quit_requested = false;

    for rule in rules {
        if quit_requested {
            break;
        }
        let result = check::evaluate_rule(rule, projects)?;
        if result.matched_nothing() && !allow_empty {
            // A rule that checked nothing is almost always a stale select/path,
            // so it fails by default; --allow-empty restores the old "ok (0
            // files)" behavior.
            any_mismatch = true;
            if app.terse {
                println!("{}", result.name);
                if app.short_circuit {
                    break;
                }
                continue;
            }
            if !app.no_header {
                println!("[{}]", result.name);
            }
            let suffix = if result.skipped.is_empty() {
                String::new()
            } else {
                format!(" ({} skipped)", result.skipped.len())
            };
            println!("no files matched{suffix}");
            if app.short_circuit {
                break;
            }
            continue;
        }
        if result.is_consistent() {
            // Passing rules are reported by default; --only-failed suppresses
            // them, as does --terse (whose output is a machine-readable list
            // of failing rule names).
            if !only_failed && !app.terse {
                if !app.no_header {
                    println!("[{}]", result.name);
                }
                println!("ok ({} files)", result.total_files);
            }
            continue;
        }

        any_mismatch = true;

        if app.terse {
            println!("{}", result.name);
            if app.short_circuit {
                break;
            }
            continue;
        }

        if !app.no_header {
            println!("[{}]", result.name);
        }
        let mut suffix_parts: Vec<String> = Vec::new();
        if !result.must_have_violations.is_empty() {
            suffix_parts.push(format!("{} missing", result.must_have_violations.len()));
        }
        if !result.skipped.is_empty() {
            suffix_parts.push(format!("{} skipped", result.skipped.len()));
        }
        let suffix = if suffix_parts.is_empty() {
            String::new()
        } else {
            format!(" ({})", suffix_parts.join(", "))
        };
        println!(
            "{} files, {} groups{suffix}",
            result.total_files,
            result.groups.len(),
        );
        if !app.no_output {
            for (i, group) in result.groups.iter().enumerate() {
                let label = interactive::group_label(i);
                println!("  group {label} ({} files):", group.len());
                for file in group {
                    println!("    {}", file.display());
                }
            }

            if !result.must_have_violations.is_empty() {
                println!("  missing in:");
                for repo in &result.must_have_violations {
                    println!("    {}", repo.display());
                }
            }

            if show_diff {
                match run_diff(&result, &mut stdin.lock(), &mut stdout.lock())? {
                    FlowControl::Quit => {
                        quit_requested = true;
                        continue;
                    }
                    FlowControl::Continue => {}
                }
            }

            if do_copy {
                match run_copy(&result, &mut stdin.lock(), &mut stdout.lock())? {
                    FlowControl::Quit => {
                        quit_requested = true;
                        continue;
                    }
                    FlowControl::Continue => {}
                }
            }

            if do_fix_missing && !result.must_have_violations.is_empty() {
                match run_fix_missing(&result, &mut stdin.lock(), &mut stdout.lock())? {
                    FlowControl::Quit => {
                        quit_requested = true;
                        continue;
                    }
                    FlowControl::Continue => {}
                }
            }
        }

        if app.short_circuit {
            break;
        }
    }

    if do_copy || do_fix_missing {
        Ok(0)
    } else {
        Ok(if any_mismatch { 1 } else { 0 })
    }
}

#[derive(Debug, PartialEq, Eq)]
enum FlowControl {
    Continue,
    Quit,
}

/// Run the diff flow for a rule with at least two content groups.
/// - 2 groups: auto-pair and diff, no prompting.
/// - 3+ groups: prompt for from/to, diff, then offer to diff another pair.
fn run_diff<R: std::io::BufRead, W: std::io::Write>(
    result: &commands::check::RuleResult,
    reader: &mut R,
    writer: &mut W,
) -> Result<FlowControl> {
    use commands::interactive::{Choice, confirm, pick_group};

    let n = result.groups.len();
    if n == 2 {
        emit_pair_diff(result, 0, 1, writer);
        return Ok(FlowControl::Continue);
    }

    loop {
        let from = match pick_group(&mut *reader, &mut *writer, "diff from group?", n, None)? {
            Choice::Value(i) => i,
            Choice::Skip => return Ok(FlowControl::Continue),
            Choice::Quit => return Ok(FlowControl::Quit),
        };
        let to = match pick_group(&mut *reader, &mut *writer, "diff to group?", n, Some(from))? {
            Choice::Value(i) => i,
            Choice::Skip => return Ok(FlowControl::Continue),
            Choice::Quit => return Ok(FlowControl::Quit),
        };
        emit_pair_diff(result, from, to, writer);

        if !confirm(&mut *reader, &mut *writer, "diff another pair?")? {
            return Ok(FlowControl::Continue);
        }
    }
}

/// Write a unified diff between representatives of `groups[a]` and `groups[b]`
/// to `writer`. Handles I/O errors and non-UTF-8 content gracefully.
fn emit_pair_diff<W: std::io::Write>(
    result: &commands::check::RuleResult,
    a_idx: usize,
    b_idx: usize,
    writer: &mut W,
) {
    let a = &result.groups[a_idx][0];
    let b = &result.groups[b_idx][0];

    let a_bytes = match std::fs::read(a) {
        Ok(b) => b,
        Err(e) => {
            let _ = writeln!(writer, "  (could not read {}: {e})", a.display());
            return;
        }
    };
    let b_bytes = match std::fs::read(b) {
        Ok(b) => b,
        Err(e) => {
            let _ = writeln!(writer, "  (could not read {}: {e})", b.display());
            return;
        }
    };
    let (a_text, b_text) = match (std::str::from_utf8(&a_bytes), std::str::from_utf8(&b_bytes)) {
        (Ok(a), Ok(b)) => (a, b),
        _ => {
            let _ = writeln!(writer, "  (binary files differ, not shown)");
            return;
        }
    };

    let diff = similar::TextDiff::from_lines(a_text, b_text);
    let _ = write!(
        writer,
        "{}",
        diff.unified_diff()
            .context_radius(3)
            .header(&a.display().to_string(), &b.display().to_string())
    );
}

/// Run the interactive copy flow for a rule: prompt for "from" and "to" groups,
/// confirm, then overwrite every file in the "to" group with the content of a
/// representative from the "from" group (preserving the destination's mode).
fn run_copy<R: std::io::BufRead, W: std::io::Write>(
    result: &commands::check::RuleResult,
    reader: &mut R,
    writer: &mut W,
) -> Result<FlowControl> {
    use commands::interactive::{Choice, confirm, group_label, pick_group};

    let n = result.groups.len();
    let from = match pick_group(&mut *reader, &mut *writer, "copy from group?", n, None)? {
        Choice::Value(i) => i,
        Choice::Skip => return Ok(FlowControl::Continue),
        Choice::Quit => return Ok(FlowControl::Quit),
    };
    let to = match pick_group(&mut *reader, &mut *writer, "copy to group?", n, Some(from))? {
        Choice::Value(i) => i,
        Choice::Skip => return Ok(FlowControl::Continue),
        Choice::Quit => return Ok(FlowControl::Quit),
    };

    let src = &result.groups[from][0];
    let dst_group = &result.groups[to];
    let prompt = format!(
        "overwrite {} file(s) in group {} with content from {}?",
        dst_group.len(),
        group_label(to),
        src.display()
    );
    if !confirm(&mut *reader, &mut *writer, &prompt)? {
        let _ = writeln!(writer, "  (skipped)");
        return Ok(FlowControl::Continue);
    }

    for dst in dst_group {
        if let Err(e) = copy_preserving_mode(src, dst) {
            let _ = writeln!(
                writer,
                "  error: {} -> {}: {e}",
                src.display(),
                dst.display()
            );
        } else {
            let _ = writeln!(writer, "  copied -> {}", dst.display());
        }
    }
    Ok(FlowControl::Continue)
}

/// `fs::copy` replaces the destination's permissions with the source's. We want
/// the opposite — overwrite the *content* but keep the destination's mode.
fn copy_preserving_mode(src: &std::path::Path, dst: &std::path::Path) -> Result<()> {
    let original_mode = std::fs::metadata(dst)
        .with_context(|| format!("failed to stat {}", dst.display()))?
        .permissions();
    std::fs::copy(src, dst)
        .with_context(|| format!("failed to copy {} -> {}", src.display(), dst.display()))?;
    std::fs::set_permissions(dst, original_mode)
        .with_context(|| format!("failed to restore permissions on {}", dst.display()))?;
    Ok(())
}

/// Run the interactive fix-missing flow for a rule that has `must_have`
/// violations. Prompts for a "seed" group to copy from, then creates the file
/// in each violating repo, using plain `fs::copy` (so the new file inherits the
/// source's mode). Parent directories are created as needed.
///
/// When the rule has zero content groups (no repo has the file at all) there's
/// nothing to seed from — print a note and skip.
fn run_fix_missing<R: std::io::BufRead, W: std::io::Write>(
    result: &commands::check::RuleResult,
    reader: &mut R,
    writer: &mut W,
) -> Result<FlowControl> {
    use commands::interactive::{Choice, confirm, pick_group};

    if result.groups.is_empty() {
        let _ = writeln!(
            writer,
            "  (cannot --fix-missing: no repo has {} — nothing to seed from)",
            result.path
        );
        return Ok(FlowControl::Continue);
    }

    let n = result.groups.len();
    let from = match pick_group(
        &mut *reader,
        &mut *writer,
        "seed missing files from which group?",
        n,
        None,
    )? {
        Choice::Value(i) => i,
        Choice::Skip => return Ok(FlowControl::Continue),
        Choice::Quit => return Ok(FlowControl::Quit),
    };

    let src = &result.groups[from][0];
    let violators = &result.must_have_violations;
    let prompt = format!(
        "create {} file(s) using content from {}?",
        violators.len(),
        src.display()
    );
    if !confirm(&mut *reader, &mut *writer, &prompt)? {
        let _ = writeln!(writer, "  (skipped)");
        return Ok(FlowControl::Continue);
    }

    for repo in violators {
        let dst = repo.join(&result.path);
        if let Some(parent) = dst.parent()
            && let Err(e) = std::fs::create_dir_all(parent)
        {
            let _ = writeln!(
                writer,
                "  error: failed to create directory {}: {e}",
                parent.display()
            );
            continue;
        }
        match std::fs::copy(src, &dst) {
            Ok(_) => {
                let _ = writeln!(writer, "  created -> {}", dst.display());
            }
            Err(e) => {
                let _ = writeln!(
                    writer,
                    "  error: {} -> {}: {e}",
                    src.display(),
                    dst.display()
                );
            }
        }
    }
    Ok(FlowControl::Continue)
}