use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::lsp::log_file;
const INSTALL_SCRIPT: &str =
"curl -sSfL https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | sh";
const TERMUX_INSTALL_SCRIPT: &str = "pkg install -y zoxide";
pub fn install_script(termux: bool) -> &'static str {
if termux {
TERMUX_INSTALL_SCRIPT
} else {
INSTALL_SCRIPT
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallState {
Idle = 0,
Running = 1,
Done = 2,
Failed = 3,
}
static INSTALL_STATE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
fn set_install_state(state: InstallState) {
INSTALL_STATE.store(state as u8, std::sync::atomic::Ordering::Release);
}
pub fn install_state() -> InstallState {
match INSTALL_STATE.load(std::sync::atomic::Ordering::Acquire) {
1 => InstallState::Running,
2 => InstallState::Done,
3 => InstallState::Failed,
_ => InstallState::Idle,
}
}
static OUTCOME: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
fn set_outcome(outcome: String) {
if let Ok(mut slot) = OUTCOME.lock() {
*slot = Some(outcome);
}
}
pub fn install_outcome() -> Option<String> {
OUTCOME.lock().ok().and_then(|slot| slot.clone())
}
#[cfg(test)]
thread_local! {
static INSTALL_REQUESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn install_requests() -> usize {
INSTALL_REQUESTS.with(|n| n.get())
}
const ZOXIDE_CMD: &str = "j";
const INIT_MARKER_START: &str = "# >>> croft zoxide (managed) >>>";
const INIT_MARKER_END: &str = "# <<< croft zoxide (managed) <<<";
const INIT_SENTINEL: &str = "zoxide init";
fn fallback_paths() -> Vec<PathBuf> {
let mut paths = Vec::new();
if let Some(home) = std::env::var_os("HOME") {
paths.push(
PathBuf::from(&home)
.join(".local")
.join("bin")
.join("zoxide"),
);
}
paths.push(PathBuf::from("/opt/homebrew/bin/zoxide"));
paths.push(PathBuf::from("/usr/local/bin/zoxide"));
paths.push(PathBuf::from("/usr/bin/zoxide"));
paths
}
fn probe(candidate: &PathBuf) -> bool {
Command::new(candidate)
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
pub fn binary() -> Option<PathBuf> {
let on_path = PathBuf::from("zoxide");
if probe(&on_path) {
return Some(on_path);
}
fallback_paths()
.into_iter()
.find(|p| p.exists() && probe(p))
}
fn query_args(needle: &str) -> Vec<String> {
let mut args = vec![String::from("query"), String::from("-l")];
args.extend(needle.split_whitespace().map(String::from));
args
}
pub fn parse_query_output(stdout: &str) -> Vec<PathBuf> {
stdout
.lines()
.filter(|l| !l.trim().is_empty())
.map(PathBuf::from)
.collect()
}
pub fn query(needle: &str) -> Option<Vec<PathBuf>> {
let bin = binary()?;
let output = Command::new(bin).args(query_args(needle)).output().ok()?;
Some(parse_query_output(&String::from_utf8_lossy(&output.stdout)))
}
fn osa_substring_distance(pattern: &[char], text: &[char]) -> usize {
let n = pattern.len();
let m = text.len();
if n == 0 {
return 0;
}
let mut d = vec![vec![0usize; m + 1]; n + 1];
for (i, row) in d.iter_mut().enumerate() {
row[0] = i;
}
for i in 1..=n {
for j in 1..=m {
let cost = usize::from(pattern[i - 1] != text[j - 1]);
let mut best = (d[i - 1][j] + 1)
.min(d[i][j - 1] + 1)
.min(d[i - 1][j - 1] + cost);
if i >= 2 && j >= 2 && pattern[i - 1] == text[j - 2] && pattern[i - 2] == text[j - 1] {
best = best.min(d[i - 2][j - 2] + 1);
}
d[i][j] = best;
}
}
d[n].iter().copied().min().unwrap_or(n)
}
fn fuzzy_threshold(len: usize) -> usize {
(len / 3).clamp(1, 3)
}
fn basename_chars(path: &std::path::Path) -> Vec<char> {
path.file_name()
.map(|n| n.to_string_lossy().to_lowercase().chars().collect())
.unwrap_or_default()
}
pub fn fuzzy_rank(needle: &str, dirs: &[PathBuf]) -> Vec<PathBuf> {
let Some(token) = needle.split_whitespace().last() else {
return Vec::new();
};
let pattern: Vec<char> = token.to_lowercase().chars().collect();
let threshold = fuzzy_threshold(pattern.len());
let mut scored: Vec<(usize, usize, PathBuf)> = dirs
.iter()
.enumerate()
.filter_map(|(rank, path)| {
let dist = osa_substring_distance(&pattern, &basename_chars(path));
(dist <= threshold).then(|| (dist, rank, path.clone()))
})
.collect();
scored.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
scored.into_iter().map(|(_, _, path)| path).collect()
}
fn supported_shell(shell_path: &str) -> Option<&'static str> {
let base = Path::new(shell_path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(shell_path);
match base {
"zsh" => Some("zsh"),
"bash" => Some("bash"),
_ => None,
}
}
fn rc_file_name(shell: &str) -> &'static str {
match shell {
"zsh" => ".zshrc",
_ => ".bashrc",
}
}
fn rc_hint(shell_path: Option<&str>) -> Option<String> {
supported_shell(shell_path?).map(|shell| format!("~/{}", rc_file_name(shell)))
}
pub fn shell_rc_hint() -> Option<String> {
rc_hint(std::env::var("SHELL").ok().as_deref())
}
fn missing_hook_rc(shell_path: Option<&str>, home: Option<&Path>) -> Option<String> {
let shell = supported_shell(shell_path?)?;
let existing = std::fs::read_to_string(home?.join(rc_file_name(shell))).unwrap_or_default();
pending_init_block(shell, &existing)?;
rc_hint(shell_path)
}
pub fn shell_hook_missing() -> Option<String> {
let home = std::env::var_os("HOME").map(PathBuf::from);
missing_hook_rc(std::env::var("SHELL").ok().as_deref(), home.as_deref())
}
#[cfg(test)]
thread_local! {
static HOOK_REQUESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn hook_requests() -> usize {
HOOK_REQUESTS.with(|n| n.get())
}
pub fn add_shell_hook() -> Option<String> {
#[cfg(test)]
HOOK_REQUESTS.with(|n| n.set(n.get() + 1));
if cfg!(test) {
return None;
}
ensure_shell_init()
}
fn init_block(shell: &str) -> String {
format!(
"\n{INIT_MARKER_START}\nexport PATH=\"$HOME/.local/bin:$PATH\"\neval \"$(zoxide init {shell} --cmd {ZOXIDE_CMD})\"\n{INIT_MARKER_END}\n"
)
}
fn pending_init_block(shell: &str, existing: &str) -> Option<String> {
if existing.contains(INIT_SENTINEL) {
return None;
}
Some(init_block(shell))
}
fn ensure_shell_init() -> Option<String> {
let Ok(shell_path) = std::env::var("SHELL") else {
log_file::log("zoxide: $SHELL unset, skipping shell-init wiring");
return None;
};
let Some(shell) = supported_shell(&shell_path) else {
log_file::log(&format!(
"zoxide: unsupported shell {shell_path:?}, skipping shell-init wiring"
));
return None;
};
let Some(home) = std::env::var_os("HOME") else {
log_file::log("zoxide: $HOME unset, skipping shell-init wiring");
return None;
};
let rc = PathBuf::from(home).join(rc_file_name(shell));
let existing = std::fs::read_to_string(&rc).unwrap_or_default();
let block = pending_init_block(shell, &existing)?;
match std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&rc)
{
Ok(mut f) => match f.write_all(block.as_bytes()) {
Ok(()) => {
log_file::log(&format!(
"zoxide: wired `{ZOXIDE_CMD}` shell init into {rc:?}"
));
return rc_hint(Some(&shell_path));
}
Err(e) => log_file::log(&format!("zoxide: failed to append init to {rc:?}: {e}")),
},
Err(e) => log_file::log(&format!(
"zoxide: could not open {rc:?} for init wiring: {e}"
)),
}
None
}
fn failure_reason(stderr: &str, status: &str) -> String {
stderr
.lines()
.map(str::trim)
.rfind(|line| !line.is_empty())
.map_or_else(
|| format!("the installer exited with {status}"),
String::from,
)
}
pub fn install_in_background() {
#[cfg(test)]
INSTALL_REQUESTS.with(|n| n.set(n.get() + 1));
let running = InstallState::Running as u8;
if cfg!(test) || INSTALL_STATE.swap(running, std::sync::atomic::Ordering::Relaxed) == running {
return;
}
std::thread::spawn(|| {
let script = install_script(crate::iterm2_inline::detect_termux());
let failure = match Command::new("sh").arg("-c").arg(script).output() {
Ok(out) if out.status.success() => {
log_file::log(&format!("zoxide: installer `{script}` succeeded"));
None
}
Ok(out) => {
let stderr = String::from_utf8_lossy(&out.stderr);
log_file::log(&format!(
"zoxide: installer `{script}` exited {}: {}",
out.status,
stderr.trim()
));
Some(failure_reason(&stderr, &out.status.to_string()))
}
Err(e) => {
log_file::log(&format!(
"zoxide: installer `{script}` could not start: {e}"
));
Some(format!("could not start sh: {e}"))
}
};
if binary().is_some() {
set_outcome(match ensure_shell_init() {
Some(rc) => format!(
"zoxide installed; added its `{ZOXIDE_CMD}` hook to {rc} between the \"{INIT_MARKER_START}\" markers"
),
None => String::from("zoxide installed"),
});
set_install_state(InstallState::Done);
} else {
set_outcome(failure.unwrap_or_else(|| {
String::from("the installer finished, but no zoxide binary was found")
}));
set_install_state(InstallState::Failed);
}
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn install_script_is_pkg_on_termux_and_curl_elsewhere() {
assert_eq!(
install_script(true),
TERMUX_INSTALL_SCRIPT,
"stock Termux has no curl, so the curl|sh installer can never run there; \
pkg is in every Termux bootstrap and installs to the always-executable $PREFIX/bin"
);
assert_eq!(
install_script(false),
INSTALL_SCRIPT,
"macOS/Linux keep the official cross-platform curl installer"
);
}
#[test]
fn query_args_splits_needle_into_keyword_tokens() {
assert_eq!(
query_args("foo bar"),
vec![
String::from("query"),
String::from("-l"),
String::from("foo"),
String::from("bar"),
],
"multi-word needles must become separate zoxide keyword args, mirroring `j foo bar`"
);
}
#[test]
fn query_args_with_empty_needle_lists_everything() {
assert_eq!(
query_args(" "),
vec![String::from("query"), String::from("-l")],
"a blank needle must yield `query -l` so the popup opens on the full frecency list"
);
}
#[test]
fn parse_query_output_keeps_one_path_per_nonblank_line_in_order() {
let out = "/Users/v/Documents/croft\n/Users/v/Documents\n\n/Users/v/.ssh\n";
assert_eq!(
parse_query_output(out),
vec![
PathBuf::from("/Users/v/Documents/croft"),
PathBuf::from("/Users/v/Documents"),
PathBuf::from("/Users/v/.ssh"),
],
"blank lines must be dropped and zoxide's best-first order preserved"
);
}
#[test]
fn parse_query_output_is_empty_for_no_matches() {
assert!(parse_query_output("").is_empty());
assert!(parse_query_output("\n \n").is_empty());
}
#[test]
fn osa_substring_distance_treats_adjacent_transposition_as_one_edit() {
let p: Vec<char> = "spilt".chars().collect();
let t: Vec<char> = "split".chars().collect();
assert_eq!(
osa_substring_distance(&p, &t),
1,
"a single adjacent swap (i<->l) must cost exactly one edit"
);
}
#[test]
fn osa_substring_distance_matches_token_inside_longer_basename() {
let p: Vec<char> = "spilt".chars().collect();
let t: Vec<char> = "pr-split".chars().collect();
assert_eq!(osa_substring_distance(&p, &t), 1);
let exact: Vec<char> = "split".chars().collect();
assert_eq!(osa_substring_distance(&exact, &t), 0);
}
#[test]
fn fuzzy_rank_recovers_transposed_typo_and_drops_unrelated_dirs() {
let dirs = vec![
PathBuf::from("/home/u/documents"),
PathBuf::from("/home/u/pr-split"),
PathBuf::from("/home/u/node_modules"),
];
let ranked = fuzzy_rank("spilt", &dirs);
assert_eq!(
ranked,
vec![PathBuf::from("/home/u/pr-split")],
"the transposed needle must surface pr-split and only pr-split"
);
}
#[test]
fn fuzzy_rank_orders_by_distance_then_frecency() {
let dirs = vec![
PathBuf::from("/a/docs"), PathBuf::from("/b/my-docs"), PathBuf::from("/c/dosc-stuff"), PathBuf::from("/d/unrelated"), ];
let ranked = fuzzy_rank("docs", &dirs);
assert_eq!(
ranked,
vec![
PathBuf::from("/a/docs"),
PathBuf::from("/b/my-docs"),
PathBuf::from("/c/dosc-stuff"),
],
"distance ascending, frecency order breaking equal-distance ties"
);
}
#[test]
fn fuzzy_rank_uses_only_the_last_whitespace_token() {
let dirs = vec![PathBuf::from("/home/u/pr-split")];
assert_eq!(fuzzy_rank("pr spilt", &dirs), dirs);
}
#[test]
fn fuzzy_threshold_is_tight_and_capped() {
assert_eq!(fuzzy_threshold(0), 1, "never below one edit");
assert_eq!(fuzzy_threshold(5), 1);
assert_eq!(fuzzy_threshold(9), 3);
assert_eq!(fuzzy_threshold(30), 3, "capped at three edits");
}
#[test]
fn supported_shell_maps_only_bash_and_zsh_by_basename() {
assert_eq!(supported_shell("/bin/zsh"), Some("zsh"));
assert_eq!(supported_shell("/usr/bin/bash"), Some("bash"));
assert_eq!(supported_shell("/opt/homebrew/bin/zsh"), Some("zsh"));
assert_eq!(
supported_shell("/usr/bin/fish"),
None,
"an unfamiliar shell must be skipped, not guessed"
);
assert_eq!(supported_shell("/bin/sh"), None);
}
#[test]
fn rc_file_name_targets_the_conventional_rc_per_shell() {
assert_eq!(rc_file_name("zsh"), ".zshrc");
assert_eq!(rc_file_name("bash"), ".bashrc");
}
#[test]
fn missing_hook_rc_names_an_rc_without_a_zoxide_init_line() {
let tmp = tempfile::tempdir().unwrap();
let (home, rc) = (Some(tmp.path()), tmp.path().join(".bashrc"));
assert_eq!(
missing_hook_rc(Some("/bin/bash"), home).as_deref(),
Some("~/.bashrc"),
"no rc yet"
);
std::fs::write(&rc, "alias ll='ls -la'\n").unwrap();
assert_eq!(
missing_hook_rc(Some("/bin/bash"), home).as_deref(),
Some("~/.bashrc")
);
std::fs::write(&rc, "eval \"$(zoxide init bash)\"\n").unwrap();
assert_eq!(
missing_hook_rc(Some("/bin/bash"), home),
None,
"hooked already"
);
assert_eq!(missing_hook_rc(Some("/usr/bin/fish"), home), None);
assert_eq!(missing_hook_rc(None, home), None);
assert_eq!(missing_hook_rc(Some("/bin/bash"), None), None);
}
#[test]
fn rc_hint_names_the_rc_an_install_would_edit_or_none() {
assert_eq!(rc_hint(Some("/bin/bash")).as_deref(), Some("~/.bashrc"));
assert_eq!(rc_hint(Some("/bin/zsh")).as_deref(), Some("~/.zshrc"));
assert_eq!(rc_hint(Some("/usr/bin/fish")), None, "fish is never wired");
assert_eq!(rc_hint(None), None, "an unset $SHELL is never wired");
}
#[test]
fn failure_reason_is_the_installers_last_error_line() {
let stderr = "info: downloading\n\
Error: zoxide has not yet been packaged for your architecture (x86_64-unknown-linux-musl)\n\n";
assert_eq!(
failure_reason(stderr, "exit status: 1"),
"Error: zoxide has not yet been packaged for your architecture (x86_64-unknown-linux-musl)"
);
assert_eq!(
failure_reason(" \n", "exit status: 127"),
"the installer exited with exit status: 127",
"a silent failure still says how it ended"
);
}
#[test]
fn init_block_installs_the_hook_and_j_command_for_the_shell() {
let bash = init_block("bash");
assert!(
bash.contains("zoxide init bash --cmd j"),
"must install the cd-hook and rename the command to `j`"
);
assert!(
bash.contains("export PATH=\"$HOME/.local/bin:$PATH\""),
"must put the croft-installed binary on PATH before the eval"
);
assert!(bash.contains(INIT_MARKER_START) && bash.contains(INIT_MARKER_END));
assert!(
bash.starts_with('\n'),
"a leading blank line keeps the block off the end of existing content"
);
assert!(init_block("zsh").contains("zoxide init zsh --cmd j"));
}
#[test]
fn pending_init_block_appends_when_rc_has_no_zoxide() {
let block = pending_init_block("bash", "# my bashrc\nalias ll='ls -la'\n");
assert!(block.is_some_and(|b| b.contains("zoxide init bash --cmd j")));
}
#[test]
fn pending_init_block_skips_when_user_already_wired_zoxide() {
let existing = "eval \"$(zoxide init zsh --cmd j)\"\n";
assert_eq!(
pending_init_block("zsh", existing),
None,
"an existing user `zoxide init` line must suppress croft's block"
);
}
#[test]
fn pending_init_block_is_idempotent_across_relaunches() {
let once = init_block("bash");
assert_eq!(
pending_init_block("bash", &once),
None,
"croft's own block must suppress a second append"
);
}
}