croft-software 0.2.182

VSCode-style TUI written in Rust
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! zoxide integration for the Explorer "jump" popup (Cmd+Z).
//!
//! croft delegates all directory ranking to the `zoxide` binary rather
//! than parsing its database: `zoxide query -l <tokens>` returns the
//! frecency-ranked matches, exactly the algorithm the user already gets
//! from `j <tokens>` in the shell (their init is `zoxide init zsh --cmd j`).
//!
//! GOLDEN RULE — identical local/remote: croft runs *on* the host (the
//! user's Mac locally, a Linux box under the remote-launch flow), so we
//! invoke whichever `zoxide` lives on that host and read that host's own
//! frecency database. The same code path serves both platforms, and the
//! database naturally stays consistent with the terminal pane's own
//! zoxide `chpwd` hook (the `cd` croft writes to the PTY bumps the score).
//!
//! croft never installs zoxide on its own (#926). Launching croft fetches
//! and runs nothing: when the binary is missing, the popup says so, shows
//! the exact installer command and the rc file it would edit, and asks
//! `[y/N]`. Only a `y` runs `install_in_background` (the official
//! cross-platform installer, no root, installs to `~/.local/bin`; `pkg` on
//! Termux). A failed attempt is remembered for the session with its reason,
//! which the popup shows instead of retrying; another `y` tries again.
//!
//! The same consented step also wires zoxide's shell hook into the host's
//! shell rc (`~/.zshrc` / `~/.bashrc`) so the terminal pane's `j` command
//! and the popup share one populated database — without it a fresh remote
//! has the binary but an empty database that no `cd` ever feeds, the exact
//! local/remote divergence the GOLDEN RULE forbids. The write is idempotent:
//! it is skipped whenever the rc already contains a `zoxide init` line (the
//! user's own, or one croft wrote before). Where zoxide was already
//! installed, by hand or a package manager, the popup offers the hook alone
//! while its list is empty, and only a `y` writes it.

use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::lsp::log_file;

/// Official zoxide installer. Cross-platform (macOS + Linux), needs only
/// `curl` + `sh`, and installs a static binary to `~/.local/bin` without
/// root — the same destination `binary()` probes below.
const INSTALL_SCRIPT: &str =
    "curl -sSfL https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | sh";

/// Termux installer. The official curl script can never run on a stock
/// Termux: `curl` is not in the Termux bootstrap. `pkg` always is, zoxide
/// is in the official Termux repo, and a `pkg` install lands in
/// `$PREFIX/bin` — on `PATH` and exec-permitted on every Termux build
/// (Android blocks exec from `$HOME` on some of them).
const TERMUX_INSTALL_SCRIPT: &str = "pkg install -y zoxide";

/// Pick the installer for this host. The popup's install offer shows it
/// verbatim, so the user sees exactly what `y` runs.
pub fn install_script(termux: bool) -> &'static str {
    if termux {
        TERMUX_INSTALL_SCRIPT
    } else {
        INSTALL_SCRIPT
    }
}

/// Lifecycle of the install the user asked for from the Cmd+Z popup,
/// surfaced there so its "unavailable" message can tell the truth: `Idle`
/// until the user says `y`, `Running` while the installer is working,
/// `Failed` once the attempt is over and the binary still cannot be found,
/// `Done` when the binary resolves.
#[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) {
    // Release/Acquire: whoever reads `Failed` also reads the `OUTCOME`
    // written just before it.
    INSTALL_STATE.store(state as u8, std::sync::atomic::Ordering::Release);
}

/// Current install lifecycle, readable from the render path (one atomic
/// load).
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,
    }
}

/// What the last finished install attempt came to, in words for the popup
/// and status bar: why it failed, or which rc file got the shell hook.
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);
    }
}

/// The last finished attempt's outcome (see [`OUTCOME`]); `None` before the
/// user has asked for an install.
pub fn install_outcome() -> Option<String> {
    OUTCOME.lock().ok().and_then(|slot| slot.clone())
}

#[cfg(test)]
thread_local! {
    /// Installs requested on this thread. Under `cfg(test)`
    /// [`install_in_background`] only counts here: a test must never fetch
    /// and run the real installer.
    static INSTALL_REQUESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// How many installs this test thread has asked for.
#[cfg(test)]
pub(crate) fn install_requests() -> usize {
    INSTALL_REQUESTS.with(|n| n.get())
}

/// The `--cmd` name croft wires into the shell, matching the Cmd+Z popup it
/// mirrors: the jump command is `j` (and the interactive `ji`), not the
/// default `z`/`zi`. Kept in sync with the popup's intent in this module.
const ZOXIDE_CMD: &str = "j";

/// Sentinels bracketing the block croft appends to the shell rc, so a prior
/// launch's block is recognisable and never duplicated.
const INIT_MARKER_START: &str = "# >>> croft zoxide (managed) >>>";
const INIT_MARKER_END: &str = "# <<< croft zoxide (managed) <<<";

/// Substring whose presence in an rc file means zoxide is already wired —
/// by the user themselves or by a previous croft run — so croft must not
/// append again. Matches every `zoxide init <shell> …` form.
const INIT_SENTINEL: &str = "zoxide init";

/// Absolute fallbacks probed after `PATH`, covering the default install
/// dir used by the official script (`~/.local/bin`) plus the common
/// Homebrew / system locations. Resolving an absolute path matters
/// because a binary the background installer drops into `~/.local/bin`
/// is not necessarily on croft's inherited `PATH`.
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
}

/// True when `candidate --version` runs and exits zero.
fn probe(candidate: &PathBuf) -> bool {
    Command::new(candidate)
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Resolve an invocable `zoxide`: first the bare name (so a `PATH` install
/// wins), then the absolute fallbacks. `None` means zoxide is not
/// installed on this host.
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))
}

/// Build the `zoxide query` argument vector for `needle`. Whitespace
/// splits the needle into independent keyword tokens, mirroring how the
/// shell `j a b` passes multiple keywords that zoxide subsequence-matches
/// against the path. An empty / whitespace needle yields `query -l`,
/// which lists every entry by score.
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
}

/// Parse `zoxide query -l` stdout into directory paths, dropping blank
/// lines. zoxide prints one absolute path per line, best-ranked first.
pub fn parse_query_output(stdout: &str) -> Vec<PathBuf> {
    stdout
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(PathBuf::from)
        .collect()
}

/// Run `zoxide query -l <needle>` and return the ranked matches.
///
/// `None` => the binary could not be found or spawned (unavailable on
/// this host). `Some(vec)` => zoxide ran; the vec is its ranked output,
/// which is legitimately empty when nothing matches (zoxide exits
/// non-zero on no-match, so a non-zero status is NOT treated as failure).
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)))
}

/// Optimal-string-alignment (restricted Damerau-Levenshtein) distance of
/// `pattern` against `text`, but with a *free* text prefix and suffix so
/// `pattern` is matched as an approximate *substring* of `text`. A single
/// adjacent transposition costs 1 edit, which is the whole point: it is
/// what recovers a typo like `spilt` against the `split` inside
/// `pr-split`, something plain subsequence matching (zoxide's own
/// algorithm, fzf, croft's Cmd+P matcher) can never do because a
/// transposition reorders characters.
///
/// `pattern`/`text` are expected pre-lowercased by the caller.
fn osa_substring_distance(pattern: &[char], text: &[char]) -> usize {
    let n = pattern.len();
    let m = text.len();
    if n == 0 {
        return 0;
    }
    // d[i][j] = best edits to match pattern[..i] ending anywhere within
    // text[..j]. Row 0 is all-zero (skipping any text prefix is free);
    // column 0 is i (the pattern char has no text to match against).
    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;
        }
    }
    // Free text suffix: the match may end at any column of the last row.
    d[n].iter().copied().min().unwrap_or(n)
}

/// Maximum edit distance tolerated for a needle of `len` characters. Kept
/// deliberately tight (≈ one edit per three chars, never more than three)
/// so this *fallback* surfaces genuine typos without flooding the popup
/// with loosely-related directories.
fn fuzzy_threshold(len: usize) -> usize {
    (len / 3).clamp(1, 3)
}

/// The basename used for fuzzy matching: the final path component,
/// lowercased into a `char` vector. zoxide matches its last keyword
/// against the final component, so the fallback mirrors that — fuzzing the
/// whole absolute path would let the long shared prefix dominate the score.
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()
}

/// Typo-tolerant fallback ranking over the cached zoxide database `dirs`
/// (already in frecency order). Used only when the strict `query` returns
/// no matches: the last whitespace token of `needle` is matched against
/// each directory's basename with `osa_substring_distance`, entries within
/// `fuzzy_threshold` are kept, and the survivors are sorted by edit
/// distance ascending, breaking ties by the original frecency order so the
/// most-used directory wins an equal-distance tie.
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()
}

/// Normalise a `$SHELL` path to the shell name croft knows how to wire,
/// or `None` for anything else (we never guess an rc layout for an
/// unfamiliar shell). Only `zsh` and `bash` are supported — the two shells
/// croft actually launches (zsh on the Mac, bash on the Linux remote).
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,
    }
}

/// The rc file croft appends the init block to for a (already validated)
/// shell. bash targets `~/.bashrc` (zoxide's documented target; the login
/// shell reaches it via `~/.profile` sourcing `~/.bashrc`), zsh targets
/// `~/.zshrc` (sourced for every interactive zsh).
fn rc_file_name(shell: &str) -> &'static str {
    match shell {
        "zsh" => ".zshrc",
        _ => ".bashrc",
    }
}

/// The rc file an install would wire the hook into for `shell_path` (a
/// `$SHELL` value), as the user would type it (`~/.bashrc`); `None` when the
/// shell is unset or unsupported, so no rc file would be touched.
fn rc_hint(shell_path: Option<&str>) -> Option<String> {
    supported_shell(shell_path?).map(|shell| format!("~/{}", rc_file_name(shell)))
}

/// [`rc_hint`] for this process's `$SHELL`: what the popup's install offer
/// names before the user agrees to anything.
pub fn shell_rc_hint() -> Option<String> {
    rc_hint(std::env::var("SHELL").ok().as_deref())
}

/// The rc file to offer zoxide's shell hook to when zoxide is already
/// installed but that rc has no `zoxide init` line (#926): the hook no
/// longer goes in at launch, and without it no terminal `cd` reaches the
/// jump list. `None` for an unsupported shell, an unknown `$HOME`, or an rc
/// that has a hook already.
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)
}

/// [`missing_hook_rc`] for this process's `$SHELL` and `$HOME`.
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! {
    /// Hook additions requested on this thread. Under `cfg(test)`
    /// [`add_shell_hook`] only counts here: a test must never edit the
    /// user's rc.
    static HOOK_REQUESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// How many hook additions this test thread has asked for.
#[cfg(test)]
pub(crate) fn hook_requests() -> usize {
    HOOK_REQUESTS.with(|n| n.get())
}

/// Add zoxide's shell hook to the rc, on the user's `y` to the jump popup's
/// hook offer (#926). Returns the rc file (`~/.bashrc`) when it was written.
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()
}

/// The managed block croft appends for `shell`: prepend `~/.local/bin` to
/// `PATH` (so the binary croft drops there is reachable before the eval),
/// then install zoxide's `cd` hook and the `j` command. Wrapped in marker
/// comments and led by a blank line so it never fuses onto existing content.
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"
    )
}

/// Decide what (if anything) to append to an rc file whose current contents
/// are `existing`. `None` means already wired — the rc contains a
/// `zoxide init` line, whether the user's own or a prior croft block — so
/// croft leaves it untouched. This is the idempotency guard that keeps
/// repeated launches from duplicating the block.
fn pending_init_block(shell: &str, existing: &str) -> Option<String> {
    if existing.contains(INIT_SENTINEL) {
        return None;
    }
    Some(init_block(shell))
}

/// Wire zoxide's shell hook into the host's shell rc so the terminal `j`
/// command and the Cmd+Z popup share one database. Best-effort and
/// idempotent: resolves `$SHELL`/`$HOME`, skips unsupported shells, and
/// appends only when no `zoxide init` line is already present. Returns the
/// rc file (`~/.bashrc`) when it appended the block, so the user is told.
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
}

/// Why a failed installer run failed, in one line: the last non-blank line
/// of its stderr (zoxide's script ends on `Error: …`), else its exit status.
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,
        )
}

/// Install zoxide on a detached thread, then wire the shell hook. Called
/// only when the user answers `y` to the jump popup's offer: croft never
/// fetches or runs an installer, or edits a shell rc, on its own (#926).
/// One attempt at a time; the outcome is recorded before the state flips,
/// so whoever sees `Failed` also finds the reason.
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());
        // The outcome is logged, never discarded: a host where the
        // installer can't run (e.g. it once piped curl on a stock
        // Termux, which has no curl) used to fail in total silence
        // while the popup claimed "installing".
        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}"))
            }
        };
        // Wire the shell hook only once the binary is actually resolvable,
        // otherwise the `eval "$(zoxide init …)"` line errors on every shell
        // start. `binary()` finds the freshly-installed `~/.local/bin` copy
        // even though it is not yet on the login shell's PATH — which is why
        // the appended block prepends that dir before the eval.
        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() {
        // The free prefix/suffix means `spilt` is found against the
        // `split` buried in `pr-split` at the cost of the one transposition.
        let p: Vec<char> = "spilt".chars().collect();
        let t: Vec<char> = "pr-split".chars().collect();
        assert_eq!(osa_substring_distance(&p, &t), 1);
        // Exact substring is free.
        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() {
        // `docs` is an exact substring (distance 0) of the first two; the
        // earlier (more frecent) one must win the tie. `dosc` is a
        // transposition (distance 1) so the exact hits rank ahead of it.
        let dirs = vec![
            PathBuf::from("/a/docs"),       // rank 0, dist 0
            PathBuf::from("/b/my-docs"),    // rank 1, dist 0
            PathBuf::from("/c/dosc-stuff"), // rank 2, dist 1
            PathBuf::from("/d/unrelated"),  // dropped
        ];
        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() {
        // Mirrors zoxide's "last keyword matches the final component":
        // the leading `pr` token is ignored, `spilt` drives the match.
        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");
    }

    /// #926: zoxide already on the host is offered the hook only for a
    /// supported shell whose rc has no `zoxide init` line yet.
    #[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() {
        // #926: the line zoxide's install.sh ends on for an unpackaged arch.
        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() {
        // The Mac case: the user's own `~/.zshrc` line. croft must never
        // append a duplicate on top of it.
        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() {
        // A second launch sees the block croft wrote on the first and must
        // not append it again (the block itself contains `zoxide init`).
        let once = init_block("bash");
        assert_eq!(
            pending_init_block("bash", &once),
            None,
            "croft's own block must suppress a second append"
        );
    }
}