Skip to main content

git_stk/
setup.rs

1use std::env;
2use std::fs;
3use std::path::PathBuf;
4use std::process::Command;
5
6use anyhow::{Context, Result};
7use clap::CommandFactory;
8
9use crate::cli::Cli;
10use crate::prompt::confirm;
11
12/// Marker comment written above the completion line so re-runs can detect it
13/// (`#` is also a comment in PowerShell).
14const COMPLETION_MARKER: &str = "# added by git-stk setup";
15
16/// The PowerShell completion line, guarded so a removed git-stk never breaks
17/// shell startup.
18const POWERSHELL_LINE: &str = "if (Get-Command git-stk -ErrorAction SilentlyContinue) { git stk completions powershell | Out-String | Invoke-Expression }";
19
20pub fn setup(yes: bool, refresh: bool) -> Result<()> {
21    if refresh {
22        // Re-render assets that can go stale across versions. Non-interactive;
23        // run by `upgrade` via the newly installed binary. Completion wiring is
24        // left alone because the rc line re-sources from the binary on every
25        // shell start; missing wiring gets a hint instead of a prompt.
26        install_man_page()?;
27        return print_completion_hint();
28    }
29
30    install_man_page()?;
31    wire_completions(yes)?;
32    Ok(())
33}
34
35/// Render the man page into the XDG data directory, which is on the default
36/// manpath. This makes `git stk --help` work: git resolves it as `man git-stk`.
37fn install_man_page() -> Result<()> {
38    if cfg!(windows) {
39        return Ok(());
40    }
41
42    let dir = man_dir()?;
43    fs::create_dir_all(&dir).with_context(|| format!("failed to create {}", dir.display()))?;
44
45    let mut buffer = Vec::new();
46    clap_mangen::Man::new(Cli::command())
47        .render(&mut buffer)
48        .context("failed to render man page")?;
49
50    let path = dir.join("git-stk.1");
51    fs::write(&path, buffer).with_context(|| format!("failed to write {}", path.display()))?;
52    println!("installed man page to {}", path.display());
53    Ok(())
54}
55
56fn man_dir() -> Result<PathBuf> {
57    let data_home = env::var_os("XDG_DATA_HOME")
58        .map(PathBuf::from)
59        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".local/share")))
60        .context("cannot locate a data directory; set HOME or XDG_DATA_HOME")?;
61    Ok(data_home.join("man/man1"))
62}
63
64/// Append a completion-sourcing line to the detected shell's rc file, once.
65fn wire_completions(yes: bool) -> Result<()> {
66    let Some((shell, rc_path, line)) = completion_target()? else {
67        println!("could not detect a supported shell");
68        println!("see the README for manual completion setup");
69        return Ok(());
70    };
71
72    let existing = match fs::read_to_string(&rc_path) {
73        Ok(contents) => contents,
74        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
75        Err(error) => {
76            return Err(error).with_context(|| format!("failed to read {}", rc_path.display()));
77        }
78    };
79
80    if existing.contains(COMPLETION_MARKER) || existing.contains("git stk completions") {
81        println!(
82            "{shell} completions already configured in {}",
83            rc_path.display()
84        );
85        return Ok(());
86    }
87
88    if !yes
89        && !confirm(&format!(
90            "append completion setup to {}? [y/N] ",
91            rc_path.display()
92        ))?
93    {
94        println!("skipped completion setup");
95        println!("to configure manually, add this to {}:", rc_path.display());
96        println!("  {line}");
97        return Ok(());
98    }
99
100    let mut updated = existing;
101    if !updated.is_empty() && !updated.ends_with('\n') {
102        updated.push('\n');
103    }
104    updated.push_str(&format!("\n{COMPLETION_MARKER}\n{line}\n"));
105    // The rc file's directory may not exist yet (fish's ~/.config/fish, a
106    // never-created PowerShell profile dir).
107    if let Some(parent) = rc_path.parent() {
108        fs::create_dir_all(parent)
109            .with_context(|| format!("failed to create {}", parent.display()))?;
110    }
111    fs::write(&rc_path, updated)
112        .with_context(|| format!("failed to write {}", rc_path.display()))?;
113    println!("added {shell} completion setup to {}", rc_path.display());
114    Ok(())
115}
116
117/// Point at `git stk setup` when the detected shell has no completion
118/// wiring yet. Used after upgrades, where prompting is not an option.
119fn print_completion_hint() -> Result<()> {
120    let Some((shell, rc_path, line)) = completion_target()? else {
121        return Ok(());
122    };
123
124    let configured = fs::read_to_string(&rc_path)
125        .map(|rc| rc.contains(COMPLETION_MARKER) || rc.contains("git stk completions"))
126        .unwrap_or(false);
127    if configured {
128        return Ok(());
129    }
130
131    println!(
132        "{shell} completions are not configured; run `git stk setup`, \
133         or add this to {}:",
134        rc_path.display()
135    );
136    println!("  {line}");
137    Ok(())
138}
139
140/// Resolve (shell name, rc file, completion line). A POSIX shell from $SHELL
141/// wins (covers Git Bash and WSL on Windows); otherwise fall back to
142/// PowerShell. The lines guard on the binary existing so a removed git-stk
143/// never breaks shell startup.
144fn completion_target() -> Result<Option<(&'static str, PathBuf, &'static str)>> {
145    if let Some(target) = posix_shell_target() {
146        return Ok(Some(target));
147    }
148    Ok(powershell_target())
149}
150
151/// A bash/zsh/fish target from $SHELL, or None when $SHELL is unset/unknown
152/// or HOME is missing (e.g. native Windows). Never an error - we fall
153/// through to PowerShell.
154fn posix_shell_target() -> Option<(&'static str, PathBuf, &'static str)> {
155    let shell = env::var("SHELL").unwrap_or_default();
156    let shell = shell.rsplit('/').next().unwrap_or_default();
157    let home = env::var_os("HOME").map(PathBuf::from)?;
158
159    match shell {
160        "bash" => Some((
161            "bash",
162            home.join(".bashrc"),
163            "command -v git-stk >/dev/null && source <(git stk completions bash)",
164        )),
165        "zsh" => Some((
166            "zsh",
167            home.join(".zshrc"),
168            "command -v git-stk >/dev/null && source <(git stk completions zsh)",
169        )),
170        "fish" => Some((
171            "fish",
172            home.join(".config/fish/config.fish"),
173            "command -q git-stk; and git stk completions fish | source",
174        )),
175        _ => None,
176    }
177}
178
179/// PowerShell's `$PROFILE`, when a PowerShell is on PATH. Asking the shell
180/// itself is the only reliable way to get the path - it differs between
181/// PowerShell 7 and Windows PowerShell 5.1, and Documents is often
182/// OneDrive-relocated.
183fn powershell_target() -> Option<(&'static str, PathBuf, &'static str)> {
184    for exe in ["pwsh", "powershell"] {
185        let Ok(output) = Command::new(exe)
186            .args(["-NoProfile", "-Command", "$PROFILE"])
187            .output()
188        else {
189            continue;
190        };
191        if !output.status.success() {
192            continue;
193        }
194        let path = String::from_utf8_lossy(&output.stdout).trim().to_owned();
195        if !path.is_empty() {
196            return Some(("PowerShell", PathBuf::from(path), POWERSHELL_LINE));
197        }
198    }
199    None
200}