Skip to main content

git_nav/
shell.rs

1//! Shell integration: emits and installs a `gnav` wrapper that captures
2//! the path git-nav prints on stdout and `cd`s into it.
3
4use std::env;
5use std::fs;
6use std::path::{Path, PathBuf};
7
8const MARKER_START: &str = "# >>> git-nav shell integration >>>";
9const MARKER_END: &str = "# <<< git-nav shell integration <<<";
10
11pub fn init_snippet(shell: &str) -> String {
12    let exe = current_exe();
13    match shell {
14        "fish" => format!(
15            r#"function gnav
16    switch "$argv[1]"
17        case -h --help -V --version --config-path --init
18            {exe} $argv
19            return
20    end
21    set -l dest ({exe} $argv)
22    if test -n "$dest"
23        cd $dest
24    end
25end
26"#
27        ),
28        // Works for both bash and zsh.
29        _ => format!(
30            r#"gnav() {{
31  # Informational flags print to stdout for human consumption; running
32  # them through the capture-and-cd path below would try to `cd` into
33  # the help text. Pass them through directly instead.
34  case "$1" in
35    -h|--help|-V|--version|--config-path|--init)
36      {exe} "$@"
37      return
38      ;;
39  esac
40  local dest
41  dest="$({exe} "$@")" || return
42  [ -n "$dest" ] && cd "$dest"
43}}
44"#
45        ),
46    }
47}
48
49fn current_exe() -> String {
50    env::current_exe()
51        .map(|p| p.to_string_lossy().to_string())
52        .unwrap_or_else(|_| "git-nav".into())
53}
54
55/// Idempotently append (or refresh) the wrapper function in the user's rc
56/// file. Returns the path of the file that was written.
57pub fn install(shell_override: Option<&str>) -> crate::Result<PathBuf> {
58    let shell = shell_override
59        .map(String::from)
60        .or_else(|| {
61            env::var("SHELL").ok().and_then(|s| {
62                Path::new(&s)
63                    .file_name()
64                    .and_then(|n| n.to_str())
65                    .map(String::from)
66            })
67        })
68        .unwrap_or_else(|| "bash".into());
69
70    let rc = rc_file_for(&shell)?;
71    let snippet = init_snippet(&shell);
72    let block = format!("{MARKER_START}\n{snippet}{MARKER_END}");
73
74    let existing = fs::read_to_string(&rc).unwrap_or_default();
75    let updated = replace_or_append(&existing, &block);
76    if let Some(parent) = rc.parent() {
77        fs::create_dir_all(parent)?;
78    }
79    fs::write(&rc, updated)?;
80    Ok(rc)
81}
82
83fn rc_file_for(shell: &str) -> crate::Result<PathBuf> {
84    let home = env::var("HOME")?;
85    let path = match shell {
86        "zsh" => PathBuf::from(&home).join(".zshrc"),
87        "bash" => PathBuf::from(&home).join(".bashrc"),
88        "fish" => PathBuf::from(&home).join(".config/fish/config.fish"),
89        other => return Err(format!("unsupported shell: {other}").into()),
90    };
91    Ok(path)
92}
93
94fn replace_or_append(existing: &str, block: &str) -> String {
95    if let (Some(start), Some(end)) = (existing.find(MARKER_START), existing.find(MARKER_END)) {
96        let end = end + MARKER_END.len();
97        let mut out = String::new();
98        out.push_str(existing[..start].trim_end_matches('\n'));
99        if !out.is_empty() {
100            out.push_str("\n\n");
101        }
102        out.push_str(block);
103        out.push('\n');
104        out.push_str(existing[end..].trim_start_matches('\n'));
105        return out;
106    }
107    let mut out = existing.trim_end().to_string();
108    if !out.is_empty() {
109        out.push_str("\n\n");
110    }
111    out.push_str(block);
112    out.push('\n');
113    out
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    #[test]
121    fn snippet_covers_all_shells() {
122        assert!(init_snippet("zsh").contains("gnav"));
123        assert!(init_snippet("bash").contains("gnav"));
124        assert!(init_snippet("fish").contains("function gnav"));
125    }
126
127    #[test]
128    fn snippet_passes_informational_flags_through() {
129        // Prevents regressions where `gnav --help` would try to `cd`
130        // into the help output.
131        for shell in ["bash", "zsh", "fish"] {
132            let s = init_snippet(shell);
133            for flag in ["--help", "--version", "--config-path", "--init"] {
134                assert!(
135                    s.contains(flag),
136                    "{shell} snippet missing passthrough for {flag}:\n{s}"
137                );
138            }
139        }
140    }
141
142    #[test]
143    fn append_when_missing() {
144        let out = replace_or_append("existing content", "BLOCK");
145        assert!(out.contains("existing content"));
146        assert!(out.trim_end().ends_with("BLOCK"));
147    }
148
149    #[test]
150    fn append_to_empty_file() {
151        let out = replace_or_append("", "BLOCK");
152        assert_eq!(out.trim(), "BLOCK");
153    }
154
155    #[test]
156    fn replace_when_present() {
157        let block = format!("{MARKER_START}\nOLD_SNIPPET\n{MARKER_END}");
158        let existing = format!("before\n{block}\nafter\n");
159        let new = format!("{MARKER_START}\nNEW_SNIPPET\n{MARKER_END}");
160        let out = replace_or_append(&existing, &new);
161        assert!(out.contains("NEW_SNIPPET"));
162        assert!(!out.contains("OLD_SNIPPET"));
163        assert!(out.contains("before"));
164        assert!(out.contains("after"));
165    }
166
167    #[test]
168    fn rc_file_maps_correctly() {
169        // SAFETY: see config::tests — HOME is only read after we set it.
170        unsafe { std::env::set_var("HOME", "/tmp/faux-home") };
171        assert!(rc_file_for("zsh").unwrap().ends_with(".zshrc"));
172        assert!(rc_file_for("bash").unwrap().ends_with(".bashrc"));
173        assert!(
174            rc_file_for("fish")
175                .unwrap()
176                .ends_with(".config/fish/config.fish")
177        );
178        assert!(rc_file_for("csh").is_err());
179    }
180}