croft-software 0.2.232

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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! debugpy environment provisioning.
//!
//! croft owns a dedicated debug virtualenv at `~/.croft/debug-venv` rather than
//! installing debugpy into the user's interpreter: PEP 668 marks the uv-managed
//! CPython externally-managed (pip refuses), and polluting the user's Python
//! would be wrong regardless. Mirrors the `~/.croft/servers` LSP store. The venv
//! is built from CPython 3.14+ (`uv venv -p 3.14`), with no fallback to older
//! interpreters; it hosts the debugpy adapter, while a launched program runs
//! under the project's own interpreter (#864). The 3.14 floor on the program
//! itself is attach's (PEP 768), not launch's.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use anyhow::{Context, Result, bail};

use crate::dap::remote_attach::PyVersion;

/// Minimum CPython line croft debugs. `uv` resolves the newest matching.
const PYTHON_VERSION: &str = "3.14";

/// Pinned vscode-js-debug release. The `js-debug-dap-vX.Y.Z.tar.gz` asset is the
/// bundled standalone debug server (the same artifact Zed and nvim/Mason use);
/// it extracts to `js-debug/src/dapDebugServer.js`. Bump deliberately, and
/// [`JS_DEBUG_SHA256`] with it.
const JS_DEBUG_VERSION: &str = "v1.117.0";

/// SHA-256 of the [`JS_DEBUG_VERSION`] release's `js-debug-dap-*.tar.gz` asset.
/// The download is checked against it before a byte is unpacked: an altered
/// asset or a tampered delivery path is refused, never installed and run.
const JS_DEBUG_SHA256: &str = "ad8d04ede9d4b75cc290fd5438a65047a06f786d04f604b6112485b36f090772";

/// Cap on the js-debug tarball download (the v1.117 asset is ~1.2 MB; this is a
/// generous ceiling that still refuses a runaway/redirected body).
const MAX_JS_DEBUG_BYTES: u64 = 64 * 1024 * 1024;

/// Oldest CPython a launched program may run under: debugpy 1.8 declares
/// `Requires-Python >=3.10`, and the code it injects into the program's
/// interpreter does not load on an older one (#864). Attach's own floor is
/// [`crate::dap::remote_attach::MIN_ATTACH_VERSION`].
pub const DEBUGPY_MIN_PYTHON: PyVersion = PyVersion {
    major: 3,
    minor: 10,
    patch: 0,
};

/// The `pyvenv.cfg` of the venv `python` belongs to (`<venv>/bin/python`),
/// when there is one.
pub fn pyvenv_cfg(python: &Path) -> Option<PathBuf> {
    let cfg = python.parent()?.parent()?.join("pyvenv.cfg");
    cfg.is_file().then_some(cfg)
}

/// The version of the interpreter at `python` (#864): from its venv's
/// `pyvenv.cfg` when it has one (`version =` from `python -m venv`,
/// `version_info =` from uv and virtualenv), else by running it once. None
/// when neither says.
pub fn python_version(python: &Path) -> Option<PyVersion> {
    let from_cfg = pyvenv_cfg(python)
        .and_then(|cfg| std::fs::read_to_string(cfg).ok())
        .and_then(|text| {
            text.lines().find_map(|line| {
                let (key, value) = line.split_once('=')?;
                matches!(key.trim(), "version" | "version_info").then(|| PyVersion::parse(value))?
            })
        });
    if from_cfg.is_some() {
        return from_cfg;
    }
    let out = run_probe(
        Command::new(python).args(["-c", "import sys; print('%d.%d' % sys.version_info[:2])"]),
        Duration::from_secs(5),
        crate::proc::Apart::No,
    )?;
    PyVersion::parse(&out)
}

/// Ensure the debug venv exists with debugpy, creating it via `uv` on first use.
/// Returns the venv interpreter path. Slow the first time: it shells out to
/// `uv venv` + `uv pip install debugpy`, each for at most [`SETUP_STEP_LIMIT`],
/// so a launch runs it on a job, never on the UI thread ([`DebugTooling`],
/// #2803); later calls are a cheap existence check.
pub fn ensure_debug_venv() -> Result<PathBuf> {
    let home =
        std::env::var_os("HOME").context("$HOME unset; cannot locate ~/.croft/debug-venv")?;
    ensure_debug_venv_in(Path::new(&home), std::env::var_os("PATH").as_deref())
}

/// [`ensure_debug_venv`] under the home folder `home`, with `path_var` as
/// `PATH`: the venv is `~/.croft/debug-venv`, and its interpreter runs
/// `-m debugpy.adapter` only. The program being debugged runs under the
/// project's own interpreter (#864): debugpy injects itself there, so
/// neither debugpy nor 3.14 is required of it. The venv is built with the
/// uv the language servers use (#2804): on PATH, else croft's own copy or
/// one where uv's installer puts it.
fn ensure_debug_venv_in(home: &Path, path_var: Option<&std::ffi::OsStr>) -> Result<PathBuf> {
    if let Some(py) = debug_venv_ready_in(home) {
        return Ok(py);
    }
    // One build at a time: a launch made while another prepares the venv
    // waits for it, then finds it built, instead of a second `uv venv`
    // writing over the first.
    static BUILDING: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _building = BUILDING
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if let Some(py) = debug_venv_ready_in(home) {
        return Ok(py);
    }
    let py = debug_venv_python_in(home);
    let dir = home.join(".croft").join("debug-venv");
    let uv = crate::lsp::install::uv_program_on(Some(home), path_var)
        .context("uv is not installed; install it (https://docs.astral.sh/uv) to debug Python")?;
    // Never on croft's terminal: uv paints progress bars on stderr, and an
    // inherited TTY would spray them over the running TUI (same class as the
    // pdftoppm trailer-dictionary spray).
    // A venv left without debugpy, by an install that failed or never
    // finished, gets debugpy now rather than a second `uv venv`.
    if !py.exists() {
        let mut venv = Command::new(&uv);
        venv.args(["venv", "-p", PYTHON_VERSION]).arg(&dir);
        setup_step(&mut venv, "`uv venv`", |why| {
            format!(
                "`uv venv -p {PYTHON_VERSION}` failed (is CPython {PYTHON_VERSION} available?): {why}"
            )
        })?;
    }
    let mut pip = Command::new(&uv);
    pip.args(["pip", "install", "--python"])
        .arg(&py)
        .arg("debugpy");
    setup_step(&mut pip, "`uv pip install debugpy`", |why| {
        format!("`uv pip install debugpy` failed: {why}")
    })?;
    Ok(py)
}

/// The debug venv's interpreter under the home folder `home`, once the venv
/// is whole: its `python` there and debugpy installed beside it. A venv
/// whose `uv pip install debugpy` has not finished, or failed, is not ready
/// (#2803): `python -m debugpy.adapter` would fail under it.
fn debug_venv_ready_in(home: &Path) -> Option<PathBuf> {
    let py = debug_venv_python_in(home);
    let venv = home.join(".croft").join("debug-venv");
    (py.exists() && debugpy_installed(&venv)).then_some(py)
}

/// Whether debugpy is installed in the venv at `venv`: its package in the
/// venv's `lib/python3.*/site-packages`, read without starting Python.
fn debugpy_installed(venv: &Path) -> bool {
    std::fs::read_dir(venv.join("lib"))
        .into_iter()
        .flatten()
        .flatten()
        .any(|entry| {
            entry.file_name().to_string_lossy().starts_with("python")
                && entry
                    .path()
                    .join("site-packages")
                    .join("debugpy")
                    .join("__init__.py")
                    .is_file()
        })
}

/// The debug venv's interpreter under the home folder `home`.
fn debug_venv_python_in(home: &Path) -> PathBuf {
    home.join(".croft")
        .join("debug-venv")
        .join("bin")
        .join("python")
}

/// The longest one step of preparing a debugger may take (#2803): a venv
/// built, debugpy or js-debug downloaded. Far past any of them on a working
/// network; a stalled one ends with that said instead of a debugger that
/// never starts.
pub(crate) const SETUP_STEP_LIMIT: Duration = Duration::from_secs(300);

/// Run one setup step, `cmd`, called `what`, for at most
/// [`SETUP_STEP_LIMIT`]; a failing exit is reported through `failed`, given
/// the end of what the step printed to stderr.
fn setup_step(cmd: &mut Command, what: &str, failed: impl FnOnce(&str) -> String) -> Result<()> {
    use crate::proc::{Apart, Bounded, Keep, RunError};
    let ran = Bounded {
        stdout: Keep::Nothing,
        stderr: Keep::Tail(16 * 1024),
        apart: Apart::No,
        limit: SETUP_STEP_LIMIT,
        retry_busy: true,
    }
    .run(cmd);
    match ran {
        Ok(ran) if ran.status.success() => Ok(()),
        Ok(ran) => bail!(failed(ran.stderr.text().trim())),
        Err(RunError::TimedOut) => bail!("{what} took longer than {}s", SETUP_STEP_LIMIT.as_secs()),
        Err(RunError::Spawn(e)) => Err(e).context(format!("running {what}")),
        Err(RunError::TooLong { .. }) => bail!("{what} printed more than croft keeps"),
        Err(RunError::Wait(e) | RunError::Pipe(e)) => Err(e).context(format!("waiting on {what}")),
    }
}

/// The tooling a debug launch can need prepared before it starts (#2803).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Tooling {
    /// The debug venv, with debugpy, for Python.
    Python,
    /// `node` and the js-debug server, for JavaScript and TypeScript.
    Js,
}

impl Tooling {
    /// What the status bar says while it is prepared.
    pub(crate) fn preparing(self) -> &'static str {
        match self {
            Tooling::Python => "Setting up the Python debugger…",
            Tooling::Js => "Setting up the JavaScript debugger…",
        }
    }
}

/// A launch's tooling, prepared.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Ready {
    /// The debug venv's interpreter, which runs `-m debugpy.adapter`.
    Python(PathBuf),
    /// `node` and the js-debug server it runs.
    Js { node: String, server: PathBuf },
}

/// What a debug launch needs from this machine before it starts (#2803):
/// whether that is ready now, a check of a few files the UI thread makes,
/// and the slow work that makes it so (a venv built, node asked of the login
/// shell, js-debug downloaded), which runs on a job. A test puts a stand-in
/// in its place.
pub(crate) trait DebugTooling: Send + Sync {
    /// `tooling`, when it is ready without waiting on anything.
    fn ready(&self, tooling: Tooling) -> Option<Ready>;
    /// Make `tooling` ready; or what to tell the user when it cannot be.
    fn prepare(&self, tooling: Tooling) -> std::result::Result<(), String>;
}

/// This machine's debugger tooling.
pub(crate) struct MachineTooling;

impl DebugTooling for MachineTooling {
    fn ready(&self, tooling: Tooling) -> Option<Ready> {
        match tooling {
            Tooling::Python => {
                let home = std::env::var_os("HOME")?;
                debug_venv_ready_in(Path::new(&home)).map(Ready::Python)
            }
            Tooling::Js => {
                let server = js_debug_server_path(&js_debug_dir()?);
                let node = known_node()?;
                server.exists().then_some(Ready::Js { node, server })
            }
        }
    }

    fn prepare(&self, tooling: Tooling) -> std::result::Result<(), String> {
        match tooling {
            Tooling::Python => ensure_debug_venv()
                .map(drop)
                .map_err(|e| format!("Debugger setup failed: {e}")),
            Tooling::Js => {
                node_program().map_err(|e| e.to_string())?;
                ensure_js_debug()
                    .map(drop)
                    .map_err(|e| format!("Debugger setup failed: {e}"))
            }
        }
    }
}

/// `~/.croft/js-debug`, the install root for the vscode-js-debug server.
pub(crate) fn js_debug_dir() -> Option<PathBuf> {
    let home = std::env::var_os("HOME")?;
    Some(PathBuf::from(home).join(".croft").join("js-debug"))
}

/// Path to the extracted `dapDebugServer.js` (the standalone DAP server).
fn js_debug_server_path(dir: &Path) -> PathBuf {
    dir.join("js-debug").join("src").join("dapDebugServer.js")
}

/// Resolve the `node` runtime croft launches the js-debug server (and the
/// debuggee) with, returning an absolute path or the bare `node` command:
/// `node` on croft's `PATH`, else the one [`crate::node::dir`] finds, the
/// node the language servers run under (nvm, Volta, Homebrew, then the
/// login shell, #2809). Errors with an actionable hint when node genuinely
/// cannot be found.
///
/// Can ask the login shell once per process; a launch calls it on a job,
/// never on the UI thread (#2803).
pub fn node_program() -> Result<String> {
    if which("node") {
        return Ok(String::from("node"));
    }
    crate::node::dir()
        .and_then(|dir| node_in(&dir))
        .context("`node` not found on PATH; install Node.js to debug JavaScript/TypeScript")
}

/// A node known without asking a shell: one on PATH, or the one
/// [`crate::node::known_dir`] holds.
fn known_node() -> Option<String> {
    if which("node") {
        return Some(String::from("node"));
    }
    node_in(&crate::node::known_dir()?)
}

/// The node in `dir`, while it can run.
fn node_in(dir: &Path) -> Option<String> {
    let node = dir.join("node");
    crate::proc::find::runnable(&node).then(|| node.to_string_lossy().into_owned())
}

/// The directory containing the resolved node binary, when it is an absolute
/// path. Prepended to the js-debug server's PATH so the *debuggee* node process
/// js-debug spawns (with a bare `node`) resolves to the same runtime.
pub fn node_bin_dir(node: &str) -> Option<PathBuf> {
    let p = Path::new(node);
    p.is_absolute().then(|| p.parent().map(Path::to_path_buf))?
}

/// Run a probe, `cmd`, to its exit or `timeout`: a program asked one
/// question whose answer it prints last, such as a login shell asked where
/// `node` is (a shell with a chatty or blocking rc must never wedge croft).
/// Returns the end of its stdout, decoded lossily so one stray byte from an
/// rc cannot hide the rest, or `None` when it could not start or outlived
/// `timeout`.
///
/// Its stdout is read as it runs, so an rc that prints more than a pipe
/// holds cannot block the probe, and only the last [`PROBE_TAIL`] bytes are
/// kept, where the answer is. One that runs in a session of its own
/// ([`crate::proc::Apart::Session`]), as [`crate::node`]'s probe does, is
/// killed with everything it started once croft is done with it, at its
/// exit or at `timeout`, so whatever its rc left running goes with it
/// (#2755).
pub(crate) fn run_probe(
    cmd: &mut Command,
    timeout: Duration,
    apart: crate::proc::Apart,
) -> Option<String> {
    // A program written a moment ago (a test's stand-in interpreter) is "Text
    // file busy" while another thread's forked child still holds its write
    // descriptor; that read as "no version" instead of waiting it out.
    let ran = crate::proc::Bounded {
        stdout: crate::proc::Keep::Tail(PROBE_TAIL),
        stderr: crate::proc::Keep::Nothing,
        apart,
        limit: timeout,
        retry_busy: true,
    }
    .run(cmd)
    .ok()?;
    Some(ran.stdout.text())
}

/// How much of a probe's stdout [`run_probe`] keeps: its last 64 KiB, which
/// hold its answer after any rc chatter before it.
pub(crate) const PROBE_TAIL: usize = 64 * 1024;

/// Whether `bin` resolves on PATH (a `command -v` check via the shell-less
/// `which`-style scan of PATH entries).
fn which(bin: &str) -> bool {
    crate::proc::find::on_path(bin).is_some()
}

/// Ensure the vscode-js-debug server is installed, downloading + extracting the
/// pinned release tarball on first use. Returns the path to `dapDebugServer.js`.
/// Slow the first time: it downloads ~1.2 MB and shells out to `tar`, each for
/// at most [`SETUP_STEP_LIMIT`], on a launch's setup job (#2803); later calls
/// are a cheap existence check. Mirrors [`ensure_debug_venv`].
pub fn ensure_js_debug() -> Result<PathBuf> {
    let dir = js_debug_dir().context("$HOME unset; cannot locate ~/.croft/js-debug")?;
    let server = js_debug_server_path(&dir);
    if server.exists() {
        return Ok(server);
    }
    // One download at a time; a second launch waits, then finds it.
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _fetching = FETCHING
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if server.exists() {
        return Ok(server);
    }
    std::fs::create_dir_all(&dir).context("creating ~/.croft/js-debug")?;

    let url = format!(
        "https://github.com/microsoft/vscode-js-debug/releases/download/{JS_DEBUG_VERSION}/js-debug-dap-{JS_DEBUG_VERSION}.tar.gz"
    );
    let tarball = dir.join("js-debug-dap.tar.gz");
    download_to_file(&url, &tarball)?;

    // The asset extracts a top-level `js-debug/` directory; -C lands it under
    // ~/.croft/js-debug so the server is at js-debug/src/dapDebugServer.js.
    let mut tar = Command::new("tar");
    tar.arg("-xzf").arg(&tarball).arg("-C").arg(&dir);
    let extracted = setup_step(&mut tar, "`tar -xzf` on the js-debug release", |why| {
        format!("extracting the js-debug release failed: {why}")
    });
    let _ = std::fs::remove_file(&tarball);
    extracted?;
    if !server.exists() {
        bail!("js-debug release did not contain dapDebugServer.js (layout changed?)");
    }
    Ok(server)
}

/// Download `url` to `dest`, refusing a body over [`MAX_JS_DEBUG_BYTES`] and
/// one that is not the pinned release. Follows redirects (the GitHub release
/// URL 302s to a CDN).
fn download_to_file(url: &str, dest: &Path) -> Result<()> {
    let resp = crate::net::get(url)
        .timeout(SETUP_STEP_LIMIT)
        .call()
        .context("downloading js-debug release")?;
    let bytes = crate::net::read_capped(resp.into_reader(), MAX_JS_DEBUG_BYTES)
        .context("reading js-debug release body")?;
    verify_js_debug(&bytes)?;
    std::fs::write(dest, &bytes).context("writing js-debug release tarball")?;
    Ok(())
}

/// Accept a js-debug download only when it is the pinned release byte for
/// byte ([`JS_DEBUG_SHA256`]).
fn verify_js_debug(bytes: &[u8]) -> Result<()> {
    if crate::net::sha256_matches(bytes, JS_DEBUG_SHA256) {
        return Ok(());
    }
    bail!("the js-debug {JS_DEBUG_VERSION} download failed its checksum; refusing to install it")
}

/// Where `dlv` is, for Go debugging (#264), in delve's own resolution order:
/// `PATH`, then `$GOBIN`, then each `bin` of the folders `$GOPATH` lists
/// (default `~/go/bin`), then croft's servers directory. Pure over its
/// inputs so the order is testable.
pub fn find_dlv(
    path_env: Option<&std::ffi::OsStr>,
    gobin: Option<&Path>,
    gopath: Option<&std::ffi::OsStr>,
    home: Option<&Path>,
) -> Option<PathBuf> {
    let mut dirs: Vec<PathBuf> = path_env
        .map(|p| std::env::split_paths(p).collect())
        .unwrap_or_default();
    dirs.extend(gobin.map(Path::to_path_buf));
    // `go` reads GOPATH as a list and refuses an entry that is not
    // absolute (#2805); such an entry, read here, would be a folder of
    // croft's own.
    match gopath {
        Some(gp) => dirs.extend(
            std::env::split_paths(gp)
                .filter(|dir| dir.is_absolute())
                .map(|dir| dir.join("bin")),
        ),
        None => dirs.extend(home.map(|h| h.join("go").join("bin"))),
    }
    dirs.extend(home.map(|h| h.join(".croft").join("servers").join("go")));
    crate::proc::find::first_in("dlv", dirs)
}

/// The command "Debug: Install Go Debugger (delve)" runs, visibly, in a
/// terminal pane (#264). `GOBIN` puts `dlv` in croft's servers directory,
/// the last place [`find_dlv`] looks, so it never shadows a delve the user
/// installed themselves.
///
/// The delve it installs is one that debugs with the Go on this machine:
/// delve refuses a Go older than it supports (1.27 wants Go 1.25 or later),
/// so Go 1.24 and older get delve 1.25.2, the last release that takes them,
/// and anything newer gets `@latest`. Wrapped in `sh -c`, since it is typed
/// into whatever shell the pane runs, fish included. It runs `go`, the Go
/// croft found ([`crate::proc::find::go`], #2807), by its path: the pane's
/// shell may not have the official installer's folder on its `PATH`.
pub fn dlv_install_command(go: &Path) -> String {
    let go = sh_double_quoted(&go.to_string_lossy());
    let script = format!(
        "case \"$({go} env GOVERSION)\" in go1.[0-9]|go1.[0-9].*|go1.1[0-9]*|go1.2[0-4]*) v=v1.25.2 ;; *) v=latest ;; esac; GOBIN=\"$HOME/.croft/servers/go\" {go} install github.com/go-delve/delve/cmd/dlv@$v"
    );
    format!("sh -c '{}'", script.replace('\'', "'\\''"))
}

/// `text` in double quotes for `sh`, with what is special inside them
/// escaped.
fn sh_double_quoted(text: &str) -> String {
    let mut quoted = String::from("\"");
    for c in text.chars() {
        if matches!(c, '"' | '\\' | '$' | '`') {
            quoted.push('\\');
        }
        quoted.push(c);
    }
    quoted.push('"');
    quoted
}

/// Whether there is a Go to install delve with: the one every feature
/// uses ([`crate::proc::find::go`], #2807).
pub fn go_on_path() -> bool {
    crate::proc::find::go().is_some()
}

/// Why Go debugging cannot start, and the next step. Without Go there is
/// nothing to install delve with, which is a different fix.
pub fn dlv_missing_message(go_available: bool) -> String {
    if go_available {
        String::from(
            "Go debugging needs delve: run Debug: Install Go Debugger (delve) to `go install` it",
        )
    } else {
        String::from(
            "Go debugging needs delve, and installing delve needs Go: install Go from https://go.dev/dl, then run Debug: Install Go Debugger (delve)",
        )
    }
}

/// `dlv` for this machine, or an error that says how to install it.
pub fn dlv_program() -> Result<PathBuf> {
    let gobin = std::env::var_os("GOBIN").map(PathBuf::from);
    let gopath = std::env::var_os("GOPATH");
    let home = std::env::var_os("HOME").map(PathBuf::from);
    find_dlv(
        std::env::var_os("PATH").as_deref(),
        gobin.as_deref(),
        gopath.as_deref(),
        home.as_deref(),
    )
    .ok_or_else(|| anyhow::anyhow!(dlv_missing_message(go_on_path())))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The js-debug pin is a full SHA-256, and a body that is not the pinned
    /// release (here a stand-in, an empty body, and a valid gzip header) is
    /// refused before anything is written or unpacked.
    #[test]
    fn a_js_debug_download_that_is_not_the_pinned_release_is_refused() {
        assert_eq!(JS_DEBUG_SHA256.len(), 64);
        assert!(
            JS_DEBUG_SHA256
                .chars()
                .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
            "{JS_DEBUG_SHA256}"
        );
        for body in [&b"not the release"[..], b"", &[0x1f, 0x8b, 0x08, 0x00]] {
            let why = verify_js_debug(body).unwrap_err().to_string();
            assert!(why.contains("failed its checksum"), "{why}");
        }
    }

    /// The pinned js-debug release still hashes to [`JS_DEBUG_SHA256`].
    /// `#[ignore]`d because it hits the network; run it when bumping
    /// [`JS_DEBUG_VERSION`]: `cargo test --bin croft -- --ignored pinned_js_debug`.
    #[test]
    #[ignore = "downloads the js-debug release from GitHub"]
    fn the_pinned_js_debug_release_matches_its_checksum() {
        let url = format!(
            "https://github.com/microsoft/vscode-js-debug/releases/download/{JS_DEBUG_VERSION}/js-debug-dap-{JS_DEBUG_VERSION}.tar.gz"
        );
        let resp = crate::net::get(&url).call().expect("download js-debug");
        let bytes = crate::net::read_capped(resp.into_reader(), MAX_JS_DEBUG_BYTES).unwrap();
        verify_js_debug(&bytes).expect("the pinned digest matches the release");
    }

    /// #264: the install picks the delve that debugs with this machine's
    /// Go: 1.25.2 for Go 1.24 and older (delve 1.27 refuses them), latest
    /// otherwise. Run as the pane would, through `sh`, against a stub `go`.
    #[cfg(unix)]
    #[test]
    fn the_delve_install_follows_the_local_go_version() {
        use std::os::unix::fs::PermissionsExt;
        for (goversion, want) in [
            ("go1.24.7", "dlv@v1.25.2"),
            ("go1.22rc1", "dlv@v1.25.2"),
            ("go1.9", "dlv@v1.25.2"),
            ("go1.25.0", "dlv@latest"),
            ("go1.26.1", "dlv@latest"),
            ("go1.30", "dlv@latest"),
        ] {
            let tmp = tempfile::tempdir().unwrap();
            let log = tmp.path().join("go.log");
            let go = tmp.path().join("go");
            std::fs::write(
                &go,
                format!(
                    "#!/bin/sh\nif [ \"$1\" = env ]; then echo {goversion}; exit 0; fi\necho \"GOBIN=$GOBIN $*\" > \"{}\"\n",
                    log.display()
                ),
            )
            .unwrap();
            std::fs::set_permissions(&go, std::fs::Permissions::from_mode(0o755)).unwrap();
            // Not on PATH: the command names the Go croft found (#2807).
            let ok = std::process::Command::new("sh")
                .arg("-c")
                .arg(dlv_install_command(&go))
                .env("PATH", "/usr/bin:/bin")
                .env("HOME", tmp.path())
                .status()
                .unwrap()
                .success();
            assert!(ok, "{goversion}");
            let ran = std::fs::read_to_string(&log).unwrap();
            assert!(ran.trim_end().ends_with(want), "{goversion}: {ran}");
            assert!(
                ran.starts_with(&format!(
                    "GOBIN={}/.croft/servers/go install ",
                    tmp.path().display()
                )),
                "{ran}"
            );
        }
    }

    /// A login shell with a chatty rc (a `fastfetch` banner, `set -x`
    /// tracing) can emit more than the OS pipe buffer. The child then blocks
    /// in write() and never exits, so waiting for exit before reading
    /// deadlocks until the timeout and reports node as missing. Output must
    /// be drained while the child runs.
    #[test]
    fn a_probe_survives_output_larger_than_the_pipe_buffer() {
        let out = run_probe(
            Command::new("/bin/sh").args(["-c", "yes croft | head -c 200000; echo answer"]),
            Duration::from_secs(3),
            crate::proc::Apart::No,
        )
        .expect("the probe answers");
        assert_eq!(out.len(), PROBE_TAIL, "only the end is kept");
        assert!(out.ends_with("answer\n"), "{:?}", &out[out.len() - 20..]);
    }

    #[test]
    fn node_bin_dir_is_the_parent_of_an_absolute_node_path() {
        assert_eq!(
            node_bin_dir("/Users/x/.nvm/versions/node/v23.7.0/bin/node"),
            Some(PathBuf::from("/Users/x/.nvm/versions/node/v23.7.0/bin"))
        );
    }

    #[test]
    fn node_bin_dir_is_none_for_a_bare_command() {
        // A bare `node` (already on PATH) has no directory to inject.
        assert_eq!(node_bin_dir("node"), None);
    }

    #[test]
    fn a_missing_delve_says_whether_go_is_there_to_install_it() {
        let with_go = dlv_missing_message(true);
        assert!(with_go.contains("Debug: Install Go Debugger (delve)"));
        assert!(!with_go.contains("go.dev"));
        let without = dlv_missing_message(false);
        assert!(without.contains("installing delve needs Go"));
        assert!(without.contains("https://go.dev/dl"));
        // The install lands where find_dlv looks last, built by the Go
        // croft found.
        assert!(
            dlv_install_command(Path::new("/usr/local/go/bin/go"))
                .contains("GOBIN=\"$HOME/.croft/servers/go\" \"/usr/local/go/bin/go\" install ")
        );
    }

    /// An empty program at `path` that can run.
    fn runnable_stand_in(path: &Path) {
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::write(path, "").unwrap();
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    /// #264: delve's own resolution order, PATH first; `~/go/bin` stands in
    /// for an unset GOPATH, and croft's servers dir comes last.
    #[test]
    fn find_dlv_searches_path_then_gobin_then_gopath_then_croft() {
        let tmp = tempfile::tempdir().unwrap();
        let mk = |rel: &str| {
            let dir = tmp.path().join(rel);
            std::fs::create_dir_all(&dir).unwrap();
            runnable_stand_in(&dir.join("dlv"));
            dir
        };
        let on_path = mk("path");
        let gobin = mk("gobin");
        let home = tmp.path().join("home");
        let home_go = mk("home/go/bin");
        let croft = mk("home/.croft/servers/go");
        let path_env = std::env::join_paths([on_path.clone()]).unwrap();
        assert_eq!(
            find_dlv(Some(&path_env), Some(&gobin), None, Some(&home)),
            Some(on_path.join("dlv"))
        );
        assert_eq!(
            find_dlv(None, Some(&gobin), None, Some(&home)),
            Some(gobin.join("dlv"))
        );
        assert_eq!(
            find_dlv(None, None, None, Some(&home)),
            Some(home_go.join("dlv"))
        );
        std::fs::remove_file(home_go.join("dlv")).unwrap();
        assert_eq!(
            find_dlv(None, None, None, Some(&home)),
            Some(croft.join("dlv"))
        );
        assert_eq!(find_dlv(None, None, None, None), None, "nowhere to look");
    }

    /// #2804: the debug venv is built with the uv croft finds for the
    /// language servers, its own copy among them, not only a uv on PATH:
    /// with croft's copy in its servers folder and none on PATH, the venv
    /// is made and debugpy installed with that copy.
    #[cfg(unix)]
    #[test]
    fn the_debug_venv_is_built_with_crofts_own_uv() {
        use std::os::unix::fs::PermissionsExt as _;
        let home = tempfile::tempdir().unwrap();
        let dist = home.path().join(".croft/servers/uv-dist");
        std::fs::create_dir_all(&dist).unwrap();
        let calls = home.path().join("uv-calls");
        let uv = dist.join("uv");
        std::fs::write(
            &uv,
            format!(
                "#!/bin/sh\necho \"$1 $2\" >> '{}'\n\
                 if [ \"$1\" = venv ]; then mkdir -p \"$4/bin\" && : > \"$4/bin/python\"; fi\n",
                calls.display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&uv, std::fs::Permissions::from_mode(0o755)).unwrap();
        let empty = tempfile::tempdir().unwrap();
        let path_var = std::env::join_paths([empty.path()]).unwrap();
        let py = ensure_debug_venv_in(home.path(), Some(&path_var)).unwrap();
        assert_eq!(py, home.path().join(".croft/debug-venv/bin/python"));
        assert_eq!(
            std::fs::read_to_string(&calls).unwrap(),
            "venv -p\npip install\n"
        );
    }

    /// #2803: a venv whose `python` is there but debugpy is not, from an
    /// install that failed or has not finished, is not ready, and the next
    /// setup installs debugpy into it rather than building it again.
    #[test]
    fn a_debug_venv_without_debugpy_is_not_ready_and_gets_it() {
        use std::os::unix::fs::PermissionsExt as _;
        let home = tempfile::tempdir().unwrap();
        let py = home.path().join(".croft/debug-venv/bin/python");
        std::fs::create_dir_all(py.parent().unwrap()).unwrap();
        std::fs::write(&py, "").unwrap();
        assert_eq!(debug_venv_ready_in(home.path()), None, "no debugpy yet");
        let dist = home.path().join(".croft/servers/uv-dist");
        std::fs::create_dir_all(&dist).unwrap();
        let calls = home.path().join("uv-calls");
        let site = home
            .path()
            .join(".croft/debug-venv/lib/python3.14/site-packages/debugpy");
        let uv = dist.join("uv");
        std::fs::write(
            &uv,
            format!(
                "#!/bin/sh\necho \"$1 $2\" >> '{}'\n\
                 if [ \"$1\" = pip ]; then mkdir -p '{}' && : > '{}/__init__.py'; fi\n",
                calls.display(),
                site.display(),
                site.display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&uv, std::fs::Permissions::from_mode(0o755)).unwrap();
        let empty = tempfile::tempdir().unwrap();
        let path_var = std::env::join_paths([empty.path()]).unwrap();
        assert_eq!(
            ensure_debug_venv_in(home.path(), Some(&path_var)).unwrap(),
            py
        );
        assert_eq!(
            std::fs::read_to_string(&calls).unwrap(),
            "pip install\n",
            "debugpy installed into the venv there"
        );
        assert_eq!(debug_venv_ready_in(home.path()), Some(py));
    }

    /// #2805: GOPATH may list several folders, as `go` reads it; delve is
    /// looked for in each one's `bin`, in order, not in a folder named after
    /// the whole list. An empty or relative entry, which `go` refuses, is
    /// passed over rather than read against croft's own folder.
    #[test]
    fn find_dlv_reads_each_folder_a_gopath_lists() {
        let tmp = tempfile::tempdir().unwrap();
        let first = tmp.path().join("first");
        let second = tmp.path().join("second");
        for dir in [&first, &second] {
            std::fs::create_dir_all(dir.join("bin")).unwrap();
        }
        runnable_stand_in(&second.join("bin").join("dlv"));
        let gopath = std::env::join_paths([
            "",
            "relative",
            first.to_str().unwrap(),
            second.to_str().unwrap(),
        ])
        .unwrap();
        assert_eq!(
            find_dlv(None, None, Some(&gopath), None),
            Some(second.join("bin").join("dlv"))
        );
        runnable_stand_in(&first.join("bin").join("dlv"));
        assert_eq!(
            find_dlv(None, None, Some(&gopath), None),
            Some(first.join("bin").join("dlv")),
            "the first folder listed wins"
        );
    }

    /// A stand-in interpreter at `<dir>/<venv>/bin/python`: a shell script
    /// running `body`, with a `pyvenv.cfg` holding `cfg` beside `bin` when
    /// one is given.
    #[cfg(unix)]
    fn stub_python(dir: &Path, venv: &str, body: &str, cfg: Option<&str>) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let bin = dir.join(venv).join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let py = bin.join("python");
        std::fs::write(&py, format!("#!/bin/sh\n{body}\n")).unwrap();
        std::fs::set_permissions(&py, std::fs::Permissions::from_mode(0o755)).unwrap();
        if let Some(cfg) = cfg {
            std::fs::write(dir.join(venv).join("pyvenv.cfg"), cfg).unwrap();
        }
        py
    }

    /// #864: a venv's version is read from its `pyvenv.cfg`, in both
    /// spellings (`version =` from `python -m venv`, `version_info =` from
    /// uv and virtualenv), without running an interpreter that would fail.
    #[cfg(unix)]
    #[test]
    fn python_version_reads_a_venvs_pyvenv_cfg_without_running_it() {
        let tmp = tempfile::tempdir().unwrap();
        let venv = stub_python(
            tmp.path(),
            ".venv",
            "exit 1",
            Some("home = /usr/bin\ninclude-system-site-packages = false\nversion = 3.12.4\n"),
        );
        assert_eq!(
            python_version(&venv).map(|v| (v.major, v.minor)),
            Some((3, 12))
        );
        let uv = stub_python(
            tmp.path(),
            "uv-venv",
            "exit 1",
            Some("home = /opt/py/bin\nimplementation = CPython\nversion_info = 3.14.0rc2\n"),
        );
        assert_eq!(
            python_version(&uv).map(|v| (v.major, v.minor)),
            Some((3, 14))
        );
    }

    /// #864: an interpreter outside a venv (a system `python3`) is asked
    /// once for its version.
    #[cfg(unix)]
    #[test]
    fn python_version_asks_an_interpreter_with_no_pyvenv_cfg() {
        let tmp = tempfile::tempdir().unwrap();
        let py = stub_python(tmp.path(), "usr", "echo 3.11", None);
        assert_eq!(
            python_version(&py).map(|v| (v.major, v.minor)),
            Some((3, 11))
        );
    }

    /// #864 guard: no version is made up. A missing interpreter, one that
    /// prints something else, and a `pyvenv.cfg` without a version (with an
    /// interpreter that says nothing) all read as unknown.
    #[cfg(unix)]
    #[test]
    fn python_version_is_none_when_nothing_says() {
        let tmp = tempfile::tempdir().unwrap();
        assert_eq!(python_version(&tmp.path().join("nope/bin/python")), None);
        let chatty = stub_python(tmp.path(), "chatty", "echo Python", None);
        assert_eq!(python_version(&chatty), None);
        let bare_cfg = stub_python(
            tmp.path(),
            ".venv",
            "exit 0",
            Some("home = /usr/bin\ninclude-system-site-packages = false\n"),
        );
        assert_eq!(python_version(&bare_cfg), None);
    }
}