cargo.rs

  1use super::DapLocator;
  2use anyhow::{Result, anyhow};
  3use async_trait::async_trait;
  4use serde_json::Value;
  5use smol::{
  6    io::AsyncReadExt,
  7    process::{Command, Stdio},
  8};
  9use task::DebugTaskDefinition;
 10
 11pub(crate) struct CargoLocator;
 12
 13async fn find_best_executable(executables: &[String], test_name: &str) -> Option<String> {
 14    if executables.len() == 1 {
 15        return executables.first().cloned();
 16    }
 17    for executable in executables {
 18        let Some(mut child) = Command::new(&executable)
 19            .arg("--list")
 20            .stdout(Stdio::piped())
 21            .spawn()
 22            .ok()
 23        else {
 24            continue;
 25        };
 26        let mut test_lines = String::default();
 27        if let Some(mut stdout) = child.stdout.take() {
 28            stdout.read_to_string(&mut test_lines).await.ok();
 29            for line in test_lines.lines() {
 30                if line.contains(&test_name) {
 31                    return Some(executable.clone());
 32                }
 33            }
 34        }
 35    }
 36    None
 37}
 38#[async_trait]
 39impl DapLocator for CargoLocator {
 40    async fn run_locator(
 41        &self,
 42        mut debug_config: DebugTaskDefinition,
 43    ) -> Result<DebugTaskDefinition> {
 44        let Some(launch_config) = (match &mut debug_config.request {
 45            task::DebugRequest::Launch(launch_config) => 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
115        let Some(executable) = executable.or_else(|| executables.first().cloned()) else {
116            return Err(anyhow!("Couldn't get executable in cargo locator"));
117        };
118
119        launch_config.program = executable;
120
121        launch_config.args.clear();
122        if let Some(test_name) = test_name {
123            launch_config.args.push(test_name);
124        }
125        Ok(debug_config)
126    }
127}