use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use crate::dap::remote_attach::PyVersion;
const PYTHON_VERSION: &str = "3.14";
const JS_DEBUG_VERSION: &str = "v1.117.0";
const JS_DEBUG_SHA256: &str = "ad8d04ede9d4b75cc290fd5438a65047a06f786d04f604b6112485b36f090772";
const MAX_JS_DEBUG_BYTES: u64 = 64 * 1024 * 1024;
pub const DEBUGPY_MIN_PYTHON: PyVersion = PyVersion {
major: 3,
minor: 10,
patch: 0,
};
pub fn pyvenv_cfg(python: &Path) -> Option<PathBuf> {
let cfg = python.parent()?.parent()?.join("pyvenv.cfg");
cfg.is_file().then_some(cfg)
}
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)
}
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())
}
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);
}
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")?;
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)
}
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)
}
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()
})
}
fn debug_venv_python_in(home: &Path) -> PathBuf {
home.join(".croft")
.join("debug-venv")
.join("bin")
.join("python")
}
pub(crate) const SETUP_STEP_LIMIT: Duration = Duration::from_secs(300);
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}")),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Tooling {
Python,
Js,
}
impl Tooling {
pub(crate) fn preparing(self) -> &'static str {
match self {
Tooling::Python => "Setting up the Python debugger…",
Tooling::Js => "Setting up the JavaScript debugger…",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Ready {
Python(PathBuf),
Js { node: String, server: PathBuf },
}
pub(crate) trait DebugTooling: Send + Sync {
fn ready(&self, tooling: Tooling) -> Option<Ready>;
fn prepare(&self, tooling: Tooling) -> std::result::Result<(), String>;
}
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}"))
}
}
}
}
pub(crate) fn js_debug_dir() -> Option<PathBuf> {
let home = std::env::var_os("HOME")?;
Some(PathBuf::from(home).join(".croft").join("js-debug"))
}
fn js_debug_server_path(dir: &Path) -> PathBuf {
dir.join("js-debug").join("src").join("dapDebugServer.js")
}
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")
}
fn known_node() -> Option<String> {
if which("node") {
return Some(String::from("node"));
}
node_in(&crate::node::known_dir()?)
}
fn node_in(dir: &Path) -> Option<String> {
let node = dir.join("node");
crate::proc::find::runnable(&node).then(|| node.to_string_lossy().into_owned())
}
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))?
}
pub(crate) fn run_probe(
cmd: &mut Command,
timeout: Duration,
apart: crate::proc::Apart,
) -> Option<String> {
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())
}
pub(crate) const PROBE_TAIL: usize = 64 * 1024;
fn which(bin: &str) -> bool {
crate::proc::find::on_path(bin).is_some()
}
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);
}
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)?;
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)
}
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(())
}
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")
}
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));
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)
}
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('\'', "'\\''"))
}
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
}
pub fn go_on_path() -> bool {
crate::proc::find::go().is_some()
}
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)",
)
}
}
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::*;
#[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}");
}
}
#[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");
}
#[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();
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}"
);
}
}
#[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() {
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"));
assert!(
dlv_install_command(Path::new("/usr/local/go/bin/go"))
.contains("GOBIN=\"$HOME/.croft/servers/go\" \"/usr/local/go/bin/go\" install ")
);
}
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();
}
#[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");
}
#[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"
);
}
#[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));
}
#[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"
);
}
#[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
}
#[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))
);
}
#[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))
);
}
#[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);
}
}