gkit 0.3.0

gkit — a transparent git/ssh toolkit: ssh keys, hooked clone, log-off check, stmb
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
//! gkit — a transparent git/ssh toolkit.
//!
//! Noun-style subcommands over `gkit-core`: `clone` (config-driven, hooked),
//! `logoff` (the log-off gate), `stmb` (switch-to-main-branch,
//! recursive + safe), `key` (ssh keys). Mutating actions support `--dry-run` and
//! confirm before acting (skip with `--yes`).

use clap::{Args, Parser, Subcommand};
use gkit_core::git::{Git, SystemGit};
use gkit_core::{checks, clone, conf, config, key, report, stmb, submodules};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};

#[derive(Parser)]
#[command(name = "gkit", version, about = "A transparent git/ssh toolkit", long_about = None)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Write a starter clone conf in the current directory (host/namespace inferred
    /// from origin when possible).
    Init(InitArgs),
    /// Clone repos from a conf file (built-in submodule branch-switch + direnv trust).
    Clone(CloneArgs),
    /// Log-off check: is every repo + submodule committed and pushed? (exit 0 = clear)
    Logoff(LogoffArgs),
    /// Switch to the base branch, update it, and delete the finished feature branch
    /// — recursively across submodules, with safe (merged-only) deletion.
    Stmb(StmbArgs),
    /// Manage ssh keys / identities (the gkit-owned ~/.ssh/git_users).
    Key(KeyArgs),
}

fn main() -> ExitCode {
    match Cli::parse().cmd {
        Cmd::Init(a) => init_cmd(a),
        Cmd::Clone(a) => clone_cmd(a),
        Cmd::Logoff(a) => logoff_cmd(a),
        Cmd::Stmb(a) => stmb_cmd(a),
        Cmd::Key(a) => key_cmd(a),
    }
}

// ---------------------------------------------------------------- init

#[derive(Args)]
struct InitArgs {
    /// File to create (default: repos.toml in the current directory).
    #[arg(default_value = "repos.toml")]
    file: String,
    /// Overwrite if the file already exists.
    #[arg(long)]
    force: bool,
}

fn init_cmd(args: InitArgs) -> ExitCode {
    let path = PathBuf::from(&args.file);
    if path.exists() && !args.force {
        return die(&format!(
            "{} already exists (use --force to overwrite)",
            args.file
        ));
    }
    // Best-effort: infer host/namespace from the current repo's origin.
    let origin = SystemGit.run(Path::new("."), &["remote", "get-url", "origin"]);
    let parts = if origin.success {
        conf::scp_url_parts(origin.trimmed())
    } else {
        None
    };
    let (host, ns) = match &parts {
        Some((h, n)) => (Some(h.as_str()), Some(n.as_str())),
        None => (None, None),
    };
    let text = conf::template(host, ns);
    if let Err(e) = std::fs::write(&path, &text) {
        return die(&format!("cannot write {}: {e}", args.file));
    }
    println!("created {}", args.file);
    match parts {
        Some((h, n)) => println!("  host/namespace inferred from origin: {h}:{n}"),
        None => println!("  fill in `host` and `namespace`, then add [[repo]] blocks"),
    }
    ExitCode::SUCCESS
}

// ---------------------------------------------------------------- clone

#[derive(Args)]
struct CloneArgs {
    /// Conf file(s) to clone from (e.g. `repos.toml` or `*.toml`). At least one is
    /// required; a directory is not accepted — use a shell glob like `confs/*.toml`.
    paths: Vec<String>,
    /// Don't switch submodules onto their .gitmodules branch (leave detached).
    #[arg(long)]
    no_submodule_branch: bool,
    /// Don't `direnv allow` cloned repos that have an .envrc.
    #[arg(long)]
    no_direnv: bool,
}

/// Resolve explicit conf-file arguments to a de-duplicated list. At least one is
/// required, and each must be a file — a directory is rejected; use a shell glob
/// like `*.toml` for "every conf here". Shared by `clone` and `logoff --conf` so
/// both accept conf paths identically.
fn resolve_confs(paths: &[String]) -> Result<Vec<PathBuf>, String> {
    if paths.is_empty() {
        return Err("need at least one conf file, e.g. `repos.toml` or `*.toml`".into());
    }
    let mut out: Vec<PathBuf> = Vec::new();
    for p in paths {
        let pb = PathBuf::from(p);
        if pb.is_dir() {
            return Err(format!(
                "`{p}` is a directory — pass conf file(s), e.g. `{}/*.toml`",
                p.trim_end_matches('/')
            ));
        }
        out.push(pb);
    }
    out.dedup();
    Ok(out)
}

fn clone_cmd(args: CloneArgs) -> ExitCode {
    let confs = match resolve_confs(&args.paths) {
        Ok(c) => c,
        Err(e) => return die(&e),
    };
    let opts = clone::Opts {
        submodule_branch: !args.no_submodule_branch,
        direnv: !args.no_direnv,
    };

    let mut failed = false;
    for conf_path in &confs {
        if confs.len() > 1 {
            println!("== {} ==", conf_path.display());
        }
        let text = match std::fs::read_to_string(conf_path) {
            Ok(t) => t,
            Err(e) => {
                eprintln!("gkit: cannot read conf `{}`: {e}", conf_path.display());
                failed = true;
                continue;
            }
        };
        let cfg = match conf::parse(&text) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("gkit: {}: {e}", conf_path.display());
                failed = true;
                continue;
            }
        };
        // Fail before cloning anything if a repo can't resolve a namespace.
        if let Err(e) = cfg.validate() {
            eprintln!("gkit: {}: {e}", conf_path.display());
            failed = true;
            continue;
        }
        // clone_all prints each step in order (commands, hooks, status).
        let reports = clone::clone_all(&SystemGit, &cfg, &opts);
        if reports
            .iter()
            .any(|r| matches!(r.outcome, clone::Outcome::Failed(_)))
        {
            failed = true;
        }
    }

    if failed {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

// ---------------------------------------------------------------- logoff

#[derive(Args)]
struct LogoffArgs {
    /// Repo path(s) to check (default: the current directory) — or, with --conf,
    /// the clone conf file(s) to read.
    paths: Vec<String>,
    /// Treat the args as clone confs and check every repo listed in them. Takes
    /// explicit conf file(s) (e.g. `*.toml`), from any dir; a directory is not
    /// accepted.
    #[arg(long)]
    conf: bool,
    /// Per-check breakdown (one fact per line, path-first, greppable).
    #[arg(short, long)]
    verbose: bool,
    /// Skip fetching submodules before checking (faster / offline).
    #[arg(long)]
    no_fetch: bool,
    /// Override the base branch (root only). Otherwise: gkit.baseBranch, then
    /// remote origin/main or origin/master.
    #[arg(long)]
    base_branch: Option<String>,
}

fn logoff_cmd(args: LogoffArgs) -> ExitCode {
    let git = SystemGit;
    let mut failed = false;

    // Collect the repo dirs to check: either each conf's repos, or the paths as-is.
    let mut dirs: Vec<PathBuf> = Vec::new();
    if args.conf {
        let confs = match resolve_confs(&args.paths) {
            Ok(c) => c,
            Err(e) => return die(&e),
        };
        for conf_path in &confs {
            if confs.len() > 1 {
                println!("== {} ==", conf_path.display());
            }
            let cfg = match std::fs::read_to_string(conf_path)
                .map_err(|e| e.to_string())
                .and_then(|t| conf::parse(&t))
            {
                Ok(c) => c,
                Err(e) => {
                    eprintln!("gkit: {}: {e}", conf_path.display());
                    failed = true;
                    continue;
                }
            };
            for r in &cfg.repo {
                dirs.push(PathBuf::from(conf::expand_path(&r.dir, |k| {
                    std::env::var(k).ok()
                })));
            }
        }
    } else {
        let srcs: Vec<String> = if args.paths.is_empty() {
            vec![".".into()]
        } else {
            args.paths.clone()
        };
        dirs = srcs.iter().map(|p| canonical(p)).collect();
    }

    for dir in &dirs {
        // In conf mode each repo resolves its own base (gkit.baseBranch -> remote).
        let base = if args.conf {
            None
        } else {
            args.base_branch.as_deref()
        };
        let entries = submodules::evaluate_tree(&git, dir, base, !args.no_fetch);
        if args.verbose {
            report::print_verbose(&entries);
        } else {
            report::print_default(&entries);
        }
        if !report::all_ok(&entries) {
            failed = true;
        }
    }

    if failed {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

// ---------------------------------------------------------------- stmb

#[derive(Args)]
struct StmbArgs {
    /// Repository path (defaults to the current directory).
    #[arg(default_value = ".")]
    path: String,
    /// Base branch to switch to (root only). Otherwise: gkit.baseBranch, then origin/HEAD.
    #[arg(long)]
    base: Option<String>,
    /// Only the top repo; don't recurse into submodules.
    #[arg(long)]
    no_recursive: bool,
    /// Force-delete the feature branch even if not fully merged (may lose commits).
    #[arg(long)]
    force: bool,
    /// Skip the confirmation prompt.
    #[arg(short = 'y', long)]
    yes: bool,
    /// Show the plan without making changes.
    #[arg(long)]
    dry_run: bool,
}

enum Step {
    Switch {
        dir: PathBuf,
        base: String,
        feature: Option<String>,
    },
    Skip {
        dir: PathBuf,
        why: String,
    },
}

fn stmb_cmd(args: StmbArgs) -> ExitCode {
    let git = SystemGit;
    let root = canonical(&args.path);
    let repos = if args.no_recursive {
        vec![root.clone()]
    } else {
        submodules::repo_paths(&git, &root)
    };

    // Resolve ONE base for the whole tree (uniform convention) — avoids mis-resolving
    // a submodule's base and treating an integration branch as a deletable feature.
    let base = match config::resolve_switch_base(&git, &root, args.base.as_deref()) {
        Some(b) => b,
        None => return die("cannot determine base branch — pass --base <branch>"),
    };

    let steps: Vec<Step> = repos
        .iter()
        .map(|dir| {
            let cur = config::current_branch_opt(&git, dir);
            let dirty = !checks::committed(&git, dir);
            match stmb::plan(cur.as_deref(), &base, dirty) {
                Ok(p) => Step::Switch {
                    dir: dir.clone(),
                    base: p.base,
                    feature: p.delete_feature,
                },
                Err(why) => Step::Skip {
                    dir: dir.clone(),
                    why,
                },
            }
        })
        .collect();

    println!("stmb plan ({} repo(s)):", steps.len());
    for s in &steps {
        match s {
            Step::Switch { dir, base, feature } => {
                let del = feature
                    .as_deref()
                    .map(|f| format!(", delete '{f}'"))
                    .unwrap_or_default();
                println!("  {}  -> switch to '{base}', pull{del}", short(dir, &root));
            }
            Step::Skip { dir, why } => println!("  {}  -- skip: {why}", short(dir, &root)),
        }
    }

    if args.dry_run {
        return ExitCode::SUCCESS;
    }
    if !args.yes && !confirm("Proceed?") {
        println!("aborted.");
        return ExitCode::SUCCESS;
    }

    let mut failed = false;
    for s in &steps {
        if let Step::Switch { dir, base, feature } = s {
            println!("{}:", short(dir, &root));
            if let Err(e) = run_stmb(&git, dir, base, feature.as_deref(), args.force) {
                eprintln!("gkit stmb: {}: {e}", short(dir, &root));
                failed = true;
            }
        }
    }

    // Verify with a (recursive) log-off check on the root.
    println!("\n--- logoff ---");
    let entries = submodules::evaluate_tree(&git, &root, None, false);
    report::print_default(&entries);
    if failed || !report::all_ok(&entries) {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

fn run_stmb(
    git: &SystemGit,
    dir: &Path,
    base: &str,
    feature: Option<&str>,
    force: bool,
) -> Result<(), String> {
    // Print each git command before running it (transparency, like `clone`).
    let run = |args: &[&str]| {
        println!("  + git {}", args.join(" "));
        git.run(dir, args)
    };
    let co = run(&["checkout", base]);
    if !co.success {
        return Err(format!("checkout {base} failed: {}", co.stderr.trim()));
    }
    let _ = run(&["pull", "--rebase", "origin", base]);
    if let Some(f) = feature {
        let del = run(&["branch", "-d", f]);
        if !del.success {
            if force {
                let force_del = run(&["branch", "-D", f]);
                if !force_del.success {
                    return Err(format!(
                        "force-delete '{f}' failed: {}",
                        force_del.stderr.trim()
                    ));
                }
            } else {
                return Err(format!(
                    "'{f}' not fully merged into {base}; rerun with --force to delete anyway"
                ));
            }
        }
    }
    let _ = run(&["remote", "prune", "origin"]);
    Ok(())
}

// ---------------------------------------------------------------- key

#[derive(Args)]
struct KeyArgs {
    #[command(subcommand)]
    action: KeyAction,
}

#[derive(Subcommand)]
enum KeyAction {
    /// Generate id_<alias>, add an ssh Host block to ~/.ssh/git_users, ssh-add it.
    Add(KeyAddArgs),
    /// Copy id_<alias>.pub to the clipboard.
    Copy { alias: String },
    /// List the Host aliases gkit owns in ~/.ssh/git_users.
    List,
}

#[derive(Args)]
struct KeyAddArgs {
    /// Alias = ssh Host = key name (~/.ssh/id_<alias>).
    alias: String,
    /// Email comment for the key.
    #[arg(long)]
    email: String,
    /// Provider hostname.
    #[arg(long, default_value = "github.com")]
    host: String,
    /// SSH port (omit for default 22).
    #[arg(long)]
    port: Option<u16>,
    /// Show the plan without making changes.
    #[arg(long)]
    dry_run: bool,
    /// Skip the confirmation prompt.
    #[arg(short = 'y', long)]
    yes: bool,
}

fn key_cmd(args: KeyArgs) -> ExitCode {
    match args.action {
        KeyAction::Add(a) => key_add(a),
        KeyAction::Copy { alias } => key_copy(&alias),
        KeyAction::List => key_list(),
    }
}

fn ssh_dir() -> PathBuf {
    // Cross-OS home: HOME (Unix/macOS) → USERPROFILE / HOMEDRIVE+HOMEPATH (Windows).
    key::home_from_env(|k| std::env::var(k).ok())
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".ssh")
}

fn key_add(a: KeyAddArgs) -> ExitCode {
    let ssh = ssh_dir();
    let key_path = ssh.join(format!("id_{}", a.alias));
    let git_users = ssh.join("git_users");
    let ssh_config = ssh.join("config");
    let macos = cfg!(target_os = "macos");

    let block = key::host_block(&a.alias, &a.host, a.port, macos);
    let existing_gu = std::fs::read_to_string(&git_users).unwrap_or_default();
    let new_gu = key::upsert_block(&existing_gu, &a.alias, &block);
    let existing_cfg = std::fs::read_to_string(&ssh_config).unwrap_or_default();
    let new_cfg = key::ensure_include(&existing_cfg);
    let need_keygen = !key_path.exists();

    println!("gkit key add '{}':", a.alias);
    if need_keygen {
        println!(
            "  ssh-keygen -t ed25519 -C {} -f {}",
            a.email,
            key_path.display()
        );
    } else {
        println!("  (key {} already exists — keeping it)", key_path.display());
    }
    println!("  upsert Host block into {}:", git_users.display());
    for l in block.lines() {
        println!("      {l}");
    }
    match &new_cfg {
        Some(_) => println!(
            "  ensure `Include git_users` in {} (asks first)",
            ssh_config.display()
        ),
        None => println!(
            "  (`Include git_users` already present in {})",
            ssh_config.display()
        ),
    }
    println!("  ssh-add the key, then copy the public key to the clipboard");

    if a.dry_run {
        return ExitCode::SUCCESS;
    }
    if !a.yes && !confirm("Proceed?") {
        println!("aborted.");
        return ExitCode::SUCCESS;
    }

    if let Err(e) = std::fs::create_dir_all(&ssh) {
        return die(&format!("cannot create {}: {e}", ssh.display()));
    }
    if need_keygen {
        // interactive (passphrase) -> inherit stdio
        let st = Command::new("ssh-keygen")
            .args(["-t", "ed25519", "-C", &a.email, "-f"])
            .arg(&key_path)
            .status();
        if !matches!(st, Ok(s) if s.success()) {
            return die("ssh-keygen failed");
        }
    }
    if let Err(e) = std::fs::write(&git_users, &new_gu) {
        return die(&format!("cannot write {}: {e}", git_users.display()));
    }
    // The sensitive edit is to the user's OWN ~/.ssh/config — check for the
    // `Include git_users` line, explain why it matters, and ask before touching it.
    match new_cfg {
        None => println!(
            "✓ `Include git_users` already present in {}",
            ssh_config.display()
        ),
        Some(c) => {
            println!(
                "! {} does not `Include git_users` — without it, ssh ignores the Host",
                ssh_config.display()
            );
            println!("  block(s) gkit manages in {}.", git_users.display());
            if a.yes
                || confirm(&format!(
                    "Add `Include git_users` to {}?",
                    ssh_config.display()
                ))
            {
                if let Err(e) = std::fs::write(&ssh_config, c) {
                    return die(&format!("cannot write {}: {e}", ssh_config.display()));
                }
                println!("  added `Include git_users`.");
            } else {
                println!(
                    "  skipped — add `Include git_users` to {} yourself to activate the key.",
                    ssh_config.display()
                );
            }
        }
    }

    let mut add = Command::new("ssh-add");
    if macos {
        add.arg("--apple-use-keychain");
    }
    let _ = add.arg(&key_path).status();

    // Copy the public key to the clipboard, ready to paste into the provider.
    let pubfile = key_path.with_extension("pub");
    match std::fs::read_to_string(&pubfile) {
        Ok(pubkey) => match clipboard_copy(&pubkey) {
            Some(tool) => {
                println!(
                    "done. id_{}.pub copied to clipboard ({tool}) — paste it into {}.",
                    a.alias, a.host
                )
            }
            None => {
                println!("done. public key (upload to {}):", a.host);
                print!("{pubkey}");
            }
        },
        Err(e) => println!("done, but cannot read {}: {e}", pubfile.display()),
    }
    ExitCode::SUCCESS
}

fn key_copy(alias: &str) -> ExitCode {
    let pubfile = ssh_dir().join(format!("id_{alias}.pub"));
    let pubkey = match std::fs::read_to_string(&pubfile) {
        Ok(k) => k,
        Err(e) => return die(&format!("cannot read {}: {e}", pubfile.display())),
    };
    match clipboard_copy(&pubkey) {
        Some(tool) => println!("copied id_{alias}.pub to clipboard ({tool})"),
        None => print!("{pubkey}"),
    }
    ExitCode::SUCCESS
}

/// Copy `text` to the OS clipboard via the first available per-OS tool
/// (pbcopy / clip / wl-copy|xclip|xsel). Returns the tool that succeeded, or
/// `None` if no clipboard tool is available (caller then prints the text).
fn clipboard_copy(text: &str) -> Option<&'static str> {
    for (prog, pargs) in key::clipboard_candidates(std::env::consts::OS) {
        let Ok(mut child) = Command::new(prog)
            .args(&pargs)
            .stdin(std::process::Stdio::piped())
            .spawn()
        else {
            continue;
        };
        if let Some(mut stdin) = child.stdin.take() {
            let _ = stdin.write_all(text.as_bytes());
        }
        if child.wait().map(|s| s.success()).unwrap_or(false) {
            return Some(prog);
        }
    }
    None
}

fn key_list() -> ExitCode {
    let git_users = ssh_dir().join("git_users");
    let content = std::fs::read_to_string(&git_users).unwrap_or_default();
    let hosts = key::list_hosts(&content);
    if hosts.is_empty() {
        println!("(no Host blocks in {})", git_users.display());
    } else {
        for (alias, identity) in hosts {
            println!("{alias:<20} {identity}");
        }
    }
    ExitCode::SUCCESS
}

// ---------------------------------------------------------------- helpers

fn canonical(p: &str) -> PathBuf {
    std::fs::canonicalize(p).unwrap_or_else(|_| PathBuf::from(p))
}

fn short(dir: &Path, root: &Path) -> String {
    dir.strip_prefix(root)
        .ok()
        .filter(|p| !p.as_os_str().is_empty())
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| ".".to_string())
}

fn confirm(msg: &str) -> bool {
    print!("{msg} [y/N]: ");
    let _ = std::io::stdout().flush();
    let mut s = String::new();
    let _ = std::io::stdin().read_line(&mut s);
    matches!(s.trim(), "y" | "Y" | "yes" | "Yes")
}

fn die(msg: &str) -> ExitCode {
    eprintln!("gkit: {msg}");
    ExitCode::from(2)
}

#[cfg(test)]
mod tests {
    use super::resolve_confs;
    use std::fs;
    use std::path::PathBuf;

    // `clone` and `logoff --conf` accept ONLY explicit conf file(s): at least one
    // is required, a directory is rejected (use a `*.toml` shell glob instead), and
    // explicit files are kept in order, deduped.
    //
    // Assertions compare Ok/Err and file *names* (not full PathBufs), which is
    // robust to OS path normalization (Windows verbatim/short-name prefixes).
    #[test]
    fn resolve_confs_requires_explicit_files() {
        let base = std::env::temp_dir().join(format!("gkit-rc-{}", std::process::id()));
        let _ = fs::remove_dir_all(&base); // clear any stale leftovers from a prior run
        fs::create_dir_all(&base).unwrap();
        let a = base.join("a.toml");
        let b = base.join("b.toml");
        fs::write(&a, "").unwrap();
        fs::write(&b, "").unwrap();

        let s = |p: &std::path::Path| p.to_string_lossy().into_owned();
        let names = |r: Result<Vec<PathBuf>, String>| {
            r.unwrap()
                .iter()
                .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
                .collect::<Vec<_>>()
        };

        // no args -> error (no cwd default)
        assert!(resolve_confs(&[]).is_err());

        // a directory -> error (no expansion)
        assert!(resolve_confs(&[s(&base)]).is_err());

        // explicit files -> kept in order, deduped
        assert_eq!(names(resolve_confs(&[s(&a), s(&b)])), ["a.toml", "b.toml"]);
        assert_eq!(names(resolve_confs(&[s(&a), s(&a)])), ["a.toml"]);

        let _ = fs::remove_dir_all(&base);
    }
}