gvsn 1.0.1

A fast, cross-platform Go version manager written in Rust
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
//! `gvsn doctor` - diagnose the gvsn environment.
//!
//! Runs a series of checks and reports the result of each one. Exits with
//! status code `1` if any check fails, making the command suitable for CI
//! health checks and pre-commit hooks.
//!
//! # Checks performed
//!
//! 1. The `gvsn` binary directory is on `PATH`.
//! 2. A global Go version has been set.
//! 3. The global version is installed on disk.
//! 4. `GOROOT` resolves to the correct directory.
//! 5. The current directory's `.go-version` or `.tool-versions` (if present)
//!    refers to an installed version.
//! 6. The `gvsn env` hook is present in the detected shell's profile.
//! 7. Only one `go` binary is active in `PATH` and it is gvsn-managed.

use anyhow::Result;
use colored::Colorize;

use crate::{commands::setup, config::Config, shell, toolchain, version::GoVersion};

/// Runs all environment checks and prints a summary.
///
/// When `shell_str` is provided it overrides shell auto-detection for the
/// profile check. The function exits the process with code `1` if any issue
/// remains after checking (and, if `fix` is `true`, after attempting repairs).
///
/// When `fix` is `true`, two classes of issue are repaired automatically
/// after the checks run:
/// - A missing/stale shell hook or missing PATH entry (checks 1 and 7) is
///   fixed by running the same logic as `gvsn setup`.
/// - A missing `~/.gvsn/current` junction (check 5) is recreated by
///   re-pointing it at the installed global version, if one is set.
///
/// Everything else (an uninstalled global version, a `.go-version` pointing
/// at an uninstalled version, a shadowed non-gvsn `go` on `PATH`) requires a
/// choice only the user can make (which version, whether to uninstall
/// something) and is never auto-fixed.
///
/// # Errors
///
/// This function only returns `Err` for unexpected I/O failures. Diagnostic
/// failures are reported to stdout and tracked in the `issues` counter rather
/// than being propagated as errors.
pub fn run(config: &Config, shell_str: Option<&str>, fix: bool) -> Result<()> {
    println!("Checking gvsn environment...\n");
    let mut issues = 0u32;
    let go_name = if cfg!(windows) { "go.exe" } else { "go" };

    // ---- Check 1: gvsn binary on PATH ----------------------------------------
    let mut path_issue = false;
    if shell::gvsn_in_path() {
        ok("gvsn binary is in PATH");
    } else {
        let dir = std::env::current_exe()
            .ok()
            .and_then(|p| p.parent().map(|d| d.display().to_string()))
            .unwrap_or_else(|| "<unknown>".to_string());
        fail(&format!("gvsn is NOT in PATH  (add '{dir}' to your PATH)"));
        issues += 1;
        path_issue = true;
    }

    // ---- Check 2 & 3: global version set and installed ----------------------
    let mut installed_global: Option<GoVersion> = None;
    match toolchain::global_version(config) {
        Err(_) => {
            fail("No global Go version set  (run 'gvsn use <version>')");
            issues += 1;
        }
        Ok(v) => {
            ok(&format!("Global version: {}", v.tag().bold()));

            if toolchain::is_installed(config, &v) {
                ok(&format!("{} is installed", v.tag()));

                // ---- Check 4: GOROOT directory exists -----------------------
                let root = config.version_dir(&v.tag());
                ok(&format!("GOROOT -> {}", root.display()));
                installed_global = Some(v);
            } else {
                fail(&format!(
                    "{} is NOT installed  (run 'gvsn install {}')",
                    v.tag(),
                    v.tag()
                ));
                issues += 1;
            }
        }
    }

    // ---- Check 5: ~/.gvsn/current junction is set up -------------------------
    //
    // Users who installed gvsn before v1.1.0 (which introduced the junction)
    // will not have ~/.gvsn/current until they run `gvsn use` with the new
    // binary. Warn them so `go` works in CMD, Git Bash and editors.
    let current_dir = config.current_dir();
    let current_go = current_dir.join("bin").join(go_name);
    let current_link_missing = !current_go.exists();
    if !current_link_missing {
        ok(&format!(
            "~/.gvsn/current junction is configured ({})",
            current_dir.display()
        ));
    } else {
        fail("~/.gvsn/current not set up  (run 'gvsn use <version>' to enable universal shell support)");
        issues += 1;
    }

    // ---- Check 6: local pin file (.go-version / .tool-versions) consistency -
    if let Ok(cwd) = std::env::current_dir() {
        if let Some((raw, source)) = read_local_pin(&cwd) {
            match crate::version::GoVersion::parse(&raw) {
                Ok(v) if toolchain::is_installed(config, &v) => {
                    ok(&format!("{source} = {} (installed)", v.tag()));
                }
                Ok(v) => {
                    warn(&format!(
                        "{source} = {} but NOT installed  (run 'gvsn install {}')",
                        v.tag(),
                        v.tag()
                    ));
                    issues += 1;
                }
                Err(_) => {
                    warn(&format!("{source} contains invalid version: '{raw}'"));
                    issues += 1;
                }
            }
        }
    }

    // ---- Check 7: shell profile contains the gvsn init hook ------------------
    let sh = match shell_str {
        Some(s) => shell::from_str(s).ok(),
        None => shell::detect(),
    };

    let mut profile_issue = false;
    if let Some(sh) = &sh {
        match sh.profile_path() {
            None => warn(&format!("Cannot determine profile path for {}", sh.name())),
            Some(profile) => {
                if profile.exists() {
                    let content = std::fs::read_to_string(&profile).unwrap_or_default();
                    if content.contains("# gvsn init") {
                        ok(&format!("Shell profile configured ({})", profile.display()));
                    } else {
                        fail(&format!(
                            "gvsn init missing from {}  (run 'gvsn setup')",
                            profile.display()
                        ));
                        issues += 1;
                        profile_issue = true;
                    }
                } else {
                    fail(&format!(
                        "Profile not found: {}  (run 'gvsn setup')",
                        profile.display()
                    ));
                    issues += 1;
                    profile_issue = true;
                }
            }
        }
    }

    // ---- Check 8: single, gvsn-managed `go` binary in PATH ------------------
    //
    // Scans every directory in PATH for a `go` (or `go.exe`) executable.
    // Reports a warning when multiple are found (shadowing is confusing) and
    // an error when the first - i.e. the active - one is not managed by gvsn.
    // This is what `whereis go` surfaces on Linux: system-installed Go
    // alongside the gvsn-managed one.
    let path_sep = if cfg!(windows) { ';' } else { ':' };
    let path_var = std::env::var("PATH").unwrap_or_default();
    let versions_dir = config.versions_dir();

    let go_paths = find_go_binaries(&path_var, path_sep, go_name);

    match classify_go_paths(&go_paths, &versions_dir, &current_dir) {
        GoPathStatus::None => {
            // No Go in PATH at all - only relevant if a version is supposed to be active.
        }
        GoPathStatus::SingleManaged(go) => {
            ok(&format!("Active Go is gvsn-managed ({})", go.display()));
        }
        GoPathStatus::SingleUnmanaged(go) => {
            fail(&format!(
                "Active Go is NOT managed by gvsn: {}",
                go.display()
            ));
            println!(
                "    Hint: remove the system Go package or run 'gvsn setup' \
                      so gvsn's PATH entry comes first."
            );
            issues += 1;
        }
        GoPathStatus::MultipleAllManaged(active) => {
            // All extra entries are other gvsn-managed paths (e.g. both the versioned
            // directory and the ~/.gvsn/current junction appear in PATH). Harmless.
            ok(&format!("Active Go is gvsn-managed ({})", active.display()));
        }
        GoPathStatus::MultipleShadowedNonGvsn { shadowed, .. } => {
            warn(&format!(
                "{} Go binaries found in PATH - {} non-gvsn installation(s) are shadowed \
                 (consider removing them to avoid confusion):",
                shadowed.len() + 1,
                shadowed.len()
            ));
            for path in &shadowed {
                println!("    {} (non-gvsn, shadowed)", path.display());
            }
        }
        GoPathStatus::MultipleActiveNotManaged { all } => {
            fail(&format!(
                "{} Go binaries in PATH - gvsn's version is being shadowed:",
                all.len()
            ));
            for (i, path) in all.iter().enumerate() {
                let label = if i == 0 {
                    " (active - NOT gvsn-managed)"
                } else if path.starts_with(&versions_dir) || path.starts_with(&current_dir) {
                    " (gvsn-managed - shadowed)"
                } else {
                    " (shadowed)"
                };
                println!("    {}{label}", path.display());
            }
            println!(
                "    Hint: remove the system Go package or run 'gvsn setup' \
                      to ensure gvsn's PATH entry is first."
            );
            issues += 1;
        }
    }

    // ---- Auto-fix -------------------------------------------------------------
    if fix {
        // Tracks whether any fixable issue was found at all, separately from
        // whether a fix actually succeeded - so the closing message can tell
        // "nothing needed fixing" apart from "something needed fixing, but
        // the attempt failed or couldn't be attempted", which must never be
        // reported as "nothing to auto-fix" right below the error explaining
        // why it wasn't fixed.
        let mut attempted_any = false;
        let mut fixed_any = false;
        println!();

        if path_issue || profile_issue {
            attempted_any = true;
            match &sh {
                Some(sh) => match setup::run(Some(sh.name()), false) {
                    Ok(()) => {
                        println!("  {} Ran 'gvsn setup' for {}.", "->".cyan(), sh.name());
                        if profile_issue {
                            println!("    Shell profile hook fixed.");
                            issues = issues.saturating_sub(1);
                        }
                        if path_issue {
                            println!(
                                "    PATH updated - open a new shell session for it to take effect."
                            );
                        }
                        fixed_any = true;
                    }
                    Err(e) => {
                        println!("  {} Could not run 'gvsn setup': {e:#}", "x".red());
                    }
                },
                None => {
                    println!(
                        "  {} Cannot auto-fix PATH/shell hook: no shell detected.",
                        "!".yellow()
                    );
                }
            }
        }

        if current_link_missing {
            attempted_any = true;
            match &installed_global {
                Some(v) => match toolchain::set_active_version(config, v) {
                    Ok(()) => {
                        println!("  {} Recreated ~/.gvsn/current -> {}", "->".cyan(), v.tag());
                        issues = issues.saturating_sub(1);
                        fixed_any = true;
                    }
                    Err(e) => {
                        println!("  {} Could not recreate ~/.gvsn/current: {e:#}", "x".red());
                    }
                },
                None => {
                    println!(
                        "  {} Cannot auto-fix ~/.gvsn/current: no installed global version set.",
                        "!".yellow()
                    );
                }
            }
        }

        if let Some(msg) = fix_outcome_message(attempted_any, fixed_any) {
            println!("  {msg}");
        }
    }

    // ---- Summary ------------------------------------------------------------
    println!();
    if issues == 0 {
        println!("{} Everything looks good!", "✓".green().bold());
    } else {
        println!("{} {} issue(s) found.", "!".yellow().bold(), issues);
        std::process::exit(1);
    }

    Ok(())
}

// --- Private helpers ---------------------------------------------------------

/// Resolves the local version pin for `dir`, checking `.go-version` first and
/// falling back to the `golang` line of `.tool-versions`. Returns the raw
/// (untrimmed-source, but trimmed here) version string paired with the name
/// of the file it came from, or `None` when neither file pins a version.
///
/// Mirrors [`toolchain::active_version`]'s precedence, but for a single
/// directory (check 6 only cares about the current directory, not the
/// walk-up-to-root resolution `active_version` does) and without the "must
/// error on unreadable file" strictness that function needs - a doctor check
/// is diagnostic, not a resolution path something else depends on.
fn read_local_pin(dir: &std::path::Path) -> Option<(String, &'static str)> {
    let go_version_path = dir.join(crate::version::GO_VERSION_FILE);
    if go_version_path.exists() {
        return std::fs::read_to_string(&go_version_path)
            .ok()
            .map(|raw| (raw.trim().to_string(), ".go-version"));
    }

    let tool_versions_path = dir.join(crate::version::TOOL_VERSIONS_FILE);
    std::fs::read_to_string(&tool_versions_path)
        .ok()
        .and_then(|content| {
            crate::version::parse_tool_versions_golang_line(&content)
                .map(|raw| (raw.to_string(), ".tool-versions"))
        })
}

/// Builds the closing line for the `--fix` section, or `None` when nothing
/// should be printed.
///
/// Distinguishes "no fixable issue was found" from "a fixable issue was
/// found but every repair attempt failed or couldn't be attempted" - the
/// two must never be conflated, since the latter already printed an
/// explanatory error/warning line immediately above that a blanket "nothing
/// to auto-fix" would directly contradict.
fn fix_outcome_message(attempted_any: bool, fixed_any: bool) -> Option<String> {
    if !attempted_any {
        Some(format!("{} Nothing to auto-fix.", "i".cyan()))
    } else if !fixed_any {
        Some(format!(
            "{} Found fixable issue(s), but could not repair any of them - see above.",
            "!".yellow()
        ))
    } else {
        None
    }
}

fn ok(msg: &str) {
    println!("  {} {msg}", "✓".green());
}

fn fail(msg: &str) {
    println!("  {} {msg}", "x".red());
}

fn warn(msg: &str) {
    println!("  {} {msg}", "!".yellow());
}

/// Scans every directory in `path_var` (a PATH-like string, entries separated
/// by `path_sep`) for an executable named `go_name`, in order.
///
/// Pure with respect to the environment - callers pass in the PATH string and
/// separator explicitly rather than reading `std::env::var("PATH")` here, so
/// this function can be exercised with a synthetic PATH in tests.
fn find_go_binaries(path_var: &str, path_sep: char, go_name: &str) -> Vec<std::path::PathBuf> {
    path_var
        .split(path_sep)
        .map(std::path::Path::new)
        .filter_map(|dir| {
            let candidate = dir.join(go_name);
            if candidate.is_file() {
                Some(candidate)
            } else {
                None
            }
        })
        .collect()
}

/// Outcome of classifying the set of `go` binaries found on `PATH` against
/// gvsn's managed directories.
#[derive(Debug, PartialEq, Eq)]
enum GoPathStatus {
    /// No `go` binary found anywhere on `PATH`.
    None,
    /// Exactly one `go` binary, and it is gvsn-managed.
    SingleManaged(std::path::PathBuf),
    /// Exactly one `go` binary, and it is NOT gvsn-managed.
    SingleUnmanaged(std::path::PathBuf),
    /// Multiple `go` binaries, all gvsn-managed (e.g. the versioned directory
    /// and the `current` junction both appear on `PATH`). Harmless.
    MultipleAllManaged(std::path::PathBuf),
    /// Multiple `go` binaries; the active (first) one is gvsn-managed, but one
    /// or more non-gvsn installations are shadowed behind it.
    MultipleShadowedNonGvsn {
        active: std::path::PathBuf,
        shadowed: Vec<std::path::PathBuf>,
    },
    /// Multiple `go` binaries; the active (first) one is NOT gvsn-managed, so
    /// gvsn's own installation is being shadowed.
    MultipleActiveNotManaged { all: Vec<std::path::PathBuf> },
}

/// Classifies `go_paths` (in PATH order) against gvsn's `versions_dir` and
/// `current_dir` to determine what, if anything, is wrong with the active Go
/// binary resolution.
fn classify_go_paths(
    go_paths: &[std::path::PathBuf],
    versions_dir: &std::path::Path,
    current_dir: &std::path::Path,
) -> GoPathStatus {
    let is_managed =
        |p: &std::path::Path| p.starts_with(versions_dir) || p.starts_with(current_dir);

    match go_paths.len() {
        0 => GoPathStatus::None,
        1 => {
            let go = go_paths[0].clone();
            if is_managed(&go) {
                GoPathStatus::SingleManaged(go)
            } else {
                GoPathStatus::SingleUnmanaged(go)
            }
        }
        _ => {
            if is_managed(&go_paths[0]) {
                let shadowed: Vec<_> = go_paths
                    .iter()
                    .skip(1)
                    .filter(|p| !is_managed(p))
                    .cloned()
                    .collect();
                if shadowed.is_empty() {
                    GoPathStatus::MultipleAllManaged(go_paths[0].clone())
                } else {
                    GoPathStatus::MultipleShadowedNonGvsn {
                        active: go_paths[0].clone(),
                        shadowed,
                    }
                }
            } else {
                GoPathStatus::MultipleActiveNotManaged {
                    all: go_paths.to_vec(),
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    fn make_go(dir: &std::path::Path, go_name: &str) -> std::path::PathBuf {
        std::fs::create_dir_all(dir).unwrap();
        let go = dir.join(go_name);
        std::fs::write(&go, b"").unwrap();
        go
    }

    #[test]
    fn read_local_pin_returns_none_when_neither_file_present() {
        let dir = tempdir().unwrap();
        assert_eq!(read_local_pin(dir.path()), None);
    }

    #[test]
    fn read_local_pin_reads_go_version_file() {
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join(".go-version"), "go1.22.4").unwrap();
        assert_eq!(
            read_local_pin(dir.path()),
            Some(("go1.22.4".to_string(), ".go-version"))
        );
    }

    #[test]
    fn read_local_pin_falls_back_to_tool_versions_golang_line() {
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join(".tool-versions"), "golang 1.22.4\n").unwrap();
        assert_eq!(
            read_local_pin(dir.path()),
            Some(("1.22.4".to_string(), ".tool-versions"))
        );
    }

    #[test]
    fn read_local_pin_prefers_go_version_over_tool_versions() {
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join(".go-version"), "go1.21.13").unwrap();
        std::fs::write(dir.path().join(".tool-versions"), "golang 1.22.4\n").unwrap();
        assert_eq!(
            read_local_pin(dir.path()),
            Some(("go1.21.13".to_string(), ".go-version"))
        );
    }

    #[test]
    fn read_local_pin_ignores_tool_versions_without_a_golang_line() {
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join(".tool-versions"), "nodejs 20.11.0\n").unwrap();
        assert_eq!(read_local_pin(dir.path()), None);
    }

    #[test]
    fn fix_outcome_message_is_none_when_a_fix_succeeded() {
        assert_eq!(fix_outcome_message(true, true), None);
    }

    #[test]
    fn fix_outcome_message_reports_nothing_to_fix_when_nothing_was_attempted() {
        let msg = fix_outcome_message(false, false).unwrap();
        assert!(msg.contains("Nothing to auto-fix"));
    }

    #[test]
    fn fix_outcome_message_never_says_nothing_to_fix_when_an_attempt_was_made() {
        // Regression test: an issue was found and an attempt was made (or
        // could not even be attempted, e.g. no shell detected), but nothing
        // was actually fixed. The message must explain that, not claim
        // there was nothing to fix - which would directly contradict the
        // error/warning line already printed above it.
        let msg = fix_outcome_message(true, false).unwrap();
        assert!(!msg.contains("Nothing to auto-fix"));
        assert!(msg.contains("could not repair"));
    }

    #[test]
    fn find_go_binaries_returns_empty_for_empty_path() {
        assert!(find_go_binaries("", ':', "go").is_empty());
    }

    #[test]
    fn find_go_binaries_finds_executables_in_order() {
        // Use a separator that never collides with a Windows drive-letter
        // colon (e.g. `C:\...`) so the test is meaningful on every platform.
        let sep = '|';
        let root = tempdir().unwrap();
        let dir_a = root.path().join("a");
        let dir_b = root.path().join("b");
        let dir_c = root.path().join("c"); // no go binary here
        let go_a = make_go(&dir_a, "go");
        let go_b = make_go(&dir_b, "go");
        std::fs::create_dir_all(&dir_c).unwrap();

        let path_var = format!(
            "{}{sep}{}{sep}{}",
            dir_a.display(),
            dir_c.display(),
            dir_b.display()
        );
        let found = find_go_binaries(&path_var, sep, "go");
        assert_eq!(found, vec![go_a, go_b]);
    }

    #[test]
    fn find_go_binaries_ignores_directories_named_like_the_binary() {
        let root = tempdir().unwrap();
        let dir = root.path().join("bin");
        // Create a directory named "go" instead of a file - should not count.
        std::fs::create_dir_all(dir.join("go")).unwrap();

        let found = find_go_binaries(&dir.display().to_string(), '|', "go");
        assert!(found.is_empty());
    }

    #[test]
    fn classify_empty_is_none() {
        let versions_dir = std::path::Path::new("/gvsn/versions");
        let current_dir = std::path::Path::new("/gvsn/current");
        assert_eq!(
            classify_go_paths(&[], versions_dir, current_dir),
            GoPathStatus::None
        );
    }

    #[test]
    fn classify_single_managed_via_versions_dir() {
        let versions_dir = std::path::Path::new("/gvsn/versions");
        let current_dir = std::path::Path::new("/gvsn/current");
        let go = versions_dir.join("go1.22.4/bin/go");
        assert_eq!(
            classify_go_paths(std::slice::from_ref(&go), versions_dir, current_dir),
            GoPathStatus::SingleManaged(go)
        );
    }

    #[test]
    fn classify_single_managed_via_current_dir() {
        let versions_dir = std::path::Path::new("/gvsn/versions");
        let current_dir = std::path::Path::new("/gvsn/current");
        let go = current_dir.join("bin/go");
        assert_eq!(
            classify_go_paths(std::slice::from_ref(&go), versions_dir, current_dir),
            GoPathStatus::SingleManaged(go)
        );
    }

    #[test]
    fn classify_single_unmanaged() {
        let versions_dir = std::path::Path::new("/gvsn/versions");
        let current_dir = std::path::Path::new("/gvsn/current");
        let go = std::path::PathBuf::from("/usr/local/go/bin/go");
        assert_eq!(
            classify_go_paths(std::slice::from_ref(&go), versions_dir, current_dir),
            GoPathStatus::SingleUnmanaged(go)
        );
    }

    #[test]
    fn classify_multiple_all_managed_is_harmless() {
        let versions_dir = std::path::Path::new("/gvsn/versions");
        let current_dir = std::path::Path::new("/gvsn/current");
        let go1 = current_dir.join("bin/go");
        let go2 = versions_dir.join("go1.22.4/bin/go");
        assert_eq!(
            classify_go_paths(&[go1.clone(), go2], versions_dir, current_dir),
            GoPathStatus::MultipleAllManaged(go1)
        );
    }

    #[test]
    fn classify_multiple_shadowed_non_gvsn() {
        let versions_dir = std::path::Path::new("/gvsn/versions");
        let current_dir = std::path::Path::new("/gvsn/current");
        let active = current_dir.join("bin/go");
        let shadowed = std::path::PathBuf::from("/usr/local/go/bin/go");
        assert_eq!(
            classify_go_paths(
                &[active.clone(), shadowed.clone()],
                versions_dir,
                current_dir
            ),
            GoPathStatus::MultipleShadowedNonGvsn {
                active,
                shadowed: vec![shadowed],
            }
        );
    }

    #[test]
    fn classify_multiple_active_not_managed() {
        let versions_dir = std::path::Path::new("/gvsn/versions");
        let current_dir = std::path::Path::new("/gvsn/current");
        let system_go = std::path::PathBuf::from("/usr/local/go/bin/go");
        let managed_go = versions_dir.join("go1.22.4/bin/go");
        let all = vec![system_go, managed_go];
        assert_eq!(
            classify_go_paths(&all, versions_dir, current_dir),
            GoPathStatus::MultipleActiveNotManaged { all }
        );
    }
}