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
//! `gvsn setup` - configure the shell environment for gvsn.
//!
//! Responsible for ALL environment configuration: shell hooks, static PATH
//! entries in login profiles (Linux/macOS), and registry PATH entries
//! (Windows). The install script places the binary and then delegates here.
//!
//! # What this command does
//!
//! 1. Injects `# gvsn init` + `# gvsn wrapper` into the shell's interactive
//!    profile (e.g. `~/.bashrc`).
//! 2. On Linux/macOS: injects `# gvsn path` into the login profile
//!    (`~/.profile` for bash, `~/.zprofile` for zsh) so `~/.gvsn/current/bin`
//!    is on PATH for GUI applications (VSCode, GoLand, etc.) that do not
//!    source the interactive profile.
//! 3. On Windows: adds the gvsn binary directory and `~\.gvsn\current\bin` to
//!    the user PATH in the registry so all applications see them.
//!
//! # `--reset` flag
//!
//! Strips every `# gvsn ...` block from the interactive and login profiles
//! (and the Windows registry on Windows), then re-applies clean configuration.
//! Only gvsn-managed blocks are touched; all other content is preserved.

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

use crate::{shell, shell::ShellConfig};

/// Runs `gvsn setup`, optionally with a full reset.
///
/// `shell_str` overrides auto-detection. `reset` strips all previous gvsn
/// configuration before re-applying.
///
/// # Errors
///
/// Returns an error if the shell cannot be detected, profiles cannot be
/// written, or (on Windows) the registry cannot be accessed.
pub fn run(shell_str: Option<&str>, reset: bool) -> Result<()> {
    let sh: Box<dyn ShellConfig> = match shell_str {
        Some(s) => {
            let sh = shell::from_str(s)?;
            if !shell::is_available(sh.as_ref()) {
                let hint = hint_for_missing_explicit_shell(&shell::available_shells());
                anyhow::bail!(
                    "Shell '{}' is not installed or not found in PATH.\n  {}",
                    s,
                    hint
                );
            }
            sh
        }
        None => match shell::detect() {
            Some(sh) => {
                // Sanity-check: the detected shell should always be available,
                // but guard against a stale $SHELL pointing to a removed binary.
                if !shell::is_available(sh.as_ref()) {
                    let hint = hint_for_stale_detected_shell(&shell::available_shells());
                    anyhow::bail!(
                        "Detected shell '{}' but its binary was not found in PATH.\n  {}",
                        sh.name(),
                        hint
                    );
                }
                sh
            }
            None => {
                let hint = hint_for_no_shell_detected(&shell::available_shells());
                anyhow::bail!("Could not detect current shell.\n  {}", hint);
            }
        },
    };

    println!("Setting up gvsn for {}...", sh.name().bold());

    // ---- Optional reset: strip all previous gvsn config ----------------------
    if reset {
        strip_all(sh.as_ref())?;
        println!();
        println!("  Previous configuration removed. Re-applying...");
        println!();
    }

    // ---- Interactive profile: eval hook + wrapper ---------------------------
    let gvsn_bin_dir = std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(std::path::PathBuf::from));
    shell::inject_profile(sh.as_ref(), gvsn_bin_dir.as_deref())?;

    // ---- Login profile (Linux/macOS): static PATH for GUI apps --------------
    #[cfg(not(target_os = "windows"))]
    shell::inject_login_profile(sh.as_ref())?;

    // ---- Windows registry: PATH entries for gvsn binary + current/bin --------
    #[cfg(target_os = "windows")]
    inject_windows_registry()?;

    // ---- Warn if gvsn binary itself is not yet on PATH -----------------------
    if !shell::gvsn_in_path() {
        if let Ok(exe) = std::env::current_exe() {
            let dir = exe
                .parent()
                .map(|p| p.display().to_string())
                .unwrap_or_default();
            println!();
            println!("{} gvsn is not in PATH yet.", "!".yellow());
            println!(
                "  Add {} to your PATH so the shell hook can call 'gvsn path'.",
                dir.cyan()
            );
        }
    }

    println!();
    println!(
        "{} Restart your shell or run: {}",
        "✓".green(),
        sh.init_line().cyan()
    );
    Ok(())
}

// --- Hint building -------------------------------------------------------

/// Builds the hint appended to the error when an explicit `--shell <s>`
/// value names a shell that isn't installed or isn't on PATH.
fn hint_for_missing_explicit_shell(available: &[&str]) -> String {
    if available.is_empty() {
        "No supported shells found in PATH.".to_string()
    } else {
        format!("Shells available on this system: {}", available.join(", "))
    }
}

/// Builds the hint appended to the error when the auto-detected shell (e.g.
/// via `$SHELL`) points at a binary that can no longer be found on PATH.
fn hint_for_stale_detected_shell(available: &[&str]) -> String {
    if available.is_empty() {
        "No supported shells found in PATH. Install bash, zsh, or fish first.".to_string()
    } else {
        format!(
            "Try: gvsn setup --shell {}",
            available.first().copied().unwrap_or("bash")
        )
    }
}

/// Builds the hint appended to the error when no shell could be detected at
/// all (neither `$SHELL` nor `PSModulePath` were set).
fn hint_for_no_shell_detected(available: &[&str]) -> String {
    if available.is_empty() {
        "No supported shells found. Install bash, zsh, fish, or PowerShell first.".to_string()
    } else {
        format!(
            "Detected shells: {}. Use --shell <name> to select one.",
            available.join(", ")
        )
    }
}

// --- Reset helpers -----------------------------------------------------------

/// Strips all gvsn-managed blocks from the interactive profile and, on
/// non-Windows, from the login profile as well.
fn strip_all(sh: &dyn ShellConfig) -> Result<()> {
    // Interactive profile (e.g. ~/.bashrc)
    if let Some(p) = sh.profile_path() {
        match shell::strip_profile(&p) {
            Ok(true) => println!("  {} Cleaned {}", "✓".green(), p.display()),
            Ok(false) => println!("  No gvsn config found in {}", p.display()),
            Err(e) => println!("  {} Could not clean {}: {e}", "!".yellow(), p.display()),
        }
    }

    // Login profile (e.g. ~/.profile or ~/.zprofile)
    #[cfg(not(target_os = "windows"))]
    if let Some(p) = sh.login_profile_path() {
        match shell::strip_profile(&p) {
            Ok(true) => println!("  {} Cleaned {}", "✓".green(), p.display()),
            Ok(false) => println!("  No gvsn config found in {}", p.display()),
            Err(e) => println!("  {} Could not clean {}: {e}", "!".yellow(), p.display()),
        }
    }

    // Windows registry
    #[cfg(target_os = "windows")]
    strip_windows_registry()?;

    Ok(())
}

// --- Windows registry --------------------------------------------------------

/// Returns `true` if `candidate` is already present in `entries`.
///
/// Windows paths are case-insensitive, so a PATH entry that differs from
/// `candidate` only in case (e.g. a different drive-letter casing from
/// another shell) still counts as present - comparing `Path` values directly
/// would miss this and insert a duplicate entry on every `gvsn setup` run.
///
/// Kept unconditional (not `#[cfg(windows)]`) so its logic is unit-tested on
/// every platform; its only production caller, `inject_windows_registry`, is
/// Windows-only, so the lint is suppressed on other platforms instead.
#[cfg_attr(not(windows), allow(dead_code))]
fn path_already_present(entries: &[String], candidate: &std::path::Path) -> bool {
    let candidate = candidate.to_string_lossy();
    entries
        .iter()
        .any(|e| e.eq_ignore_ascii_case(candidate.as_ref()))
}

/// Broadcasts `WM_SETTINGCHANGE` so running processes - most importantly
/// Explorer - refresh their cached environment block immediately.
///
/// Writing `HKCU\Environment` alone is not enough: Explorer (and anything it
/// spawns - the Start Menu, the taskbar, double-clicking an `.exe`) keeps its
/// own copy of the environment from whenever it last started, and normally
/// only refreshes it on this broadcast, a logoff, or a restart. Without it, a
/// GUI application like VS Code or GoLand launched right after `gvsn setup`/
/// `gvsn use` still sees the *old* PATH and fails to find `go`, even though
/// any terminal opened afterward works fine (terminals inherit PATH fresh
/// from Explorer at spawn time once Explorer itself has the update).
///
/// This only affects newly spawned processes - a GUI app that was already
/// running keeps whatever environment it started with regardless, since
/// Windows has no way to inject new environment variables into a live
/// process. It still needs to be closed and reopened once.
///
/// Best-effort: failures are ignored. Worst case, the pre-existing "restart
/// your terminal or log out/in" guidance still applies.
#[cfg(target_os = "windows")]
fn broadcast_environment_change() {
    use windows_sys::Win32::Foundation::HWND;
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        SendMessageTimeoutW, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,
    };

    let param: Vec<u16> = "Environment\0".encode_utf16().collect();
    let mut result: usize = 0;
    unsafe {
        SendMessageTimeoutW(
            HWND_BROADCAST as HWND,
            WM_SETTINGCHANGE,
            0,
            param.as_ptr() as isize,
            SMTO_ABORTIFHUNG,
            5000,
            &mut result,
        );
    }
}

/// Adds the gvsn binary directory and `~\.gvsn\current\bin` to the user PATH
/// in the Windows registry (HKCU\Environment).
///
/// Idempotent: entries that are already present are not duplicated.
#[cfg(target_os = "windows")]
fn inject_windows_registry() -> Result<()> {
    use anyhow::Context;
    use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
    use winreg::RegKey;

    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    let env = hkcu
        .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
        .context("Cannot open HKCU\\Environment registry key")?;

    let current_path: String = env.get_value("PATH").unwrap_or_default();
    let mut entries: Vec<String> = current_path
        .split(';')
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect();

    let mut changed = false;

    // gvsn binary directory
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            let dir_str = dir.to_string_lossy().to_string();
            if !path_already_present(&entries, dir) {
                entries.insert(0, dir_str);
                println!("  Added {} to user PATH (registry)", dir.display());
                changed = true;
            } else {
                println!("  {} already in user PATH", dir.display());
            }
        }
    }

    // ~/.gvsn/current/bin
    if let Some(home) = dirs::home_dir() {
        let current_bin = home.join(".gvsn").join("current").join("bin");
        let current_bin_str = current_bin.to_string_lossy().to_string();
        if !path_already_present(&entries, &current_bin) {
            entries.insert(0, current_bin_str);
            println!("  Added {} to user PATH (registry)", current_bin.display());
            changed = true;
        } else {
            println!("  {} already in user PATH", current_bin.display());
        }
    }

    if changed {
        let new_path = entries.join(";");
        env.set_value("PATH", &new_path)
            .context("Cannot write PATH to HKCU\\Environment")?;
        broadcast_environment_change();
        println!("  {} User PATH updated in registry", "✓".green());
        println!(
            "  New terminals and GUI apps (VSCode, GoLand, ...) will pick this up automatically."
        );
        println!("  Already-open ones need to be restarted to see it.");
    }

    Ok(())
}

/// Removes all gvsn-managed entries from the Windows user PATH in the registry.
#[cfg(target_os = "windows")]
fn strip_windows_registry() -> Result<()> {
    use anyhow::Context;
    use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
    use winreg::RegKey;

    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    let env = hkcu
        .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
        .context("Cannot open HKCU\\Environment registry key")?;

    let current_path: String = env.get_value("PATH").unwrap_or_default();

    // Remove any entry that is inside the user's .gvsn directory.
    let home = dirs::home_dir().unwrap_or_default();
    let gvsn_root = home.join(".gvsn");

    let filtered: Vec<&str> = current_path
        .split(';')
        .filter(|e| {
            let p = std::path::Path::new(e);
            !p.starts_with(&gvsn_root)
        })
        .collect();

    let new_path = filtered.join(";");
    if new_path != current_path {
        env.set_value("PATH", &new_path)
            .context("Cannot write PATH to HKCU\\Environment")?;
        broadcast_environment_change();
        println!(
            "  {} Removed gvsn entries from user PATH (registry)",
            "✓".green()
        );
    }

    Ok(())
}

// --- Tests ---------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(not(target_os = "windows"))]
    use std::path::PathBuf;

    // Smoke test only: confirms the WM_SETTINGCHANGE broadcast itself is a
    // well-formed call that doesn't crash the process. It never touches the
    // registry, so it's safe to run in CI - it can't verify that Explorer
    // actually refreshes its cached environment, which requires a real
    // interactive desktop session to observe.
    #[cfg(target_os = "windows")]
    #[test]
    fn broadcast_environment_change_does_not_panic() {
        broadcast_environment_change();
    }

    #[test]
    fn path_already_present_matches_case_insensitively() {
        let entries = vec![r"C:\Users\jhon\.gvsn\current\bin".to_string()];
        let candidate = std::path::Path::new(r"c:\users\jhon\.gvsn\current\bin");
        assert!(path_already_present(&entries, candidate));
    }

    #[test]
    fn path_already_present_is_false_for_unrelated_entry() {
        let entries = vec![r"C:\Users\jhon\.cargo\bin".to_string()];
        let candidate = std::path::Path::new(r"C:\Users\jhon\.gvsn\current\bin");
        assert!(!path_already_present(&entries, candidate));
    }

    #[test]
    fn hint_for_missing_explicit_shell_lists_available() {
        assert_eq!(
            hint_for_missing_explicit_shell(&["bash", "zsh"]),
            "Shells available on this system: bash, zsh"
        );
    }

    #[test]
    fn hint_for_missing_explicit_shell_handles_empty() {
        assert_eq!(
            hint_for_missing_explicit_shell(&[]),
            "No supported shells found in PATH."
        );
    }

    #[test]
    fn hint_for_stale_detected_shell_suggests_first_available() {
        assert_eq!(
            hint_for_stale_detected_shell(&["zsh", "fish"]),
            "Try: gvsn setup --shell zsh"
        );
    }

    #[test]
    fn hint_for_stale_detected_shell_handles_empty() {
        assert_eq!(
            hint_for_stale_detected_shell(&[]),
            "No supported shells found in PATH. Install bash, zsh, or fish first."
        );
    }

    #[test]
    fn hint_for_no_shell_detected_lists_available() {
        assert_eq!(
            hint_for_no_shell_detected(&["bash", "fish"]),
            "Detected shells: bash, fish. Use --shell <name> to select one."
        );
    }

    #[test]
    fn hint_for_no_shell_detected_handles_empty() {
        assert_eq!(
            hint_for_no_shell_detected(&[]),
            "No supported shells found. Install bash, zsh, fish, or PowerShell first."
        );
    }

    /// Fake [`ShellConfig`] whose `profile_path()`/`login_profile_path()`
    /// point into a tempdir, so `strip_all` can be exercised without
    /// touching real shell profiles or (on Windows) the registry.
    #[cfg(not(target_os = "windows"))]
    #[derive(Debug)]
    struct FakeShell {
        profile: PathBuf,
        login_profile: PathBuf,
    }

    #[cfg(not(target_os = "windows"))]
    impl ShellConfig for FakeShell {
        fn name(&self) -> &'static str {
            "bash"
        }
        fn env_script(&self, _ctx: &shell::EnvContext<'_>) -> String {
            String::new()
        }
        fn profile_path(&self) -> Option<PathBuf> {
            Some(self.profile.clone())
        }
        fn login_profile_path(&self) -> Option<PathBuf> {
            Some(self.login_profile.clone())
        }
        fn init_line(&self) -> &'static str {
            "eval gvsn"
        }
        fn wrapper_function(&self) -> &'static str {
            "gvsn() { command gvsn \"$@\"; }"
        }
        fn shell_version_script(
            &self,
            _tag: &str,
            _bin: &std::path::Path,
            _root: &std::path::Path,
        ) -> String {
            String::new()
        }
        fn shell_unset_script(&self) -> &'static str {
            ""
        }
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn strip_all_cleans_both_profiles() {
        let dir = tempfile::tempdir().unwrap();
        let sh = FakeShell {
            profile: dir.path().join("profile"),
            login_profile: dir.path().join("login_profile"),
        };

        // Seed both files with gvsn-managed blocks plus user content.
        std::fs::write(
            &sh.profile,
            "# user\nexport FOO=bar\n\n# gvsn init\neval gvsn\n",
        )
        .unwrap();
        std::fs::write(
            &sh.login_profile,
            "# gvsn path\nexport PATH=\"$HOME/.gvsn/current/bin:$PATH\"\n",
        )
        .unwrap();

        strip_all(&sh).unwrap();

        let profile_content = std::fs::read_to_string(&sh.profile).unwrap();
        assert!(!profile_content.contains("# gvsn init"));
        assert!(profile_content.contains("export FOO=bar"));

        let login_content = std::fs::read_to_string(&sh.login_profile).unwrap();
        assert!(!login_content.contains("# gvsn path"));
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn strip_all_is_a_noop_on_files_without_gvsn_config() {
        let dir = tempfile::tempdir().unwrap();
        let sh = FakeShell {
            profile: dir.path().join("profile"),
            login_profile: dir.path().join("login_profile"),
        };
        std::fs::write(&sh.profile, "export FOO=bar\n").unwrap();

        // Must not error even though the login profile doesn't exist yet.
        strip_all(&sh).unwrap();

        let content = std::fs::read_to_string(&sh.profile).unwrap();
        assert_eq!(content, "export FOO=bar\n");
    }
}