cargo.rs

  1use super::DapLocator;
  2use anyhow::{Result, anyhow};
  3use async_trait::async_trait;
  4use dap::DebugAdapterConfig;
  5use serde_json::{Value, json};
  6use smol::{
  7    io::AsyncReadExt,
  8    process::{Command, Stdio},
  9};
 10use util::maybe;
 11
 12pub(super) struct CargoLocator;
 13
 14async fn find_best_executable(executables: &[String], test_name: &str) -> Option<String> {
 15    if executables.len() == 1 {
 16        return executables.first().cloned();
 17    }
 18    for executable in executables {
 19        let Some(mut child) = Command::new(&executable)
 20            .arg("--list")
 21            .stdout(Stdio::piped())
 22            .spawn()
 23            .ok()
 24        else {
 25            continue;
 26        };
 27        let mut test_lines = String::default();
 28        if let Some(mut stdout) = child.stdout.take() {
 29            stdout.read_to_string(&mut test_lines).await.ok();
 30            for line in test_lines.lines() {
 31                if line.contains(&test_name) {
 32                    return Some(executable.clone());
 33                }
 34            }
 35        }
 36    }
 37    None
 38}
 39#[async_trait]
 40impl DapLocator for CargoLocator {
 41    async fn run_locator(&self, debug_config: &mut DebugAdapterConfig) -> Result<()> {
 42        let Some(launch_config) = (match &mut debug_config.request {
 43            task::DebugRequestDisposition::UserConfigured(task::DebugRequestType::Launch(
 44                launch_config,
 45            )) => Some(launch_config),
 46            _ => None,
 47        }) else {
 48            return Err(anyhow!("Couldn't get launch config in locator"));
 49        };
 50
 51        let Some(cwd) = launch_config.cwd.clone() else {
 52            return Err(anyhow!(
 53                "Couldn't get cwd from debug config which is needed for locators"
 54            ));
 55        };
 56
 57        let mut child = Command::new("cargo")
 58            .args(&launch_config.args)
 59            .arg("--message-format=json")
 60            .current_dir(cwd)
 61            .stdout(Stdio::piped())
 62            .spawn()?;
 63
 64        let mut output = String::new();
 65        if let Some(mut stdout) = child.stdout.take() {
 66            stdout.read_to_string(&mut output).await?;
 67        }
 68
 69        let status = child.status().await?;
 70        if !status.success() {
 71            return Err(anyhow::anyhow!("Cargo command failed"));
 72        }
 73
 74        let executables = output
 75            .lines()
 76            .filter(|line| !line.trim().is_empty())
 77            .filter_map(|line| serde_json::from_str(line).ok())
 78            .filter_map(|json: Value| {
 79                json.get("executable")
 80                    .and_then(Value::as_str)
 81                    .map(String::from)
 82            })
 83            .collect::<Vec<_>>();
 84        if executables.is_empty() {
 85            return Err(anyhow!("Couldn't get executable in cargo locator"));
 86        };
 87
 88        let is_test = launch_config
 89            .args
 90            .first()
 91            .map_or(false, |arg| arg == "test");
 92
 93        let mut test_name = None;
 94        if is_test {
 95            if let Some(package_index) = launch_config
 96                .args
 97                .iter()
 98                .position(|arg| arg == "-p" || arg == "--package")
 99            {
100                test_name = launch_config
101                    .args
102                    .get(package_index + 2)
103                    .filter(|name| !name.starts_with("--"))
104                    .cloned();
105            }
106        }
107        let executable = {
108            if let Some(ref name) = test_name {
109                find_best_executable(&executables, &name).await
110            } else {
111                None
112            }
113        };
114        let Some(executable) = executable.or_else(|| executables.first().cloned()) else {
115            return Err(anyhow!("Couldn't get executable in cargo locator"));
116        };
117
118        launch_config.program = executable;
119
120        if debug_config.adapter == "LLDB" && debug_config.initialize_args.is_none() {
121            // Find Rust pretty-printers in current toolchain's sysroot
122            let cwd = launch_config.cwd.clone();
123            debug_config.initialize_args = maybe!(async move {
124                let cwd = cwd?;
125
126                let output = Command::new("rustc")
127                    .arg("--print")
128                    .arg("sysroot")
129                    .current_dir(cwd)
130                    .output()
131                    .await
132                    .ok()?;
133
134                if !output.status.success() {
135                    return None;
136                }
137
138                let sysroot_path = String::from_utf8(output.stdout).ok()?;
139                let sysroot_path = sysroot_path.trim_end();
140                let first_command = format!(
141                    r#"command script import "{sysroot_path}/lib/rustlib/etc/lldb_lookup.py"#
142                );
143                let second_command =
144                    format!(r#"command source -s 0 '{sysroot_path}/lib/rustlib/etc/lldb_commands"#);
145
146                Some(json!({"initCommands": [first_command, second_command]}))
147            })
148            .await;
149        }
150
151        launch_config.args.clear();
152        if let Some(test_name) = test_name {
153            launch_config.args.push(test_name);
154        }
155        Ok(())
156    }
157}